ExprConstant.cpp 583 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Expr constant evaluator.
  10. //
  11. // Constant expression evaluation produces four main results:
  12. //
  13. // * A success/failure flag indicating whether constant folding was successful.
  14. // This is the 'bool' return value used by most of the code in this file. A
  15. // 'false' return value indicates that constant folding has failed, and any
  16. // appropriate diagnostic has already been produced.
  17. //
  18. // * An evaluated result, valid only if constant folding has not failed.
  19. //
  20. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  21. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  22. // where it is possible to determine the evaluated result regardless.
  23. //
  24. // * A set of notes indicating why the evaluation was not a constant expression
  25. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  26. // too, why the expression could not be folded.
  27. //
  28. // If we are checking for a potential constant expression, failure to constant
  29. // fold a potential constant sub-expression will be indicated by a 'false'
  30. // return value (the expression could not be folded) and no diagnostic (the
  31. // expression is not necessarily non-constant).
  32. //
  33. //===----------------------------------------------------------------------===//
  34. #include "Interp/Context.h"
  35. #include "Interp/Frame.h"
  36. #include "Interp/State.h"
  37. #include "clang/AST/APValue.h"
  38. #include "clang/AST/ASTContext.h"
  39. #include "clang/AST/ASTDiagnostic.h"
  40. #include "clang/AST/ASTLambda.h"
  41. #include "clang/AST/Attr.h"
  42. #include "clang/AST/CXXInheritance.h"
  43. #include "clang/AST/CharUnits.h"
  44. #include "clang/AST/CurrentSourceLocExprScope.h"
  45. #include "clang/AST/Expr.h"
  46. #include "clang/AST/OSLog.h"
  47. #include "clang/AST/OptionalDiagnostic.h"
  48. #include "clang/AST/RecordLayout.h"
  49. #include "clang/AST/StmtVisitor.h"
  50. #include "clang/AST/TypeLoc.h"
  51. #include "clang/Basic/Builtins.h"
  52. #include "clang/Basic/TargetInfo.h"
  53. #include "llvm/ADT/APFixedPoint.h"
  54. #include "llvm/ADT/SmallBitVector.h"
  55. #include "llvm/Support/Debug.h"
  56. #include "llvm/Support/SaveAndRestore.h"
  57. #include "llvm/Support/TimeProfiler.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include <cstring>
  60. #include <functional>
  61. #include <optional>
  62. #define DEBUG_TYPE "exprconstant"
  63. using namespace clang;
  64. using llvm::APFixedPoint;
  65. using llvm::APInt;
  66. using llvm::APSInt;
  67. using llvm::APFloat;
  68. using llvm::FixedPointSemantics;
  69. namespace {
  70. struct LValue;
  71. class CallStackFrame;
  72. class EvalInfo;
  73. using SourceLocExprScopeGuard =
  74. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  75. static QualType getType(APValue::LValueBase B) {
  76. return B.getType();
  77. }
  78. /// Get an LValue path entry, which is known to not be an array index, as a
  79. /// field declaration.
  80. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  81. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  82. }
  83. /// Get an LValue path entry, which is known to not be an array index, as a
  84. /// base class declaration.
  85. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  86. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  87. }
  88. /// Determine whether this LValue path entry for a base class names a virtual
  89. /// base class.
  90. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  91. return E.getAsBaseOrMember().getInt();
  92. }
  93. /// Given an expression, determine the type used to store the result of
  94. /// evaluating that expression.
  95. static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
  96. if (E->isPRValue())
  97. return E->getType();
  98. return Ctx.getLValueReferenceType(E->getType());
  99. }
  100. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  101. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  102. if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
  103. return DirectCallee->getAttr<AllocSizeAttr>();
  104. if (const Decl *IndirectCallee = CE->getCalleeDecl())
  105. return IndirectCallee->getAttr<AllocSizeAttr>();
  106. return nullptr;
  107. }
  108. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  109. /// This will look through a single cast.
  110. ///
  111. /// Returns null if we couldn't unwrap a function with alloc_size.
  112. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  113. if (!E->getType()->isPointerType())
  114. return nullptr;
  115. E = E->IgnoreParens();
  116. // If we're doing a variable assignment from e.g. malloc(N), there will
  117. // probably be a cast of some kind. In exotic cases, we might also see a
  118. // top-level ExprWithCleanups. Ignore them either way.
  119. if (const auto *FE = dyn_cast<FullExpr>(E))
  120. E = FE->getSubExpr()->IgnoreParens();
  121. if (const auto *Cast = dyn_cast<CastExpr>(E))
  122. E = Cast->getSubExpr()->IgnoreParens();
  123. if (const auto *CE = dyn_cast<CallExpr>(E))
  124. return getAllocSizeAttr(CE) ? CE : nullptr;
  125. return nullptr;
  126. }
  127. /// Determines whether or not the given Base contains a call to a function
  128. /// with the alloc_size attribute.
  129. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  130. const auto *E = Base.dyn_cast<const Expr *>();
  131. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  132. }
  133. /// Determines whether the given kind of constant expression is only ever
  134. /// used for name mangling. If so, it's permitted to reference things that we
  135. /// can't generate code for (in particular, dllimported functions).
  136. static bool isForManglingOnly(ConstantExprKind Kind) {
  137. switch (Kind) {
  138. case ConstantExprKind::Normal:
  139. case ConstantExprKind::ClassTemplateArgument:
  140. case ConstantExprKind::ImmediateInvocation:
  141. // Note that non-type template arguments of class type are emitted as
  142. // template parameter objects.
  143. return false;
  144. case ConstantExprKind::NonClassTemplateArgument:
  145. return true;
  146. }
  147. llvm_unreachable("unknown ConstantExprKind");
  148. }
  149. static bool isTemplateArgument(ConstantExprKind Kind) {
  150. switch (Kind) {
  151. case ConstantExprKind::Normal:
  152. case ConstantExprKind::ImmediateInvocation:
  153. return false;
  154. case ConstantExprKind::ClassTemplateArgument:
  155. case ConstantExprKind::NonClassTemplateArgument:
  156. return true;
  157. }
  158. llvm_unreachable("unknown ConstantExprKind");
  159. }
  160. /// The bound to claim that an array of unknown bound has.
  161. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  162. /// to an arbitrary value that's likely to loudly break things if it's used.
  163. static const uint64_t AssumedSizeForUnsizedArray =
  164. std::numeric_limits<uint64_t>::max() / 2;
  165. /// Determines if an LValue with the given LValueBase will have an unsized
  166. /// array in its designator.
  167. /// Find the path length and type of the most-derived subobject in the given
  168. /// path, and find the size of the containing array, if any.
  169. static unsigned
  170. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  171. ArrayRef<APValue::LValuePathEntry> Path,
  172. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  173. bool &FirstEntryIsUnsizedArray) {
  174. // This only accepts LValueBases from APValues, and APValues don't support
  175. // arrays that lack size info.
  176. assert(!isBaseAnAllocSizeCall(Base) &&
  177. "Unsized arrays shouldn't appear here");
  178. unsigned MostDerivedLength = 0;
  179. Type = getType(Base);
  180. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  181. if (Type->isArrayType()) {
  182. const ArrayType *AT = Ctx.getAsArrayType(Type);
  183. Type = AT->getElementType();
  184. MostDerivedLength = I + 1;
  185. IsArray = true;
  186. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  187. ArraySize = CAT->getSize().getZExtValue();
  188. } else {
  189. assert(I == 0 && "unexpected unsized array designator");
  190. FirstEntryIsUnsizedArray = true;
  191. ArraySize = AssumedSizeForUnsizedArray;
  192. }
  193. } else if (Type->isAnyComplexType()) {
  194. const ComplexType *CT = Type->castAs<ComplexType>();
  195. Type = CT->getElementType();
  196. ArraySize = 2;
  197. MostDerivedLength = I + 1;
  198. IsArray = true;
  199. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  200. Type = FD->getType();
  201. ArraySize = 0;
  202. MostDerivedLength = I + 1;
  203. IsArray = false;
  204. } else {
  205. // Path[I] describes a base class.
  206. ArraySize = 0;
  207. IsArray = false;
  208. }
  209. }
  210. return MostDerivedLength;
  211. }
  212. /// A path from a glvalue to a subobject of that glvalue.
  213. struct SubobjectDesignator {
  214. /// True if the subobject was named in a manner not supported by C++11. Such
  215. /// lvalues can still be folded, but they are not core constant expressions
  216. /// and we cannot perform lvalue-to-rvalue conversions on them.
  217. unsigned Invalid : 1;
  218. /// Is this a pointer one past the end of an object?
  219. unsigned IsOnePastTheEnd : 1;
  220. /// Indicator of whether the first entry is an unsized array.
  221. unsigned FirstEntryIsAnUnsizedArray : 1;
  222. /// Indicator of whether the most-derived object is an array element.
  223. unsigned MostDerivedIsArrayElement : 1;
  224. /// The length of the path to the most-derived object of which this is a
  225. /// subobject.
  226. unsigned MostDerivedPathLength : 28;
  227. /// The size of the array of which the most-derived object is an element.
  228. /// This will always be 0 if the most-derived object is not an array
  229. /// element. 0 is not an indicator of whether or not the most-derived object
  230. /// is an array, however, because 0-length arrays are allowed.
  231. ///
  232. /// If the current array is an unsized array, the value of this is
  233. /// undefined.
  234. uint64_t MostDerivedArraySize;
  235. /// The type of the most derived object referred to by this address.
  236. QualType MostDerivedType;
  237. typedef APValue::LValuePathEntry PathEntry;
  238. /// The entries on the path from the glvalue to the designated subobject.
  239. SmallVector<PathEntry, 8> Entries;
  240. SubobjectDesignator() : Invalid(true) {}
  241. explicit SubobjectDesignator(QualType T)
  242. : Invalid(false), IsOnePastTheEnd(false),
  243. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  244. MostDerivedPathLength(0), MostDerivedArraySize(0),
  245. MostDerivedType(T) {}
  246. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  247. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  248. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  249. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  250. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  251. if (!Invalid) {
  252. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  253. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  254. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  255. if (V.getLValueBase()) {
  256. bool IsArray = false;
  257. bool FirstIsUnsizedArray = false;
  258. MostDerivedPathLength = findMostDerivedSubobject(
  259. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  260. MostDerivedType, IsArray, FirstIsUnsizedArray);
  261. MostDerivedIsArrayElement = IsArray;
  262. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  263. }
  264. }
  265. }
  266. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  267. unsigned NewLength) {
  268. if (Invalid)
  269. return;
  270. assert(Base && "cannot truncate path for null pointer");
  271. assert(NewLength <= Entries.size() && "not a truncation");
  272. if (NewLength == Entries.size())
  273. return;
  274. Entries.resize(NewLength);
  275. bool IsArray = false;
  276. bool FirstIsUnsizedArray = false;
  277. MostDerivedPathLength = findMostDerivedSubobject(
  278. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  279. FirstIsUnsizedArray);
  280. MostDerivedIsArrayElement = IsArray;
  281. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  282. }
  283. void setInvalid() {
  284. Invalid = true;
  285. Entries.clear();
  286. }
  287. /// Determine whether the most derived subobject is an array without a
  288. /// known bound.
  289. bool isMostDerivedAnUnsizedArray() const {
  290. assert(!Invalid && "Calling this makes no sense on invalid designators");
  291. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  292. }
  293. /// Determine what the most derived array's size is. Results in an assertion
  294. /// failure if the most derived array lacks a size.
  295. uint64_t getMostDerivedArraySize() const {
  296. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  297. return MostDerivedArraySize;
  298. }
  299. /// Determine whether this is a one-past-the-end pointer.
  300. bool isOnePastTheEnd() const {
  301. assert(!Invalid);
  302. if (IsOnePastTheEnd)
  303. return true;
  304. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  305. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  306. MostDerivedArraySize)
  307. return true;
  308. return false;
  309. }
  310. /// Get the range of valid index adjustments in the form
  311. /// {maximum value that can be subtracted from this pointer,
  312. /// maximum value that can be added to this pointer}
  313. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  314. if (Invalid || isMostDerivedAnUnsizedArray())
  315. return {0, 0};
  316. // [expr.add]p4: For the purposes of these operators, a pointer to a
  317. // nonarray object behaves the same as a pointer to the first element of
  318. // an array of length one with the type of the object as its element type.
  319. bool IsArray = MostDerivedPathLength == Entries.size() &&
  320. MostDerivedIsArrayElement;
  321. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  322. : (uint64_t)IsOnePastTheEnd;
  323. uint64_t ArraySize =
  324. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  325. return {ArrayIndex, ArraySize - ArrayIndex};
  326. }
  327. /// Check that this refers to a valid subobject.
  328. bool isValidSubobject() const {
  329. if (Invalid)
  330. return false;
  331. return !isOnePastTheEnd();
  332. }
  333. /// Check that this refers to a valid subobject, and if not, produce a
  334. /// relevant diagnostic and set the designator as invalid.
  335. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  336. /// Get the type of the designated object.
  337. QualType getType(ASTContext &Ctx) const {
  338. assert(!Invalid && "invalid designator has no subobject type");
  339. return MostDerivedPathLength == Entries.size()
  340. ? MostDerivedType
  341. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  342. }
  343. /// Update this designator to refer to the first element within this array.
  344. void addArrayUnchecked(const ConstantArrayType *CAT) {
  345. Entries.push_back(PathEntry::ArrayIndex(0));
  346. // This is a most-derived object.
  347. MostDerivedType = CAT->getElementType();
  348. MostDerivedIsArrayElement = true;
  349. MostDerivedArraySize = CAT->getSize().getZExtValue();
  350. MostDerivedPathLength = Entries.size();
  351. }
  352. /// Update this designator to refer to the first element within the array of
  353. /// elements of type T. This is an array of unknown size.
  354. void addUnsizedArrayUnchecked(QualType ElemTy) {
  355. Entries.push_back(PathEntry::ArrayIndex(0));
  356. MostDerivedType = ElemTy;
  357. MostDerivedIsArrayElement = true;
  358. // The value in MostDerivedArraySize is undefined in this case. So, set it
  359. // to an arbitrary value that's likely to loudly break things if it's
  360. // used.
  361. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  362. MostDerivedPathLength = Entries.size();
  363. }
  364. /// Update this designator to refer to the given base or member of this
  365. /// object.
  366. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  367. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  368. // If this isn't a base class, it's a new most-derived object.
  369. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  370. MostDerivedType = FD->getType();
  371. MostDerivedIsArrayElement = false;
  372. MostDerivedArraySize = 0;
  373. MostDerivedPathLength = Entries.size();
  374. }
  375. }
  376. /// Update this designator to refer to the given complex component.
  377. void addComplexUnchecked(QualType EltTy, bool Imag) {
  378. Entries.push_back(PathEntry::ArrayIndex(Imag));
  379. // This is technically a most-derived object, though in practice this
  380. // is unlikely to matter.
  381. MostDerivedType = EltTy;
  382. MostDerivedIsArrayElement = true;
  383. MostDerivedArraySize = 2;
  384. MostDerivedPathLength = Entries.size();
  385. }
  386. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  387. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  388. const APSInt &N);
  389. /// Add N to the address of this subobject.
  390. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  391. if (Invalid || !N) return;
  392. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  393. if (isMostDerivedAnUnsizedArray()) {
  394. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  395. // Can't verify -- trust that the user is doing the right thing (or if
  396. // not, trust that the caller will catch the bad behavior).
  397. // FIXME: Should we reject if this overflows, at least?
  398. Entries.back() = PathEntry::ArrayIndex(
  399. Entries.back().getAsArrayIndex() + TruncatedN);
  400. return;
  401. }
  402. // [expr.add]p4: For the purposes of these operators, a pointer to a
  403. // nonarray object behaves the same as a pointer to the first element of
  404. // an array of length one with the type of the object as its element type.
  405. bool IsArray = MostDerivedPathLength == Entries.size() &&
  406. MostDerivedIsArrayElement;
  407. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  408. : (uint64_t)IsOnePastTheEnd;
  409. uint64_t ArraySize =
  410. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  411. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  412. // Calculate the actual index in a wide enough type, so we can include
  413. // it in the note.
  414. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  415. (llvm::APInt&)N += ArrayIndex;
  416. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  417. diagnosePointerArithmetic(Info, E, N);
  418. setInvalid();
  419. return;
  420. }
  421. ArrayIndex += TruncatedN;
  422. assert(ArrayIndex <= ArraySize &&
  423. "bounds check succeeded for out-of-bounds index");
  424. if (IsArray)
  425. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  426. else
  427. IsOnePastTheEnd = (ArrayIndex != 0);
  428. }
  429. };
  430. /// A scope at the end of which an object can need to be destroyed.
  431. enum class ScopeKind {
  432. Block,
  433. FullExpression,
  434. Call
  435. };
  436. /// A reference to a particular call and its arguments.
  437. struct CallRef {
  438. CallRef() : OrigCallee(), CallIndex(0), Version() {}
  439. CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
  440. : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
  441. explicit operator bool() const { return OrigCallee; }
  442. /// Get the parameter that the caller initialized, corresponding to the
  443. /// given parameter in the callee.
  444. const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
  445. return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
  446. : PVD;
  447. }
  448. /// The callee at the point where the arguments were evaluated. This might
  449. /// be different from the actual callee (a different redeclaration, or a
  450. /// virtual override), but this function's parameters are the ones that
  451. /// appear in the parameter map.
  452. const FunctionDecl *OrigCallee;
  453. /// The call index of the frame that holds the argument values.
  454. unsigned CallIndex;
  455. /// The version of the parameters corresponding to this call.
  456. unsigned Version;
  457. };
  458. /// A stack frame in the constexpr call stack.
  459. class CallStackFrame : public interp::Frame {
  460. public:
  461. EvalInfo &Info;
  462. /// Parent - The caller of this stack frame.
  463. CallStackFrame *Caller;
  464. /// Callee - The function which was called.
  465. const FunctionDecl *Callee;
  466. /// This - The binding for the this pointer in this call, if any.
  467. const LValue *This;
  468. /// Information on how to find the arguments to this call. Our arguments
  469. /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
  470. /// key and this value as the version.
  471. CallRef Arguments;
  472. /// Source location information about the default argument or default
  473. /// initializer expression we're evaluating, if any.
  474. CurrentSourceLocExprScope CurSourceLocExprScope;
  475. // Note that we intentionally use std::map here so that references to
  476. // values are stable.
  477. typedef std::pair<const void *, unsigned> MapKeyTy;
  478. typedef std::map<MapKeyTy, APValue> MapTy;
  479. /// Temporaries - Temporary lvalues materialized within this stack frame.
  480. MapTy Temporaries;
  481. /// CallLoc - The location of the call expression for this call.
  482. SourceLocation CallLoc;
  483. /// Index - The call index of this call.
  484. unsigned Index;
  485. /// The stack of integers for tracking version numbers for temporaries.
  486. SmallVector<unsigned, 2> TempVersionStack = {1};
  487. unsigned CurTempVersion = TempVersionStack.back();
  488. unsigned getTempVersion() const { return TempVersionStack.back(); }
  489. void pushTempVersion() {
  490. TempVersionStack.push_back(++CurTempVersion);
  491. }
  492. void popTempVersion() {
  493. TempVersionStack.pop_back();
  494. }
  495. CallRef createCall(const FunctionDecl *Callee) {
  496. return {Callee, Index, ++CurTempVersion};
  497. }
  498. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  499. // on the overall stack usage of deeply-recursing constexpr evaluations.
  500. // (We should cache this map rather than recomputing it repeatedly.)
  501. // But let's try this and see how it goes; we can look into caching the map
  502. // as a later change.
  503. /// LambdaCaptureFields - Mapping from captured variables/this to
  504. /// corresponding data members in the closure class.
  505. llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
  506. FieldDecl *LambdaThisCaptureField;
  507. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  508. const FunctionDecl *Callee, const LValue *This,
  509. CallRef Arguments);
  510. ~CallStackFrame();
  511. // Return the temporary for Key whose version number is Version.
  512. APValue *getTemporary(const void *Key, unsigned Version) {
  513. MapKeyTy KV(Key, Version);
  514. auto LB = Temporaries.lower_bound(KV);
  515. if (LB != Temporaries.end() && LB->first == KV)
  516. return &LB->second;
  517. return nullptr;
  518. }
  519. // Return the current temporary for Key in the map.
  520. APValue *getCurrentTemporary(const void *Key) {
  521. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  522. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  523. return &std::prev(UB)->second;
  524. return nullptr;
  525. }
  526. // Return the version number of the current temporary for Key.
  527. unsigned getCurrentTemporaryVersion(const void *Key) const {
  528. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  529. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  530. return std::prev(UB)->first.second;
  531. return 0;
  532. }
  533. /// Allocate storage for an object of type T in this stack frame.
  534. /// Populates LV with a handle to the created object. Key identifies
  535. /// the temporary within the stack frame, and must not be reused without
  536. /// bumping the temporary version number.
  537. template<typename KeyT>
  538. APValue &createTemporary(const KeyT *Key, QualType T,
  539. ScopeKind Scope, LValue &LV);
  540. /// Allocate storage for a parameter of a function call made in this frame.
  541. APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
  542. void describe(llvm::raw_ostream &OS) override;
  543. Frame *getCaller() const override { return Caller; }
  544. SourceLocation getCallLocation() const override { return CallLoc; }
  545. const FunctionDecl *getCallee() const override { return Callee; }
  546. bool isStdFunction() const {
  547. for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
  548. if (DC->isStdNamespace())
  549. return true;
  550. return false;
  551. }
  552. private:
  553. APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
  554. ScopeKind Scope);
  555. };
  556. /// Temporarily override 'this'.
  557. class ThisOverrideRAII {
  558. public:
  559. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  560. : Frame(Frame), OldThis(Frame.This) {
  561. if (Enable)
  562. Frame.This = NewThis;
  563. }
  564. ~ThisOverrideRAII() {
  565. Frame.This = OldThis;
  566. }
  567. private:
  568. CallStackFrame &Frame;
  569. const LValue *OldThis;
  570. };
  571. // A shorthand time trace scope struct, prints source range, for example
  572. // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
  573. class ExprTimeTraceScope {
  574. public:
  575. ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
  576. : TimeScope(Name, [E, &Ctx] {
  577. return E->getSourceRange().printToString(Ctx.getSourceManager());
  578. }) {}
  579. private:
  580. llvm::TimeTraceScope TimeScope;
  581. };
  582. }
  583. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  584. const LValue &This, QualType ThisType);
  585. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  586. APValue::LValueBase LVBase, APValue &Value,
  587. QualType T);
  588. namespace {
  589. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  590. class Cleanup {
  591. llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
  592. APValue::LValueBase Base;
  593. QualType T;
  594. public:
  595. Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
  596. ScopeKind Scope)
  597. : Value(Val, Scope), Base(Base), T(T) {}
  598. /// Determine whether this cleanup should be performed at the end of the
  599. /// given kind of scope.
  600. bool isDestroyedAtEndOf(ScopeKind K) const {
  601. return (int)Value.getInt() >= (int)K;
  602. }
  603. bool endLifetime(EvalInfo &Info, bool RunDestructors) {
  604. if (RunDestructors) {
  605. SourceLocation Loc;
  606. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
  607. Loc = VD->getLocation();
  608. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  609. Loc = E->getExprLoc();
  610. return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
  611. }
  612. *Value.getPointer() = APValue();
  613. return true;
  614. }
  615. bool hasSideEffect() {
  616. return T.isDestructedType();
  617. }
  618. };
  619. /// A reference to an object whose construction we are currently evaluating.
  620. struct ObjectUnderConstruction {
  621. APValue::LValueBase Base;
  622. ArrayRef<APValue::LValuePathEntry> Path;
  623. friend bool operator==(const ObjectUnderConstruction &LHS,
  624. const ObjectUnderConstruction &RHS) {
  625. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  626. }
  627. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  628. return llvm::hash_combine(Obj.Base, Obj.Path);
  629. }
  630. };
  631. enum class ConstructionPhase {
  632. None,
  633. Bases,
  634. AfterBases,
  635. AfterFields,
  636. Destroying,
  637. DestroyingBases
  638. };
  639. }
  640. namespace llvm {
  641. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  642. using Base = DenseMapInfo<APValue::LValueBase>;
  643. static ObjectUnderConstruction getEmptyKey() {
  644. return {Base::getEmptyKey(), {}}; }
  645. static ObjectUnderConstruction getTombstoneKey() {
  646. return {Base::getTombstoneKey(), {}};
  647. }
  648. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  649. return hash_value(Object);
  650. }
  651. static bool isEqual(const ObjectUnderConstruction &LHS,
  652. const ObjectUnderConstruction &RHS) {
  653. return LHS == RHS;
  654. }
  655. };
  656. }
  657. namespace {
  658. /// A dynamically-allocated heap object.
  659. struct DynAlloc {
  660. /// The value of this heap-allocated object.
  661. APValue Value;
  662. /// The allocating expression; used for diagnostics. Either a CXXNewExpr
  663. /// or a CallExpr (the latter is for direct calls to operator new inside
  664. /// std::allocator<T>::allocate).
  665. const Expr *AllocExpr = nullptr;
  666. enum Kind {
  667. New,
  668. ArrayNew,
  669. StdAllocator
  670. };
  671. /// Get the kind of the allocation. This must match between allocation
  672. /// and deallocation.
  673. Kind getKind() const {
  674. if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
  675. return NE->isArray() ? ArrayNew : New;
  676. assert(isa<CallExpr>(AllocExpr));
  677. return StdAllocator;
  678. }
  679. };
  680. struct DynAllocOrder {
  681. bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
  682. return L.getIndex() < R.getIndex();
  683. }
  684. };
  685. /// EvalInfo - This is a private struct used by the evaluator to capture
  686. /// information about a subexpression as it is folded. It retains information
  687. /// about the AST context, but also maintains information about the folded
  688. /// expression.
  689. ///
  690. /// If an expression could be evaluated, it is still possible it is not a C
  691. /// "integer constant expression" or constant expression. If not, this struct
  692. /// captures information about how and why not.
  693. ///
  694. /// One bit of information passed *into* the request for constant folding
  695. /// indicates whether the subexpression is "evaluated" or not according to C
  696. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  697. /// evaluate the expression regardless of what the RHS is, but C only allows
  698. /// certain things in certain situations.
  699. class EvalInfo : public interp::State {
  700. public:
  701. ASTContext &Ctx;
  702. /// EvalStatus - Contains information about the evaluation.
  703. Expr::EvalStatus &EvalStatus;
  704. /// CurrentCall - The top of the constexpr call stack.
  705. CallStackFrame *CurrentCall;
  706. /// CallStackDepth - The number of calls in the call stack right now.
  707. unsigned CallStackDepth;
  708. /// NextCallIndex - The next call index to assign.
  709. unsigned NextCallIndex;
  710. /// StepsLeft - The remaining number of evaluation steps we're permitted
  711. /// to perform. This is essentially a limit for the number of statements
  712. /// we will evaluate.
  713. unsigned StepsLeft;
  714. /// Enable the experimental new constant interpreter. If an expression is
  715. /// not supported by the interpreter, an error is triggered.
  716. bool EnableNewConstInterp;
  717. /// BottomFrame - The frame in which evaluation started. This must be
  718. /// initialized after CurrentCall and CallStackDepth.
  719. CallStackFrame BottomFrame;
  720. /// A stack of values whose lifetimes end at the end of some surrounding
  721. /// evaluation frame.
  722. llvm::SmallVector<Cleanup, 16> CleanupStack;
  723. /// EvaluatingDecl - This is the declaration whose initializer is being
  724. /// evaluated, if any.
  725. APValue::LValueBase EvaluatingDecl;
  726. enum class EvaluatingDeclKind {
  727. None,
  728. /// We're evaluating the construction of EvaluatingDecl.
  729. Ctor,
  730. /// We're evaluating the destruction of EvaluatingDecl.
  731. Dtor,
  732. };
  733. EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
  734. /// EvaluatingDeclValue - This is the value being constructed for the
  735. /// declaration whose initializer is being evaluated, if any.
  736. APValue *EvaluatingDeclValue;
  737. /// Set of objects that are currently being constructed.
  738. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  739. ObjectsUnderConstruction;
  740. /// Current heap allocations, along with the location where each was
  741. /// allocated. We use std::map here because we need stable addresses
  742. /// for the stored APValues.
  743. std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
  744. /// The number of heap allocations performed so far in this evaluation.
  745. unsigned NumHeapAllocs = 0;
  746. struct EvaluatingConstructorRAII {
  747. EvalInfo &EI;
  748. ObjectUnderConstruction Object;
  749. bool DidInsert;
  750. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  751. bool HasBases)
  752. : EI(EI), Object(Object) {
  753. DidInsert =
  754. EI.ObjectsUnderConstruction
  755. .insert({Object, HasBases ? ConstructionPhase::Bases
  756. : ConstructionPhase::AfterBases})
  757. .second;
  758. }
  759. void finishedConstructingBases() {
  760. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  761. }
  762. void finishedConstructingFields() {
  763. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
  764. }
  765. ~EvaluatingConstructorRAII() {
  766. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  767. }
  768. };
  769. struct EvaluatingDestructorRAII {
  770. EvalInfo &EI;
  771. ObjectUnderConstruction Object;
  772. bool DidInsert;
  773. EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
  774. : EI(EI), Object(Object) {
  775. DidInsert = EI.ObjectsUnderConstruction
  776. .insert({Object, ConstructionPhase::Destroying})
  777. .second;
  778. }
  779. void startedDestroyingBases() {
  780. EI.ObjectsUnderConstruction[Object] =
  781. ConstructionPhase::DestroyingBases;
  782. }
  783. ~EvaluatingDestructorRAII() {
  784. if (DidInsert)
  785. EI.ObjectsUnderConstruction.erase(Object);
  786. }
  787. };
  788. ConstructionPhase
  789. isEvaluatingCtorDtor(APValue::LValueBase Base,
  790. ArrayRef<APValue::LValuePathEntry> Path) {
  791. return ObjectsUnderConstruction.lookup({Base, Path});
  792. }
  793. /// If we're currently speculatively evaluating, the outermost call stack
  794. /// depth at which we can mutate state, otherwise 0.
  795. unsigned SpeculativeEvaluationDepth = 0;
  796. /// The current array initialization index, if we're performing array
  797. /// initialization.
  798. uint64_t ArrayInitIndex = -1;
  799. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  800. /// notes attached to it will also be stored, otherwise they will not be.
  801. bool HasActiveDiagnostic;
  802. /// Have we emitted a diagnostic explaining why we couldn't constant
  803. /// fold (not just why it's not strictly a constant expression)?
  804. bool HasFoldFailureDiagnostic;
  805. /// Whether we're checking that an expression is a potential constant
  806. /// expression. If so, do not fail on constructs that could become constant
  807. /// later on (such as a use of an undefined global).
  808. bool CheckingPotentialConstantExpression = false;
  809. /// Whether we're checking for an expression that has undefined behavior.
  810. /// If so, we will produce warnings if we encounter an operation that is
  811. /// always undefined.
  812. ///
  813. /// Note that we still need to evaluate the expression normally when this
  814. /// is set; this is used when evaluating ICEs in C.
  815. bool CheckingForUndefinedBehavior = false;
  816. enum EvaluationMode {
  817. /// Evaluate as a constant expression. Stop if we find that the expression
  818. /// is not a constant expression.
  819. EM_ConstantExpression,
  820. /// Evaluate as a constant expression. Stop if we find that the expression
  821. /// is not a constant expression. Some expressions can be retried in the
  822. /// optimizer if we don't constant fold them here, but in an unevaluated
  823. /// context we try to fold them immediately since the optimizer never
  824. /// gets a chance to look at it.
  825. EM_ConstantExpressionUnevaluated,
  826. /// Fold the expression to a constant. Stop if we hit a side-effect that
  827. /// we can't model.
  828. EM_ConstantFold,
  829. /// Evaluate in any way we know how. Don't worry about side-effects that
  830. /// can't be modeled.
  831. EM_IgnoreSideEffects,
  832. } EvalMode;
  833. /// Are we checking whether the expression is a potential constant
  834. /// expression?
  835. bool checkingPotentialConstantExpression() const override {
  836. return CheckingPotentialConstantExpression;
  837. }
  838. /// Are we checking an expression for overflow?
  839. // FIXME: We should check for any kind of undefined or suspicious behavior
  840. // in such constructs, not just overflow.
  841. bool checkingForUndefinedBehavior() const override {
  842. return CheckingForUndefinedBehavior;
  843. }
  844. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  845. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  846. CallStackDepth(0), NextCallIndex(1),
  847. StepsLeft(C.getLangOpts().ConstexprStepLimit),
  848. EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
  849. BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
  850. EvaluatingDecl((const ValueDecl *)nullptr),
  851. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  852. HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
  853. ~EvalInfo() {
  854. discardCleanups();
  855. }
  856. ASTContext &getCtx() const override { return Ctx; }
  857. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
  858. EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
  859. EvaluatingDecl = Base;
  860. IsEvaluatingDecl = EDK;
  861. EvaluatingDeclValue = &Value;
  862. }
  863. bool CheckCallLimit(SourceLocation Loc) {
  864. // Don't perform any constexpr calls (other than the call we're checking)
  865. // when checking a potential constant expression.
  866. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  867. return false;
  868. if (NextCallIndex == 0) {
  869. // NextCallIndex has wrapped around.
  870. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  871. return false;
  872. }
  873. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  874. return true;
  875. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  876. << getLangOpts().ConstexprCallDepth;
  877. return false;
  878. }
  879. std::pair<CallStackFrame *, unsigned>
  880. getCallFrameAndDepth(unsigned CallIndex) {
  881. assert(CallIndex && "no call index in getCallFrameAndDepth");
  882. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  883. // be null in this loop.
  884. unsigned Depth = CallStackDepth;
  885. CallStackFrame *Frame = CurrentCall;
  886. while (Frame->Index > CallIndex) {
  887. Frame = Frame->Caller;
  888. --Depth;
  889. }
  890. if (Frame->Index == CallIndex)
  891. return {Frame, Depth};
  892. return {nullptr, 0};
  893. }
  894. bool nextStep(const Stmt *S) {
  895. if (!StepsLeft) {
  896. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  897. return false;
  898. }
  899. --StepsLeft;
  900. return true;
  901. }
  902. APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
  903. std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
  904. std::optional<DynAlloc *> Result;
  905. auto It = HeapAllocs.find(DA);
  906. if (It != HeapAllocs.end())
  907. Result = &It->second;
  908. return Result;
  909. }
  910. /// Get the allocated storage for the given parameter of the given call.
  911. APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
  912. CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
  913. return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
  914. : nullptr;
  915. }
  916. /// Information about a stack frame for std::allocator<T>::[de]allocate.
  917. struct StdAllocatorCaller {
  918. unsigned FrameIndex;
  919. QualType ElemType;
  920. explicit operator bool() const { return FrameIndex != 0; };
  921. };
  922. StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
  923. for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
  924. Call = Call->Caller) {
  925. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
  926. if (!MD)
  927. continue;
  928. const IdentifierInfo *FnII = MD->getIdentifier();
  929. if (!FnII || !FnII->isStr(FnName))
  930. continue;
  931. const auto *CTSD =
  932. dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
  933. if (!CTSD)
  934. continue;
  935. const IdentifierInfo *ClassII = CTSD->getIdentifier();
  936. const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
  937. if (CTSD->isInStdNamespace() && ClassII &&
  938. ClassII->isStr("allocator") && TAL.size() >= 1 &&
  939. TAL[0].getKind() == TemplateArgument::Type)
  940. return {Call->Index, TAL[0].getAsType()};
  941. }
  942. return {};
  943. }
  944. void performLifetimeExtension() {
  945. // Disable the cleanups for lifetime-extended temporaries.
  946. llvm::erase_if(CleanupStack, [](Cleanup &C) {
  947. return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
  948. });
  949. }
  950. /// Throw away any remaining cleanups at the end of evaluation. If any
  951. /// cleanups would have had a side-effect, note that as an unmodeled
  952. /// side-effect and return false. Otherwise, return true.
  953. bool discardCleanups() {
  954. for (Cleanup &C : CleanupStack) {
  955. if (C.hasSideEffect() && !noteSideEffect()) {
  956. CleanupStack.clear();
  957. return false;
  958. }
  959. }
  960. CleanupStack.clear();
  961. return true;
  962. }
  963. private:
  964. interp::Frame *getCurrentFrame() override { return CurrentCall; }
  965. const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
  966. bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
  967. void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
  968. void setFoldFailureDiagnostic(bool Flag) override {
  969. HasFoldFailureDiagnostic = Flag;
  970. }
  971. Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
  972. // If we have a prior diagnostic, it will be noting that the expression
  973. // isn't a constant expression. This diagnostic is more important,
  974. // unless we require this evaluation to produce a constant expression.
  975. //
  976. // FIXME: We might want to show both diagnostics to the user in
  977. // EM_ConstantFold mode.
  978. bool hasPriorDiagnostic() override {
  979. if (!EvalStatus.Diag->empty()) {
  980. switch (EvalMode) {
  981. case EM_ConstantFold:
  982. case EM_IgnoreSideEffects:
  983. if (!HasFoldFailureDiagnostic)
  984. break;
  985. // We've already failed to fold something. Keep that diagnostic.
  986. [[fallthrough]];
  987. case EM_ConstantExpression:
  988. case EM_ConstantExpressionUnevaluated:
  989. setActiveDiagnostic(false);
  990. return true;
  991. }
  992. }
  993. return false;
  994. }
  995. unsigned getCallStackDepth() override { return CallStackDepth; }
  996. public:
  997. /// Should we continue evaluation after encountering a side-effect that we
  998. /// couldn't model?
  999. bool keepEvaluatingAfterSideEffect() {
  1000. switch (EvalMode) {
  1001. case EM_IgnoreSideEffects:
  1002. return true;
  1003. case EM_ConstantExpression:
  1004. case EM_ConstantExpressionUnevaluated:
  1005. case EM_ConstantFold:
  1006. // By default, assume any side effect might be valid in some other
  1007. // evaluation of this expression from a different context.
  1008. return checkingPotentialConstantExpression() ||
  1009. checkingForUndefinedBehavior();
  1010. }
  1011. llvm_unreachable("Missed EvalMode case");
  1012. }
  1013. /// Note that we have had a side-effect, and determine whether we should
  1014. /// keep evaluating.
  1015. bool noteSideEffect() {
  1016. EvalStatus.HasSideEffects = true;
  1017. return keepEvaluatingAfterSideEffect();
  1018. }
  1019. /// Should we continue evaluation after encountering undefined behavior?
  1020. bool keepEvaluatingAfterUndefinedBehavior() {
  1021. switch (EvalMode) {
  1022. case EM_IgnoreSideEffects:
  1023. case EM_ConstantFold:
  1024. return true;
  1025. case EM_ConstantExpression:
  1026. case EM_ConstantExpressionUnevaluated:
  1027. return checkingForUndefinedBehavior();
  1028. }
  1029. llvm_unreachable("Missed EvalMode case");
  1030. }
  1031. /// Note that we hit something that was technically undefined behavior, but
  1032. /// that we can evaluate past it (such as signed overflow or floating-point
  1033. /// division by zero.)
  1034. bool noteUndefinedBehavior() override {
  1035. EvalStatus.HasUndefinedBehavior = true;
  1036. return keepEvaluatingAfterUndefinedBehavior();
  1037. }
  1038. /// Should we continue evaluation as much as possible after encountering a
  1039. /// construct which can't be reduced to a value?
  1040. bool keepEvaluatingAfterFailure() const override {
  1041. if (!StepsLeft)
  1042. return false;
  1043. switch (EvalMode) {
  1044. case EM_ConstantExpression:
  1045. case EM_ConstantExpressionUnevaluated:
  1046. case EM_ConstantFold:
  1047. case EM_IgnoreSideEffects:
  1048. return checkingPotentialConstantExpression() ||
  1049. checkingForUndefinedBehavior();
  1050. }
  1051. llvm_unreachable("Missed EvalMode case");
  1052. }
  1053. /// Notes that we failed to evaluate an expression that other expressions
  1054. /// directly depend on, and determine if we should keep evaluating. This
  1055. /// should only be called if we actually intend to keep evaluating.
  1056. ///
  1057. /// Call noteSideEffect() instead if we may be able to ignore the value that
  1058. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  1059. ///
  1060. /// (Foo(), 1) // use noteSideEffect
  1061. /// (Foo() || true) // use noteSideEffect
  1062. /// Foo() + 1 // use noteFailure
  1063. [[nodiscard]] bool noteFailure() {
  1064. // Failure when evaluating some expression often means there is some
  1065. // subexpression whose evaluation was skipped. Therefore, (because we
  1066. // don't track whether we skipped an expression when unwinding after an
  1067. // evaluation failure) every evaluation failure that bubbles up from a
  1068. // subexpression implies that a side-effect has potentially happened. We
  1069. // skip setting the HasSideEffects flag to true until we decide to
  1070. // continue evaluating after that point, which happens here.
  1071. bool KeepGoing = keepEvaluatingAfterFailure();
  1072. EvalStatus.HasSideEffects |= KeepGoing;
  1073. return KeepGoing;
  1074. }
  1075. class ArrayInitLoopIndex {
  1076. EvalInfo &Info;
  1077. uint64_t OuterIndex;
  1078. public:
  1079. ArrayInitLoopIndex(EvalInfo &Info)
  1080. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  1081. Info.ArrayInitIndex = 0;
  1082. }
  1083. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  1084. operator uint64_t&() { return Info.ArrayInitIndex; }
  1085. };
  1086. };
  1087. /// Object used to treat all foldable expressions as constant expressions.
  1088. struct FoldConstant {
  1089. EvalInfo &Info;
  1090. bool Enabled;
  1091. bool HadNoPriorDiags;
  1092. EvalInfo::EvaluationMode OldMode;
  1093. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  1094. : Info(Info),
  1095. Enabled(Enabled),
  1096. HadNoPriorDiags(Info.EvalStatus.Diag &&
  1097. Info.EvalStatus.Diag->empty() &&
  1098. !Info.EvalStatus.HasSideEffects),
  1099. OldMode(Info.EvalMode) {
  1100. if (Enabled)
  1101. Info.EvalMode = EvalInfo::EM_ConstantFold;
  1102. }
  1103. void keepDiagnostics() { Enabled = false; }
  1104. ~FoldConstant() {
  1105. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  1106. !Info.EvalStatus.HasSideEffects)
  1107. Info.EvalStatus.Diag->clear();
  1108. Info.EvalMode = OldMode;
  1109. }
  1110. };
  1111. /// RAII object used to set the current evaluation mode to ignore
  1112. /// side-effects.
  1113. struct IgnoreSideEffectsRAII {
  1114. EvalInfo &Info;
  1115. EvalInfo::EvaluationMode OldMode;
  1116. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  1117. : Info(Info), OldMode(Info.EvalMode) {
  1118. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  1119. }
  1120. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  1121. };
  1122. /// RAII object used to optionally suppress diagnostics and side-effects from
  1123. /// a speculative evaluation.
  1124. class SpeculativeEvaluationRAII {
  1125. EvalInfo *Info = nullptr;
  1126. Expr::EvalStatus OldStatus;
  1127. unsigned OldSpeculativeEvaluationDepth;
  1128. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1129. Info = Other.Info;
  1130. OldStatus = Other.OldStatus;
  1131. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1132. Other.Info = nullptr;
  1133. }
  1134. void maybeRestoreState() {
  1135. if (!Info)
  1136. return;
  1137. Info->EvalStatus = OldStatus;
  1138. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1139. }
  1140. public:
  1141. SpeculativeEvaluationRAII() = default;
  1142. SpeculativeEvaluationRAII(
  1143. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1144. : Info(&Info), OldStatus(Info.EvalStatus),
  1145. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1146. Info.EvalStatus.Diag = NewDiag;
  1147. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1148. }
  1149. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1150. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1151. moveFromAndCancel(std::move(Other));
  1152. }
  1153. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1154. maybeRestoreState();
  1155. moveFromAndCancel(std::move(Other));
  1156. return *this;
  1157. }
  1158. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1159. };
  1160. /// RAII object wrapping a full-expression or block scope, and handling
  1161. /// the ending of the lifetime of temporaries created within it.
  1162. template<ScopeKind Kind>
  1163. class ScopeRAII {
  1164. EvalInfo &Info;
  1165. unsigned OldStackSize;
  1166. public:
  1167. ScopeRAII(EvalInfo &Info)
  1168. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1169. // Push a new temporary version. This is needed to distinguish between
  1170. // temporaries created in different iterations of a loop.
  1171. Info.CurrentCall->pushTempVersion();
  1172. }
  1173. bool destroy(bool RunDestructors = true) {
  1174. bool OK = cleanup(Info, RunDestructors, OldStackSize);
  1175. OldStackSize = -1U;
  1176. return OK;
  1177. }
  1178. ~ScopeRAII() {
  1179. if (OldStackSize != -1U)
  1180. destroy(false);
  1181. // Body moved to a static method to encourage the compiler to inline away
  1182. // instances of this class.
  1183. Info.CurrentCall->popTempVersion();
  1184. }
  1185. private:
  1186. static bool cleanup(EvalInfo &Info, bool RunDestructors,
  1187. unsigned OldStackSize) {
  1188. assert(OldStackSize <= Info.CleanupStack.size() &&
  1189. "running cleanups out of order?");
  1190. // Run all cleanups for a block scope, and non-lifetime-extended cleanups
  1191. // for a full-expression scope.
  1192. bool Success = true;
  1193. for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
  1194. if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
  1195. if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
  1196. Success = false;
  1197. break;
  1198. }
  1199. }
  1200. }
  1201. // Compact any retained cleanups.
  1202. auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
  1203. if (Kind != ScopeKind::Block)
  1204. NewEnd =
  1205. std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
  1206. return C.isDestroyedAtEndOf(Kind);
  1207. });
  1208. Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
  1209. return Success;
  1210. }
  1211. };
  1212. typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
  1213. typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
  1214. typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
  1215. }
  1216. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1217. CheckSubobjectKind CSK) {
  1218. if (Invalid)
  1219. return false;
  1220. if (isOnePastTheEnd()) {
  1221. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1222. << CSK;
  1223. setInvalid();
  1224. return false;
  1225. }
  1226. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1227. // must actually be at least one array element; even a VLA cannot have a
  1228. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1229. return true;
  1230. }
  1231. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1232. const Expr *E) {
  1233. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1234. // Do not set the designator as invalid: we can represent this situation,
  1235. // and correct handling of __builtin_object_size requires us to do so.
  1236. }
  1237. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1238. const Expr *E,
  1239. const APSInt &N) {
  1240. // If we're complaining, we must be able to statically determine the size of
  1241. // the most derived array.
  1242. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1243. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1244. << N << /*array*/ 0
  1245. << static_cast<unsigned>(getMostDerivedArraySize());
  1246. else
  1247. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1248. << N << /*non-array*/ 1;
  1249. setInvalid();
  1250. }
  1251. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1252. const FunctionDecl *Callee, const LValue *This,
  1253. CallRef Call)
  1254. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1255. Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1256. Info.CurrentCall = this;
  1257. ++Info.CallStackDepth;
  1258. }
  1259. CallStackFrame::~CallStackFrame() {
  1260. assert(Info.CurrentCall == this && "calls retired out of order");
  1261. --Info.CallStackDepth;
  1262. Info.CurrentCall = Caller;
  1263. }
  1264. static bool isRead(AccessKinds AK) {
  1265. return AK == AK_Read || AK == AK_ReadObjectRepresentation;
  1266. }
  1267. static bool isModification(AccessKinds AK) {
  1268. switch (AK) {
  1269. case AK_Read:
  1270. case AK_ReadObjectRepresentation:
  1271. case AK_MemberCall:
  1272. case AK_DynamicCast:
  1273. case AK_TypeId:
  1274. return false;
  1275. case AK_Assign:
  1276. case AK_Increment:
  1277. case AK_Decrement:
  1278. case AK_Construct:
  1279. case AK_Destroy:
  1280. return true;
  1281. }
  1282. llvm_unreachable("unknown access kind");
  1283. }
  1284. static bool isAnyAccess(AccessKinds AK) {
  1285. return isRead(AK) || isModification(AK);
  1286. }
  1287. /// Is this an access per the C++ definition?
  1288. static bool isFormalAccess(AccessKinds AK) {
  1289. return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
  1290. }
  1291. /// Is this kind of axcess valid on an indeterminate object value?
  1292. static bool isValidIndeterminateAccess(AccessKinds AK) {
  1293. switch (AK) {
  1294. case AK_Read:
  1295. case AK_Increment:
  1296. case AK_Decrement:
  1297. // These need the object's value.
  1298. return false;
  1299. case AK_ReadObjectRepresentation:
  1300. case AK_Assign:
  1301. case AK_Construct:
  1302. case AK_Destroy:
  1303. // Construction and destruction don't need the value.
  1304. return true;
  1305. case AK_MemberCall:
  1306. case AK_DynamicCast:
  1307. case AK_TypeId:
  1308. // These aren't really meaningful on scalars.
  1309. return true;
  1310. }
  1311. llvm_unreachable("unknown access kind");
  1312. }
  1313. namespace {
  1314. struct ComplexValue {
  1315. private:
  1316. bool IsInt;
  1317. public:
  1318. APSInt IntReal, IntImag;
  1319. APFloat FloatReal, FloatImag;
  1320. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1321. void makeComplexFloat() { IsInt = false; }
  1322. bool isComplexFloat() const { return !IsInt; }
  1323. APFloat &getComplexFloatReal() { return FloatReal; }
  1324. APFloat &getComplexFloatImag() { return FloatImag; }
  1325. void makeComplexInt() { IsInt = true; }
  1326. bool isComplexInt() const { return IsInt; }
  1327. APSInt &getComplexIntReal() { return IntReal; }
  1328. APSInt &getComplexIntImag() { return IntImag; }
  1329. void moveInto(APValue &v) const {
  1330. if (isComplexFloat())
  1331. v = APValue(FloatReal, FloatImag);
  1332. else
  1333. v = APValue(IntReal, IntImag);
  1334. }
  1335. void setFrom(const APValue &v) {
  1336. assert(v.isComplexFloat() || v.isComplexInt());
  1337. if (v.isComplexFloat()) {
  1338. makeComplexFloat();
  1339. FloatReal = v.getComplexFloatReal();
  1340. FloatImag = v.getComplexFloatImag();
  1341. } else {
  1342. makeComplexInt();
  1343. IntReal = v.getComplexIntReal();
  1344. IntImag = v.getComplexIntImag();
  1345. }
  1346. }
  1347. };
  1348. struct LValue {
  1349. APValue::LValueBase Base;
  1350. CharUnits Offset;
  1351. SubobjectDesignator Designator;
  1352. bool IsNullPtr : 1;
  1353. bool InvalidBase : 1;
  1354. const APValue::LValueBase getLValueBase() const { return Base; }
  1355. CharUnits &getLValueOffset() { return Offset; }
  1356. const CharUnits &getLValueOffset() const { return Offset; }
  1357. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1358. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1359. bool isNullPointer() const { return IsNullPtr;}
  1360. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1361. unsigned getLValueVersion() const { return Base.getVersion(); }
  1362. void moveInto(APValue &V) const {
  1363. if (Designator.Invalid)
  1364. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1365. else {
  1366. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1367. V = APValue(Base, Offset, Designator.Entries,
  1368. Designator.IsOnePastTheEnd, IsNullPtr);
  1369. }
  1370. }
  1371. void setFrom(ASTContext &Ctx, const APValue &V) {
  1372. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1373. Base = V.getLValueBase();
  1374. Offset = V.getLValueOffset();
  1375. InvalidBase = false;
  1376. Designator = SubobjectDesignator(Ctx, V);
  1377. IsNullPtr = V.isNullPointer();
  1378. }
  1379. void set(APValue::LValueBase B, bool BInvalid = false) {
  1380. #ifndef NDEBUG
  1381. // We only allow a few types of invalid bases. Enforce that here.
  1382. if (BInvalid) {
  1383. const auto *E = B.get<const Expr *>();
  1384. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1385. "Unexpected type of invalid base");
  1386. }
  1387. #endif
  1388. Base = B;
  1389. Offset = CharUnits::fromQuantity(0);
  1390. InvalidBase = BInvalid;
  1391. Designator = SubobjectDesignator(getType(B));
  1392. IsNullPtr = false;
  1393. }
  1394. void setNull(ASTContext &Ctx, QualType PointerTy) {
  1395. Base = (const ValueDecl *)nullptr;
  1396. Offset =
  1397. CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
  1398. InvalidBase = false;
  1399. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1400. IsNullPtr = true;
  1401. }
  1402. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1403. set(B, true);
  1404. }
  1405. std::string toString(ASTContext &Ctx, QualType T) const {
  1406. APValue Printable;
  1407. moveInto(Printable);
  1408. return Printable.getAsString(Ctx, T);
  1409. }
  1410. private:
  1411. // Check that this LValue is not based on a null pointer. If it is, produce
  1412. // a diagnostic and mark the designator as invalid.
  1413. template <typename GenDiagType>
  1414. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1415. if (Designator.Invalid)
  1416. return false;
  1417. if (IsNullPtr) {
  1418. GenDiag();
  1419. Designator.setInvalid();
  1420. return false;
  1421. }
  1422. return true;
  1423. }
  1424. public:
  1425. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1426. CheckSubobjectKind CSK) {
  1427. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1428. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1429. });
  1430. }
  1431. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1432. AccessKinds AK) {
  1433. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1434. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1435. });
  1436. }
  1437. // Check this LValue refers to an object. If not, set the designator to be
  1438. // invalid and emit a diagnostic.
  1439. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1440. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1441. Designator.checkSubobject(Info, E, CSK);
  1442. }
  1443. void addDecl(EvalInfo &Info, const Expr *E,
  1444. const Decl *D, bool Virtual = false) {
  1445. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1446. Designator.addDeclUnchecked(D, Virtual);
  1447. }
  1448. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1449. if (!Designator.Entries.empty()) {
  1450. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1451. Designator.setInvalid();
  1452. return;
  1453. }
  1454. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1455. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1456. Designator.FirstEntryIsAnUnsizedArray = true;
  1457. Designator.addUnsizedArrayUnchecked(ElemTy);
  1458. }
  1459. }
  1460. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1461. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1462. Designator.addArrayUnchecked(CAT);
  1463. }
  1464. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1465. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1466. Designator.addComplexUnchecked(EltTy, Imag);
  1467. }
  1468. void clearIsNullPointer() {
  1469. IsNullPtr = false;
  1470. }
  1471. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1472. const APSInt &Index, CharUnits ElementSize) {
  1473. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1474. // but we're not required to diagnose it and it's valid in C++.)
  1475. if (!Index)
  1476. return;
  1477. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1478. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1479. // offsets.
  1480. uint64_t Offset64 = Offset.getQuantity();
  1481. uint64_t ElemSize64 = ElementSize.getQuantity();
  1482. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1483. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1484. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1485. Designator.adjustIndex(Info, E, Index);
  1486. clearIsNullPointer();
  1487. }
  1488. void adjustOffset(CharUnits N) {
  1489. Offset += N;
  1490. if (N.getQuantity())
  1491. clearIsNullPointer();
  1492. }
  1493. };
  1494. struct MemberPtr {
  1495. MemberPtr() {}
  1496. explicit MemberPtr(const ValueDecl *Decl)
  1497. : DeclAndIsDerivedMember(Decl, false) {}
  1498. /// The member or (direct or indirect) field referred to by this member
  1499. /// pointer, or 0 if this is a null member pointer.
  1500. const ValueDecl *getDecl() const {
  1501. return DeclAndIsDerivedMember.getPointer();
  1502. }
  1503. /// Is this actually a member of some type derived from the relevant class?
  1504. bool isDerivedMember() const {
  1505. return DeclAndIsDerivedMember.getInt();
  1506. }
  1507. /// Get the class which the declaration actually lives in.
  1508. const CXXRecordDecl *getContainingRecord() const {
  1509. return cast<CXXRecordDecl>(
  1510. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1511. }
  1512. void moveInto(APValue &V) const {
  1513. V = APValue(getDecl(), isDerivedMember(), Path);
  1514. }
  1515. void setFrom(const APValue &V) {
  1516. assert(V.isMemberPointer());
  1517. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1518. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1519. Path.clear();
  1520. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1521. Path.insert(Path.end(), P.begin(), P.end());
  1522. }
  1523. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1524. /// whether the member is a member of some class derived from the class type
  1525. /// of the member pointer.
  1526. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1527. /// Path - The path of base/derived classes from the member declaration's
  1528. /// class (exclusive) to the class type of the member pointer (inclusive).
  1529. SmallVector<const CXXRecordDecl*, 4> Path;
  1530. /// Perform a cast towards the class of the Decl (either up or down the
  1531. /// hierarchy).
  1532. bool castBack(const CXXRecordDecl *Class) {
  1533. assert(!Path.empty());
  1534. const CXXRecordDecl *Expected;
  1535. if (Path.size() >= 2)
  1536. Expected = Path[Path.size() - 2];
  1537. else
  1538. Expected = getContainingRecord();
  1539. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1540. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1541. // if B does not contain the original member and is not a base or
  1542. // derived class of the class containing the original member, the result
  1543. // of the cast is undefined.
  1544. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1545. // (D::*). We consider that to be a language defect.
  1546. return false;
  1547. }
  1548. Path.pop_back();
  1549. return true;
  1550. }
  1551. /// Perform a base-to-derived member pointer cast.
  1552. bool castToDerived(const CXXRecordDecl *Derived) {
  1553. if (!getDecl())
  1554. return true;
  1555. if (!isDerivedMember()) {
  1556. Path.push_back(Derived);
  1557. return true;
  1558. }
  1559. if (!castBack(Derived))
  1560. return false;
  1561. if (Path.empty())
  1562. DeclAndIsDerivedMember.setInt(false);
  1563. return true;
  1564. }
  1565. /// Perform a derived-to-base member pointer cast.
  1566. bool castToBase(const CXXRecordDecl *Base) {
  1567. if (!getDecl())
  1568. return true;
  1569. if (Path.empty())
  1570. DeclAndIsDerivedMember.setInt(true);
  1571. if (isDerivedMember()) {
  1572. Path.push_back(Base);
  1573. return true;
  1574. }
  1575. return castBack(Base);
  1576. }
  1577. };
  1578. /// Compare two member pointers, which are assumed to be of the same type.
  1579. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1580. if (!LHS.getDecl() || !RHS.getDecl())
  1581. return !LHS.getDecl() && !RHS.getDecl();
  1582. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1583. return false;
  1584. return LHS.Path == RHS.Path;
  1585. }
  1586. }
  1587. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1588. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1589. const LValue &This, const Expr *E,
  1590. bool AllowNonLiteralTypes = false);
  1591. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1592. bool InvalidBaseOK = false);
  1593. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1594. bool InvalidBaseOK = false);
  1595. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1596. EvalInfo &Info);
  1597. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1598. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1599. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1600. EvalInfo &Info);
  1601. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1602. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1603. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1604. EvalInfo &Info);
  1605. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1606. static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
  1607. EvalInfo &Info);
  1608. /// Evaluate an integer or fixed point expression into an APResult.
  1609. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1610. EvalInfo &Info);
  1611. /// Evaluate only a fixed point expression into an APResult.
  1612. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1613. EvalInfo &Info);
  1614. //===----------------------------------------------------------------------===//
  1615. // Misc utilities
  1616. //===----------------------------------------------------------------------===//
  1617. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1618. /// preserving its value (by extending by up to one bit as needed).
  1619. static void negateAsSigned(APSInt &Int) {
  1620. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1621. Int = Int.extend(Int.getBitWidth() + 1);
  1622. Int.setIsSigned(true);
  1623. }
  1624. Int = -Int;
  1625. }
  1626. template<typename KeyT>
  1627. APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
  1628. ScopeKind Scope, LValue &LV) {
  1629. unsigned Version = getTempVersion();
  1630. APValue::LValueBase Base(Key, Index, Version);
  1631. LV.set(Base);
  1632. return createLocal(Base, Key, T, Scope);
  1633. }
  1634. /// Allocate storage for a parameter of a function call made in this frame.
  1635. APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
  1636. LValue &LV) {
  1637. assert(Args.CallIndex == Index && "creating parameter in wrong frame");
  1638. APValue::LValueBase Base(PVD, Index, Args.Version);
  1639. LV.set(Base);
  1640. // We always destroy parameters at the end of the call, even if we'd allow
  1641. // them to live to the end of the full-expression at runtime, in order to
  1642. // give portable results and match other compilers.
  1643. return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
  1644. }
  1645. APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
  1646. QualType T, ScopeKind Scope) {
  1647. assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
  1648. unsigned Version = Base.getVersion();
  1649. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1650. assert(Result.isAbsent() && "local created multiple times");
  1651. // If we're creating a local immediately in the operand of a speculative
  1652. // evaluation, don't register a cleanup to be run outside the speculative
  1653. // evaluation context, since we won't actually be able to initialize this
  1654. // object.
  1655. if (Index <= Info.SpeculativeEvaluationDepth) {
  1656. if (T.isDestructedType())
  1657. Info.noteSideEffect();
  1658. } else {
  1659. Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
  1660. }
  1661. return Result;
  1662. }
  1663. APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
  1664. if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
  1665. FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
  1666. return nullptr;
  1667. }
  1668. DynamicAllocLValue DA(NumHeapAllocs++);
  1669. LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
  1670. auto Result = HeapAllocs.emplace(std::piecewise_construct,
  1671. std::forward_as_tuple(DA), std::tuple<>());
  1672. assert(Result.second && "reused a heap alloc index?");
  1673. Result.first->second.AllocExpr = E;
  1674. return &Result.first->second.Value;
  1675. }
  1676. /// Produce a string describing the given constexpr call.
  1677. void CallStackFrame::describe(raw_ostream &Out) {
  1678. unsigned ArgIndex = 0;
  1679. bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
  1680. !isa<CXXConstructorDecl>(Callee) &&
  1681. cast<CXXMethodDecl>(Callee)->isInstance();
  1682. if (!IsMemberCall)
  1683. Out << *Callee << '(';
  1684. if (This && IsMemberCall) {
  1685. APValue Val;
  1686. This->moveInto(Val);
  1687. Val.printPretty(Out, Info.Ctx,
  1688. This->Designator.MostDerivedType);
  1689. // FIXME: Add parens around Val if needed.
  1690. Out << "->" << *Callee << '(';
  1691. IsMemberCall = false;
  1692. }
  1693. for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
  1694. E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1695. if (ArgIndex > (unsigned)IsMemberCall)
  1696. Out << ", ";
  1697. const ParmVarDecl *Param = *I;
  1698. APValue *V = Info.getParamSlot(Arguments, Param);
  1699. if (V)
  1700. V->printPretty(Out, Info.Ctx, Param->getType());
  1701. else
  1702. Out << "<...>";
  1703. if (ArgIndex == 0 && IsMemberCall)
  1704. Out << "->" << *Callee << '(';
  1705. }
  1706. Out << ')';
  1707. }
  1708. /// Evaluate an expression to see if it had side-effects, and discard its
  1709. /// result.
  1710. /// \return \c true if the caller should keep evaluating.
  1711. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1712. assert(!E->isValueDependent());
  1713. APValue Scratch;
  1714. if (!Evaluate(Scratch, Info, E))
  1715. // We don't need the value, but we might have skipped a side effect here.
  1716. return Info.noteSideEffect();
  1717. return true;
  1718. }
  1719. /// Should this call expression be treated as a no-op?
  1720. static bool IsNoOpCall(const CallExpr *E) {
  1721. unsigned Builtin = E->getBuiltinCallee();
  1722. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1723. Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
  1724. Builtin == Builtin::BI__builtin_function_start);
  1725. }
  1726. static bool IsGlobalLValue(APValue::LValueBase B) {
  1727. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1728. // constant expression of pointer type that evaluates to...
  1729. // ... a null pointer value, or a prvalue core constant expression of type
  1730. // std::nullptr_t.
  1731. if (!B) return true;
  1732. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1733. // ... the address of an object with static storage duration,
  1734. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1735. return VD->hasGlobalStorage();
  1736. if (isa<TemplateParamObjectDecl>(D))
  1737. return true;
  1738. // ... the address of a function,
  1739. // ... the address of a GUID [MS extension],
  1740. // ... the address of an unnamed global constant
  1741. return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
  1742. }
  1743. if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
  1744. return true;
  1745. const Expr *E = B.get<const Expr*>();
  1746. switch (E->getStmtClass()) {
  1747. default:
  1748. return false;
  1749. case Expr::CompoundLiteralExprClass: {
  1750. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1751. return CLE->isFileScope() && CLE->isLValue();
  1752. }
  1753. case Expr::MaterializeTemporaryExprClass:
  1754. // A materialized temporary might have been lifetime-extended to static
  1755. // storage duration.
  1756. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1757. // A string literal has static storage duration.
  1758. case Expr::StringLiteralClass:
  1759. case Expr::PredefinedExprClass:
  1760. case Expr::ObjCStringLiteralClass:
  1761. case Expr::ObjCEncodeExprClass:
  1762. return true;
  1763. case Expr::ObjCBoxedExprClass:
  1764. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1765. case Expr::CallExprClass:
  1766. return IsNoOpCall(cast<CallExpr>(E));
  1767. // For GCC compatibility, &&label has static storage duration.
  1768. case Expr::AddrLabelExprClass:
  1769. return true;
  1770. // A Block literal expression may be used as the initialization value for
  1771. // Block variables at global or local static scope.
  1772. case Expr::BlockExprClass:
  1773. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1774. // The APValue generated from a __builtin_source_location will be emitted as a
  1775. // literal.
  1776. case Expr::SourceLocExprClass:
  1777. return true;
  1778. case Expr::ImplicitValueInitExprClass:
  1779. // FIXME:
  1780. // We can never form an lvalue with an implicit value initialization as its
  1781. // base through expression evaluation, so these only appear in one case: the
  1782. // implicit variable declaration we invent when checking whether a constexpr
  1783. // constructor can produce a constant expression. We must assume that such
  1784. // an expression might be a global lvalue.
  1785. return true;
  1786. }
  1787. }
  1788. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1789. return LVal.Base.dyn_cast<const ValueDecl*>();
  1790. }
  1791. static bool IsLiteralLValue(const LValue &Value) {
  1792. if (Value.getLValueCallIndex())
  1793. return false;
  1794. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1795. return E && !isa<MaterializeTemporaryExpr>(E);
  1796. }
  1797. static bool IsWeakLValue(const LValue &Value) {
  1798. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1799. return Decl && Decl->isWeak();
  1800. }
  1801. static bool isZeroSized(const LValue &Value) {
  1802. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1803. if (Decl && isa<VarDecl>(Decl)) {
  1804. QualType Ty = Decl->getType();
  1805. if (Ty->isArrayType())
  1806. return Ty->isIncompleteType() ||
  1807. Decl->getASTContext().getTypeSize(Ty) == 0;
  1808. }
  1809. return false;
  1810. }
  1811. static bool HasSameBase(const LValue &A, const LValue &B) {
  1812. if (!A.getLValueBase())
  1813. return !B.getLValueBase();
  1814. if (!B.getLValueBase())
  1815. return false;
  1816. if (A.getLValueBase().getOpaqueValue() !=
  1817. B.getLValueBase().getOpaqueValue())
  1818. return false;
  1819. return A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1820. A.getLValueVersion() == B.getLValueVersion();
  1821. }
  1822. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1823. assert(Base && "no location for a null lvalue");
  1824. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1825. // For a parameter, find the corresponding call stack frame (if it still
  1826. // exists), and point at the parameter of the function definition we actually
  1827. // invoked.
  1828. if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
  1829. unsigned Idx = PVD->getFunctionScopeIndex();
  1830. for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
  1831. if (F->Arguments.CallIndex == Base.getCallIndex() &&
  1832. F->Arguments.Version == Base.getVersion() && F->Callee &&
  1833. Idx < F->Callee->getNumParams()) {
  1834. VD = F->Callee->getParamDecl(Idx);
  1835. break;
  1836. }
  1837. }
  1838. }
  1839. if (VD)
  1840. Info.Note(VD->getLocation(), diag::note_declared_at);
  1841. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1842. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1843. else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
  1844. // FIXME: Produce a note for dangling pointers too.
  1845. if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
  1846. Info.Note((*Alloc)->AllocExpr->getExprLoc(),
  1847. diag::note_constexpr_dynamic_alloc_here);
  1848. }
  1849. // We have no information to show for a typeid(T) object.
  1850. }
  1851. enum class CheckEvaluationResultKind {
  1852. ConstantExpression,
  1853. FullyInitialized,
  1854. };
  1855. /// Materialized temporaries that we've already checked to determine if they're
  1856. /// initializsed by a constant expression.
  1857. using CheckedTemporaries =
  1858. llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
  1859. static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
  1860. EvalInfo &Info, SourceLocation DiagLoc,
  1861. QualType Type, const APValue &Value,
  1862. ConstantExprKind Kind,
  1863. SourceLocation SubobjectLoc,
  1864. CheckedTemporaries &CheckedTemps);
  1865. /// Check that this reference or pointer core constant expression is a valid
  1866. /// value for an address or reference constant expression. Return true if we
  1867. /// can fold this expression, whether or not it's a constant expression.
  1868. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1869. QualType Type, const LValue &LVal,
  1870. ConstantExprKind Kind,
  1871. CheckedTemporaries &CheckedTemps) {
  1872. bool IsReferenceType = Type->isReferenceType();
  1873. APValue::LValueBase Base = LVal.getLValueBase();
  1874. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1875. const Expr *BaseE = Base.dyn_cast<const Expr *>();
  1876. const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
  1877. // Additional restrictions apply in a template argument. We only enforce the
  1878. // C++20 restrictions here; additional syntactic and semantic restrictions
  1879. // are applied elsewhere.
  1880. if (isTemplateArgument(Kind)) {
  1881. int InvalidBaseKind = -1;
  1882. StringRef Ident;
  1883. if (Base.is<TypeInfoLValue>())
  1884. InvalidBaseKind = 0;
  1885. else if (isa_and_nonnull<StringLiteral>(BaseE))
  1886. InvalidBaseKind = 1;
  1887. else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
  1888. isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
  1889. InvalidBaseKind = 2;
  1890. else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
  1891. InvalidBaseKind = 3;
  1892. Ident = PE->getIdentKindName();
  1893. }
  1894. if (InvalidBaseKind != -1) {
  1895. Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
  1896. << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
  1897. << Ident;
  1898. return false;
  1899. }
  1900. }
  1901. if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
  1902. if (FD->isConsteval()) {
  1903. Info.FFDiag(Loc, diag::note_consteval_address_accessible)
  1904. << !Type->isAnyPointerType();
  1905. Info.Note(FD->getLocation(), diag::note_declared_at);
  1906. return false;
  1907. }
  1908. }
  1909. // Check that the object is a global. Note that the fake 'this' object we
  1910. // manufacture when checking potential constant expressions is conservatively
  1911. // assumed to be global here.
  1912. if (!IsGlobalLValue(Base)) {
  1913. if (Info.getLangOpts().CPlusPlus11) {
  1914. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1915. << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
  1916. << BaseVD;
  1917. auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
  1918. if (VarD && VarD->isConstexpr()) {
  1919. // Non-static local constexpr variables have unintuitive semantics:
  1920. // constexpr int a = 1;
  1921. // constexpr const int *p = &a;
  1922. // ... is invalid because the address of 'a' is not constant. Suggest
  1923. // adding a 'static' in this case.
  1924. Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
  1925. << VarD
  1926. << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
  1927. } else {
  1928. NoteLValueLocation(Info, Base);
  1929. }
  1930. } else {
  1931. Info.FFDiag(Loc);
  1932. }
  1933. // Don't allow references to temporaries to escape.
  1934. return false;
  1935. }
  1936. assert((Info.checkingPotentialConstantExpression() ||
  1937. LVal.getLValueCallIndex() == 0) &&
  1938. "have call index for global lvalue");
  1939. if (Base.is<DynamicAllocLValue>()) {
  1940. Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
  1941. << IsReferenceType << !Designator.Entries.empty();
  1942. NoteLValueLocation(Info, Base);
  1943. return false;
  1944. }
  1945. if (BaseVD) {
  1946. if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
  1947. // Check if this is a thread-local variable.
  1948. if (Var->getTLSKind())
  1949. // FIXME: Diagnostic!
  1950. return false;
  1951. // A dllimport variable never acts like a constant, unless we're
  1952. // evaluating a value for use only in name mangling.
  1953. if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
  1954. // FIXME: Diagnostic!
  1955. return false;
  1956. // In CUDA/HIP device compilation, only device side variables have
  1957. // constant addresses.
  1958. if (Info.getCtx().getLangOpts().CUDA &&
  1959. Info.getCtx().getLangOpts().CUDAIsDevice &&
  1960. Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
  1961. if ((!Var->hasAttr<CUDADeviceAttr>() &&
  1962. !Var->hasAttr<CUDAConstantAttr>() &&
  1963. !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
  1964. !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
  1965. Var->hasAttr<HIPManagedAttr>())
  1966. return false;
  1967. }
  1968. }
  1969. if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
  1970. // __declspec(dllimport) must be handled very carefully:
  1971. // We must never initialize an expression with the thunk in C++.
  1972. // Doing otherwise would allow the same id-expression to yield
  1973. // different addresses for the same function in different translation
  1974. // units. However, this means that we must dynamically initialize the
  1975. // expression with the contents of the import address table at runtime.
  1976. //
  1977. // The C language has no notion of ODR; furthermore, it has no notion of
  1978. // dynamic initialization. This means that we are permitted to
  1979. // perform initialization with the address of the thunk.
  1980. if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
  1981. FD->hasAttr<DLLImportAttr>())
  1982. // FIXME: Diagnostic!
  1983. return false;
  1984. }
  1985. } else if (const auto *MTE =
  1986. dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
  1987. if (CheckedTemps.insert(MTE).second) {
  1988. QualType TempType = getType(Base);
  1989. if (TempType.isDestructedType()) {
  1990. Info.FFDiag(MTE->getExprLoc(),
  1991. diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
  1992. << TempType;
  1993. return false;
  1994. }
  1995. APValue *V = MTE->getOrCreateValue(false);
  1996. assert(V && "evasluation result refers to uninitialised temporary");
  1997. if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  1998. Info, MTE->getExprLoc(), TempType, *V,
  1999. Kind, SourceLocation(), CheckedTemps))
  2000. return false;
  2001. }
  2002. }
  2003. // Allow address constant expressions to be past-the-end pointers. This is
  2004. // an extension: the standard requires them to point to an object.
  2005. if (!IsReferenceType)
  2006. return true;
  2007. // A reference constant expression must refer to an object.
  2008. if (!Base) {
  2009. // FIXME: diagnostic
  2010. Info.CCEDiag(Loc);
  2011. return true;
  2012. }
  2013. // Does this refer one past the end of some object?
  2014. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  2015. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  2016. << !Designator.Entries.empty() << !!BaseVD << BaseVD;
  2017. NoteLValueLocation(Info, Base);
  2018. }
  2019. return true;
  2020. }
  2021. /// Member pointers are constant expressions unless they point to a
  2022. /// non-virtual dllimport member function.
  2023. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  2024. SourceLocation Loc,
  2025. QualType Type,
  2026. const APValue &Value,
  2027. ConstantExprKind Kind) {
  2028. const ValueDecl *Member = Value.getMemberPointerDecl();
  2029. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  2030. if (!FD)
  2031. return true;
  2032. if (FD->isConsteval()) {
  2033. Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
  2034. Info.Note(FD->getLocation(), diag::note_declared_at);
  2035. return false;
  2036. }
  2037. return isForManglingOnly(Kind) || FD->isVirtual() ||
  2038. !FD->hasAttr<DLLImportAttr>();
  2039. }
  2040. /// Check that this core constant expression is of literal type, and if not,
  2041. /// produce an appropriate diagnostic.
  2042. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  2043. const LValue *This = nullptr) {
  2044. if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
  2045. return true;
  2046. // C++1y: A constant initializer for an object o [...] may also invoke
  2047. // constexpr constructors for o and its subobjects even if those objects
  2048. // are of non-literal class types.
  2049. //
  2050. // C++11 missed this detail for aggregates, so classes like this:
  2051. // struct foo_t { union { int i; volatile int j; } u; };
  2052. // are not (obviously) initializable like so:
  2053. // __attribute__((__require_constant_initialization__))
  2054. // static const foo_t x = {{0}};
  2055. // because "i" is a subobject with non-literal initialization (due to the
  2056. // volatile member of the union). See:
  2057. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  2058. // Therefore, we use the C++1y behavior.
  2059. if (This && Info.EvaluatingDecl == This->getLValueBase())
  2060. return true;
  2061. // Prvalue constant expressions must be of literal types.
  2062. if (Info.getLangOpts().CPlusPlus11)
  2063. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  2064. << E->getType();
  2065. else
  2066. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2067. return false;
  2068. }
  2069. static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
  2070. EvalInfo &Info, SourceLocation DiagLoc,
  2071. QualType Type, const APValue &Value,
  2072. ConstantExprKind Kind,
  2073. SourceLocation SubobjectLoc,
  2074. CheckedTemporaries &CheckedTemps) {
  2075. if (!Value.hasValue()) {
  2076. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  2077. << true << Type;
  2078. if (SubobjectLoc.isValid())
  2079. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  2080. return false;
  2081. }
  2082. // We allow _Atomic(T) to be initialized from anything that T can be
  2083. // initialized from.
  2084. if (const AtomicType *AT = Type->getAs<AtomicType>())
  2085. Type = AT->getValueType();
  2086. // Core issue 1454: For a literal constant expression of array or class type,
  2087. // each subobject of its value shall have been initialized by a constant
  2088. // expression.
  2089. if (Value.isArray()) {
  2090. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  2091. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  2092. if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  2093. Value.getArrayInitializedElt(I), Kind,
  2094. SubobjectLoc, CheckedTemps))
  2095. return false;
  2096. }
  2097. if (!Value.hasArrayFiller())
  2098. return true;
  2099. return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  2100. Value.getArrayFiller(), Kind, SubobjectLoc,
  2101. CheckedTemps);
  2102. }
  2103. if (Value.isUnion() && Value.getUnionField()) {
  2104. return CheckEvaluationResult(
  2105. CERK, Info, DiagLoc, Value.getUnionField()->getType(),
  2106. Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
  2107. CheckedTemps);
  2108. }
  2109. if (Value.isStruct()) {
  2110. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  2111. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  2112. unsigned BaseIndex = 0;
  2113. for (const CXXBaseSpecifier &BS : CD->bases()) {
  2114. if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
  2115. Value.getStructBase(BaseIndex), Kind,
  2116. BS.getBeginLoc(), CheckedTemps))
  2117. return false;
  2118. ++BaseIndex;
  2119. }
  2120. }
  2121. for (const auto *I : RD->fields()) {
  2122. if (I->isUnnamedBitfield())
  2123. continue;
  2124. if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
  2125. Value.getStructField(I->getFieldIndex()),
  2126. Kind, I->getLocation(), CheckedTemps))
  2127. return false;
  2128. }
  2129. }
  2130. if (Value.isLValue() &&
  2131. CERK == CheckEvaluationResultKind::ConstantExpression) {
  2132. LValue LVal;
  2133. LVal.setFrom(Info.Ctx, Value);
  2134. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
  2135. CheckedTemps);
  2136. }
  2137. if (Value.isMemberPointer() &&
  2138. CERK == CheckEvaluationResultKind::ConstantExpression)
  2139. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
  2140. // Everything else is fine.
  2141. return true;
  2142. }
  2143. /// Check that this core constant expression value is a valid value for a
  2144. /// constant expression. If not, report an appropriate diagnostic. Does not
  2145. /// check that the expression is of literal type.
  2146. static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
  2147. QualType Type, const APValue &Value,
  2148. ConstantExprKind Kind) {
  2149. // Nothing to check for a constant expression of type 'cv void'.
  2150. if (Type->isVoidType())
  2151. return true;
  2152. CheckedTemporaries CheckedTemps;
  2153. return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  2154. Info, DiagLoc, Type, Value, Kind,
  2155. SourceLocation(), CheckedTemps);
  2156. }
  2157. /// Check that this evaluated value is fully-initialized and can be loaded by
  2158. /// an lvalue-to-rvalue conversion.
  2159. static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
  2160. QualType Type, const APValue &Value) {
  2161. CheckedTemporaries CheckedTemps;
  2162. return CheckEvaluationResult(
  2163. CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
  2164. ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
  2165. }
  2166. /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
  2167. /// "the allocated storage is deallocated within the evaluation".
  2168. static bool CheckMemoryLeaks(EvalInfo &Info) {
  2169. if (!Info.HeapAllocs.empty()) {
  2170. // We can still fold to a constant despite a compile-time memory leak,
  2171. // so long as the heap allocation isn't referenced in the result (we check
  2172. // that in CheckConstantExpression).
  2173. Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
  2174. diag::note_constexpr_memory_leak)
  2175. << unsigned(Info.HeapAllocs.size() - 1);
  2176. }
  2177. return true;
  2178. }
  2179. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  2180. // A null base expression indicates a null pointer. These are always
  2181. // evaluatable, and they are false unless the offset is zero.
  2182. if (!Value.getLValueBase()) {
  2183. // TODO: Should a non-null pointer with an offset of zero evaluate to true?
  2184. Result = !Value.getLValueOffset().isZero();
  2185. return true;
  2186. }
  2187. // We have a non-null base. These are generally known to be true, but if it's
  2188. // a weak declaration it can be null at runtime.
  2189. Result = true;
  2190. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  2191. return !Decl || !Decl->isWeak();
  2192. }
  2193. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  2194. // TODO: This function should produce notes if it fails.
  2195. switch (Val.getKind()) {
  2196. case APValue::None:
  2197. case APValue::Indeterminate:
  2198. return false;
  2199. case APValue::Int:
  2200. Result = Val.getInt().getBoolValue();
  2201. return true;
  2202. case APValue::FixedPoint:
  2203. Result = Val.getFixedPoint().getBoolValue();
  2204. return true;
  2205. case APValue::Float:
  2206. Result = !Val.getFloat().isZero();
  2207. return true;
  2208. case APValue::ComplexInt:
  2209. Result = Val.getComplexIntReal().getBoolValue() ||
  2210. Val.getComplexIntImag().getBoolValue();
  2211. return true;
  2212. case APValue::ComplexFloat:
  2213. Result = !Val.getComplexFloatReal().isZero() ||
  2214. !Val.getComplexFloatImag().isZero();
  2215. return true;
  2216. case APValue::LValue:
  2217. return EvalPointerValueAsBool(Val, Result);
  2218. case APValue::MemberPointer:
  2219. if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
  2220. return false;
  2221. }
  2222. Result = Val.getMemberPointerDecl();
  2223. return true;
  2224. case APValue::Vector:
  2225. case APValue::Array:
  2226. case APValue::Struct:
  2227. case APValue::Union:
  2228. case APValue::AddrLabelDiff:
  2229. return false;
  2230. }
  2231. llvm_unreachable("unknown APValue kind");
  2232. }
  2233. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  2234. EvalInfo &Info) {
  2235. assert(!E->isValueDependent());
  2236. assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
  2237. APValue Val;
  2238. if (!Evaluate(Val, Info, E))
  2239. return false;
  2240. return HandleConversionToBool(Val, Result);
  2241. }
  2242. template<typename T>
  2243. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  2244. const T &SrcValue, QualType DestType) {
  2245. Info.CCEDiag(E, diag::note_constexpr_overflow)
  2246. << SrcValue << DestType;
  2247. return Info.noteUndefinedBehavior();
  2248. }
  2249. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  2250. QualType SrcType, const APFloat &Value,
  2251. QualType DestType, APSInt &Result) {
  2252. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2253. // Determine whether we are converting to unsigned or signed.
  2254. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  2255. Result = APSInt(DestWidth, !DestSigned);
  2256. bool ignored;
  2257. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  2258. & APFloat::opInvalidOp)
  2259. return HandleOverflow(Info, E, Value, DestType);
  2260. return true;
  2261. }
  2262. /// Get rounding mode to use in evaluation of the specified expression.
  2263. ///
  2264. /// If rounding mode is unknown at compile time, still try to evaluate the
  2265. /// expression. If the result is exact, it does not depend on rounding mode.
  2266. /// So return "tonearest" mode instead of "dynamic".
  2267. static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
  2268. llvm::RoundingMode RM =
  2269. E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
  2270. if (RM == llvm::RoundingMode::Dynamic)
  2271. RM = llvm::RoundingMode::NearestTiesToEven;
  2272. return RM;
  2273. }
  2274. /// Check if the given evaluation result is allowed for constant evaluation.
  2275. static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
  2276. APFloat::opStatus St) {
  2277. // In a constant context, assume that any dynamic rounding mode or FP
  2278. // exception state matches the default floating-point environment.
  2279. if (Info.InConstantContext)
  2280. return true;
  2281. FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
  2282. if ((St & APFloat::opInexact) &&
  2283. FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
  2284. // Inexact result means that it depends on rounding mode. If the requested
  2285. // mode is dynamic, the evaluation cannot be made in compile time.
  2286. Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
  2287. return false;
  2288. }
  2289. if ((St != APFloat::opOK) &&
  2290. (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
  2291. FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
  2292. FPO.getAllowFEnvAccess())) {
  2293. Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
  2294. return false;
  2295. }
  2296. if ((St & APFloat::opStatus::opInvalidOp) &&
  2297. FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
  2298. // There is no usefully definable result.
  2299. Info.FFDiag(E);
  2300. return false;
  2301. }
  2302. // FIXME: if:
  2303. // - evaluation triggered other FP exception, and
  2304. // - exception mode is not "ignore", and
  2305. // - the expression being evaluated is not a part of global variable
  2306. // initializer,
  2307. // the evaluation probably need to be rejected.
  2308. return true;
  2309. }
  2310. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  2311. QualType SrcType, QualType DestType,
  2312. APFloat &Result) {
  2313. assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
  2314. llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
  2315. APFloat::opStatus St;
  2316. APFloat Value = Result;
  2317. bool ignored;
  2318. St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
  2319. return checkFloatingPointResult(Info, E, St);
  2320. }
  2321. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  2322. QualType DestType, QualType SrcType,
  2323. const APSInt &Value) {
  2324. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2325. // Figure out if this is a truncate, extend or noop cast.
  2326. // If the input is signed, do a sign extend, noop, or truncate.
  2327. APSInt Result = Value.extOrTrunc(DestWidth);
  2328. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  2329. if (DestType->isBooleanType())
  2330. Result = Value.getBoolValue();
  2331. return Result;
  2332. }
  2333. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  2334. const FPOptions FPO,
  2335. QualType SrcType, const APSInt &Value,
  2336. QualType DestType, APFloat &Result) {
  2337. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  2338. llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
  2339. APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
  2340. return checkFloatingPointResult(Info, E, St);
  2341. }
  2342. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  2343. APValue &Value, const FieldDecl *FD) {
  2344. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  2345. if (!Value.isInt()) {
  2346. // Trying to store a pointer-cast-to-integer into a bitfield.
  2347. // FIXME: In this case, we should provide the diagnostic for casting
  2348. // a pointer to an integer.
  2349. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  2350. Info.FFDiag(E);
  2351. return false;
  2352. }
  2353. APSInt &Int = Value.getInt();
  2354. unsigned OldBitWidth = Int.getBitWidth();
  2355. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  2356. if (NewBitWidth < OldBitWidth)
  2357. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  2358. return true;
  2359. }
  2360. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  2361. llvm::APInt &Res) {
  2362. APValue SVal;
  2363. if (!Evaluate(SVal, Info, E))
  2364. return false;
  2365. if (SVal.isInt()) {
  2366. Res = SVal.getInt();
  2367. return true;
  2368. }
  2369. if (SVal.isFloat()) {
  2370. Res = SVal.getFloat().bitcastToAPInt();
  2371. return true;
  2372. }
  2373. if (SVal.isVector()) {
  2374. QualType VecTy = E->getType();
  2375. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  2376. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  2377. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  2378. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  2379. Res = llvm::APInt::getZero(VecSize);
  2380. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  2381. APValue &Elt = SVal.getVectorElt(i);
  2382. llvm::APInt EltAsInt;
  2383. if (Elt.isInt()) {
  2384. EltAsInt = Elt.getInt();
  2385. } else if (Elt.isFloat()) {
  2386. EltAsInt = Elt.getFloat().bitcastToAPInt();
  2387. } else {
  2388. // Don't try to handle vectors of anything other than int or float
  2389. // (not sure if it's possible to hit this case).
  2390. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2391. return false;
  2392. }
  2393. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2394. if (BigEndian)
  2395. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2396. else
  2397. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2398. }
  2399. return true;
  2400. }
  2401. // Give up if the input isn't an int, float, or vector. For example, we
  2402. // reject "(v4i16)(intptr_t)&a".
  2403. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2404. return false;
  2405. }
  2406. /// Perform the given integer operation, which is known to need at most BitWidth
  2407. /// bits, and check for overflow in the original type (if that type was not an
  2408. /// unsigned type).
  2409. template<typename Operation>
  2410. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2411. const APSInt &LHS, const APSInt &RHS,
  2412. unsigned BitWidth, Operation Op,
  2413. APSInt &Result) {
  2414. if (LHS.isUnsigned()) {
  2415. Result = Op(LHS, RHS);
  2416. return true;
  2417. }
  2418. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2419. Result = Value.trunc(LHS.getBitWidth());
  2420. if (Result.extend(BitWidth) != Value) {
  2421. if (Info.checkingForUndefinedBehavior())
  2422. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2423. diag::warn_integer_constant_overflow)
  2424. << toString(Result, 10) << E->getType();
  2425. return HandleOverflow(Info, E, Value, E->getType());
  2426. }
  2427. return true;
  2428. }
  2429. /// Perform the given binary integer operation.
  2430. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2431. BinaryOperatorKind Opcode, APSInt RHS,
  2432. APSInt &Result) {
  2433. bool HandleOverflowResult = true;
  2434. switch (Opcode) {
  2435. default:
  2436. Info.FFDiag(E);
  2437. return false;
  2438. case BO_Mul:
  2439. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2440. std::multiplies<APSInt>(), Result);
  2441. case BO_Add:
  2442. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2443. std::plus<APSInt>(), Result);
  2444. case BO_Sub:
  2445. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2446. std::minus<APSInt>(), Result);
  2447. case BO_And: Result = LHS & RHS; return true;
  2448. case BO_Xor: Result = LHS ^ RHS; return true;
  2449. case BO_Or: Result = LHS | RHS; return true;
  2450. case BO_Div:
  2451. case BO_Rem:
  2452. if (RHS == 0) {
  2453. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2454. return false;
  2455. }
  2456. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2457. // this operation and gives the two's complement result.
  2458. if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
  2459. LHS.isMinSignedValue())
  2460. HandleOverflowResult = HandleOverflow(
  2461. Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
  2462. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2463. return HandleOverflowResult;
  2464. case BO_Shl: {
  2465. if (Info.getLangOpts().OpenCL)
  2466. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2467. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2468. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2469. RHS.isUnsigned());
  2470. else if (RHS.isSigned() && RHS.isNegative()) {
  2471. // During constant-folding, a negative shift is an opposite shift. Such
  2472. // a shift is not a constant expression.
  2473. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2474. RHS = -RHS;
  2475. goto shift_right;
  2476. }
  2477. shift_left:
  2478. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2479. // the shifted type.
  2480. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2481. if (SA != RHS) {
  2482. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2483. << RHS << E->getType() << LHS.getBitWidth();
  2484. } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
  2485. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2486. // operand, and must not overflow the corresponding unsigned type.
  2487. // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
  2488. // E1 x 2^E2 module 2^N.
  2489. if (LHS.isNegative())
  2490. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2491. else if (LHS.countLeadingZeros() < SA)
  2492. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2493. }
  2494. Result = LHS << SA;
  2495. return true;
  2496. }
  2497. case BO_Shr: {
  2498. if (Info.getLangOpts().OpenCL)
  2499. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2500. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2501. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2502. RHS.isUnsigned());
  2503. else if (RHS.isSigned() && RHS.isNegative()) {
  2504. // During constant-folding, a negative shift is an opposite shift. Such a
  2505. // shift is not a constant expression.
  2506. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2507. RHS = -RHS;
  2508. goto shift_left;
  2509. }
  2510. shift_right:
  2511. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2512. // shifted type.
  2513. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2514. if (SA != RHS)
  2515. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2516. << RHS << E->getType() << LHS.getBitWidth();
  2517. Result = LHS >> SA;
  2518. return true;
  2519. }
  2520. case BO_LT: Result = LHS < RHS; return true;
  2521. case BO_GT: Result = LHS > RHS; return true;
  2522. case BO_LE: Result = LHS <= RHS; return true;
  2523. case BO_GE: Result = LHS >= RHS; return true;
  2524. case BO_EQ: Result = LHS == RHS; return true;
  2525. case BO_NE: Result = LHS != RHS; return true;
  2526. case BO_Cmp:
  2527. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2528. }
  2529. }
  2530. /// Perform the given binary floating-point operation, in-place, on LHS.
  2531. static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
  2532. APFloat &LHS, BinaryOperatorKind Opcode,
  2533. const APFloat &RHS) {
  2534. llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
  2535. APFloat::opStatus St;
  2536. switch (Opcode) {
  2537. default:
  2538. Info.FFDiag(E);
  2539. return false;
  2540. case BO_Mul:
  2541. St = LHS.multiply(RHS, RM);
  2542. break;
  2543. case BO_Add:
  2544. St = LHS.add(RHS, RM);
  2545. break;
  2546. case BO_Sub:
  2547. St = LHS.subtract(RHS, RM);
  2548. break;
  2549. case BO_Div:
  2550. // [expr.mul]p4:
  2551. // If the second operand of / or % is zero the behavior is undefined.
  2552. if (RHS.isZero())
  2553. Info.CCEDiag(E, diag::note_expr_divide_by_zero);
  2554. St = LHS.divide(RHS, RM);
  2555. break;
  2556. }
  2557. // [expr.pre]p4:
  2558. // If during the evaluation of an expression, the result is not
  2559. // mathematically defined [...], the behavior is undefined.
  2560. // FIXME: C++ rules require us to not conform to IEEE 754 here.
  2561. if (LHS.isNaN()) {
  2562. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2563. return Info.noteUndefinedBehavior();
  2564. }
  2565. return checkFloatingPointResult(Info, E, St);
  2566. }
  2567. static bool handleLogicalOpForVector(const APInt &LHSValue,
  2568. BinaryOperatorKind Opcode,
  2569. const APInt &RHSValue, APInt &Result) {
  2570. bool LHS = (LHSValue != 0);
  2571. bool RHS = (RHSValue != 0);
  2572. if (Opcode == BO_LAnd)
  2573. Result = LHS && RHS;
  2574. else
  2575. Result = LHS || RHS;
  2576. return true;
  2577. }
  2578. static bool handleLogicalOpForVector(const APFloat &LHSValue,
  2579. BinaryOperatorKind Opcode,
  2580. const APFloat &RHSValue, APInt &Result) {
  2581. bool LHS = !LHSValue.isZero();
  2582. bool RHS = !RHSValue.isZero();
  2583. if (Opcode == BO_LAnd)
  2584. Result = LHS && RHS;
  2585. else
  2586. Result = LHS || RHS;
  2587. return true;
  2588. }
  2589. static bool handleLogicalOpForVector(const APValue &LHSValue,
  2590. BinaryOperatorKind Opcode,
  2591. const APValue &RHSValue, APInt &Result) {
  2592. // The result is always an int type, however operands match the first.
  2593. if (LHSValue.getKind() == APValue::Int)
  2594. return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
  2595. RHSValue.getInt(), Result);
  2596. assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
  2597. return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
  2598. RHSValue.getFloat(), Result);
  2599. }
  2600. template <typename APTy>
  2601. static bool
  2602. handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
  2603. const APTy &RHSValue, APInt &Result) {
  2604. switch (Opcode) {
  2605. default:
  2606. llvm_unreachable("unsupported binary operator");
  2607. case BO_EQ:
  2608. Result = (LHSValue == RHSValue);
  2609. break;
  2610. case BO_NE:
  2611. Result = (LHSValue != RHSValue);
  2612. break;
  2613. case BO_LT:
  2614. Result = (LHSValue < RHSValue);
  2615. break;
  2616. case BO_GT:
  2617. Result = (LHSValue > RHSValue);
  2618. break;
  2619. case BO_LE:
  2620. Result = (LHSValue <= RHSValue);
  2621. break;
  2622. case BO_GE:
  2623. Result = (LHSValue >= RHSValue);
  2624. break;
  2625. }
  2626. // The boolean operations on these vector types use an instruction that
  2627. // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
  2628. // to -1 to make sure that we produce the correct value.
  2629. Result.negate();
  2630. return true;
  2631. }
  2632. static bool handleCompareOpForVector(const APValue &LHSValue,
  2633. BinaryOperatorKind Opcode,
  2634. const APValue &RHSValue, APInt &Result) {
  2635. // The result is always an int type, however operands match the first.
  2636. if (LHSValue.getKind() == APValue::Int)
  2637. return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
  2638. RHSValue.getInt(), Result);
  2639. assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
  2640. return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
  2641. RHSValue.getFloat(), Result);
  2642. }
  2643. // Perform binary operations for vector types, in place on the LHS.
  2644. static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
  2645. BinaryOperatorKind Opcode,
  2646. APValue &LHSValue,
  2647. const APValue &RHSValue) {
  2648. assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
  2649. "Operation not supported on vector types");
  2650. const auto *VT = E->getType()->castAs<VectorType>();
  2651. unsigned NumElements = VT->getNumElements();
  2652. QualType EltTy = VT->getElementType();
  2653. // In the cases (typically C as I've observed) where we aren't evaluating
  2654. // constexpr but are checking for cases where the LHS isn't yet evaluatable,
  2655. // just give up.
  2656. if (!LHSValue.isVector()) {
  2657. assert(LHSValue.isLValue() &&
  2658. "A vector result that isn't a vector OR uncalculated LValue");
  2659. Info.FFDiag(E);
  2660. return false;
  2661. }
  2662. assert(LHSValue.getVectorLength() == NumElements &&
  2663. RHSValue.getVectorLength() == NumElements && "Different vector sizes");
  2664. SmallVector<APValue, 4> ResultElements;
  2665. for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
  2666. APValue LHSElt = LHSValue.getVectorElt(EltNum);
  2667. APValue RHSElt = RHSValue.getVectorElt(EltNum);
  2668. if (EltTy->isIntegerType()) {
  2669. APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
  2670. EltTy->isUnsignedIntegerType()};
  2671. bool Success = true;
  2672. if (BinaryOperator::isLogicalOp(Opcode))
  2673. Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
  2674. else if (BinaryOperator::isComparisonOp(Opcode))
  2675. Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
  2676. else
  2677. Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
  2678. RHSElt.getInt(), EltResult);
  2679. if (!Success) {
  2680. Info.FFDiag(E);
  2681. return false;
  2682. }
  2683. ResultElements.emplace_back(EltResult);
  2684. } else if (EltTy->isFloatingType()) {
  2685. assert(LHSElt.getKind() == APValue::Float &&
  2686. RHSElt.getKind() == APValue::Float &&
  2687. "Mismatched LHS/RHS/Result Type");
  2688. APFloat LHSFloat = LHSElt.getFloat();
  2689. if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
  2690. RHSElt.getFloat())) {
  2691. Info.FFDiag(E);
  2692. return false;
  2693. }
  2694. ResultElements.emplace_back(LHSFloat);
  2695. }
  2696. }
  2697. LHSValue = APValue(ResultElements.data(), ResultElements.size());
  2698. return true;
  2699. }
  2700. /// Cast an lvalue referring to a base subobject to a derived class, by
  2701. /// truncating the lvalue's path to the given length.
  2702. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2703. const RecordDecl *TruncatedType,
  2704. unsigned TruncatedElements) {
  2705. SubobjectDesignator &D = Result.Designator;
  2706. // Check we actually point to a derived class object.
  2707. if (TruncatedElements == D.Entries.size())
  2708. return true;
  2709. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2710. "not casting to a derived class");
  2711. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2712. return false;
  2713. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2714. const RecordDecl *RD = TruncatedType;
  2715. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2716. if (RD->isInvalidDecl()) return false;
  2717. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2718. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2719. if (isVirtualBaseClass(D.Entries[I]))
  2720. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2721. else
  2722. Result.Offset -= Layout.getBaseClassOffset(Base);
  2723. RD = Base;
  2724. }
  2725. D.Entries.resize(TruncatedElements);
  2726. return true;
  2727. }
  2728. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2729. const CXXRecordDecl *Derived,
  2730. const CXXRecordDecl *Base,
  2731. const ASTRecordLayout *RL = nullptr) {
  2732. if (!RL) {
  2733. if (Derived->isInvalidDecl()) return false;
  2734. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2735. }
  2736. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2737. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2738. return true;
  2739. }
  2740. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2741. const CXXRecordDecl *DerivedDecl,
  2742. const CXXBaseSpecifier *Base) {
  2743. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2744. if (!Base->isVirtual())
  2745. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2746. SubobjectDesignator &D = Obj.Designator;
  2747. if (D.Invalid)
  2748. return false;
  2749. // Extract most-derived object and corresponding type.
  2750. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2751. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2752. return false;
  2753. // Find the virtual base class.
  2754. if (DerivedDecl->isInvalidDecl()) return false;
  2755. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2756. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2757. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2758. return true;
  2759. }
  2760. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2761. QualType Type, LValue &Result) {
  2762. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2763. PathE = E->path_end();
  2764. PathI != PathE; ++PathI) {
  2765. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2766. *PathI))
  2767. return false;
  2768. Type = (*PathI)->getType();
  2769. }
  2770. return true;
  2771. }
  2772. /// Cast an lvalue referring to a derived class to a known base subobject.
  2773. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2774. const CXXRecordDecl *DerivedRD,
  2775. const CXXRecordDecl *BaseRD) {
  2776. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2777. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2778. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2779. llvm_unreachable("Class must be derived from the passed in base class!");
  2780. for (CXXBasePathElement &Elem : Paths.front())
  2781. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2782. return false;
  2783. return true;
  2784. }
  2785. /// Update LVal to refer to the given field, which must be a member of the type
  2786. /// currently described by LVal.
  2787. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2788. const FieldDecl *FD,
  2789. const ASTRecordLayout *RL = nullptr) {
  2790. if (!RL) {
  2791. if (FD->getParent()->isInvalidDecl()) return false;
  2792. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2793. }
  2794. unsigned I = FD->getFieldIndex();
  2795. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2796. LVal.addDecl(Info, E, FD);
  2797. return true;
  2798. }
  2799. /// Update LVal to refer to the given indirect field.
  2800. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2801. LValue &LVal,
  2802. const IndirectFieldDecl *IFD) {
  2803. for (const auto *C : IFD->chain())
  2804. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2805. return false;
  2806. return true;
  2807. }
  2808. /// Get the size of the given type in char units.
  2809. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2810. QualType Type, CharUnits &Size) {
  2811. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2812. // extension.
  2813. if (Type->isVoidType() || Type->isFunctionType()) {
  2814. Size = CharUnits::One();
  2815. return true;
  2816. }
  2817. if (Type->isDependentType()) {
  2818. Info.FFDiag(Loc);
  2819. return false;
  2820. }
  2821. if (!Type->isConstantSizeType()) {
  2822. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2823. // FIXME: Better diagnostic.
  2824. Info.FFDiag(Loc);
  2825. return false;
  2826. }
  2827. Size = Info.Ctx.getTypeSizeInChars(Type);
  2828. return true;
  2829. }
  2830. /// Update a pointer value to model pointer arithmetic.
  2831. /// \param Info - Information about the ongoing evaluation.
  2832. /// \param E - The expression being evaluated, for diagnostic purposes.
  2833. /// \param LVal - The pointer value to be updated.
  2834. /// \param EltTy - The pointee type represented by LVal.
  2835. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2836. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2837. LValue &LVal, QualType EltTy,
  2838. APSInt Adjustment) {
  2839. CharUnits SizeOfPointee;
  2840. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2841. return false;
  2842. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2843. return true;
  2844. }
  2845. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2846. LValue &LVal, QualType EltTy,
  2847. int64_t Adjustment) {
  2848. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2849. APSInt::get(Adjustment));
  2850. }
  2851. /// Update an lvalue to refer to a component of a complex number.
  2852. /// \param Info - Information about the ongoing evaluation.
  2853. /// \param LVal - The lvalue to be updated.
  2854. /// \param EltTy - The complex number's component type.
  2855. /// \param Imag - False for the real component, true for the imaginary.
  2856. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2857. LValue &LVal, QualType EltTy,
  2858. bool Imag) {
  2859. if (Imag) {
  2860. CharUnits SizeOfComponent;
  2861. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2862. return false;
  2863. LVal.Offset += SizeOfComponent;
  2864. }
  2865. LVal.addComplex(Info, E, EltTy, Imag);
  2866. return true;
  2867. }
  2868. /// Try to evaluate the initializer for a variable declaration.
  2869. ///
  2870. /// \param Info Information about the ongoing evaluation.
  2871. /// \param E An expression to be used when printing diagnostics.
  2872. /// \param VD The variable whose initializer should be obtained.
  2873. /// \param Version The version of the variable within the frame.
  2874. /// \param Frame The frame in which the variable was created. Must be null
  2875. /// if this variable is not local to the evaluation.
  2876. /// \param Result Filled in with a pointer to the value of the variable.
  2877. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2878. const VarDecl *VD, CallStackFrame *Frame,
  2879. unsigned Version, APValue *&Result) {
  2880. APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
  2881. // If this is a local variable, dig out its value.
  2882. if (Frame) {
  2883. Result = Frame->getTemporary(VD, Version);
  2884. if (Result)
  2885. return true;
  2886. if (!isa<ParmVarDecl>(VD)) {
  2887. // Assume variables referenced within a lambda's call operator that were
  2888. // not declared within the call operator are captures and during checking
  2889. // of a potential constant expression, assume they are unknown constant
  2890. // expressions.
  2891. assert(isLambdaCallOperator(Frame->Callee) &&
  2892. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2893. "missing value for local variable");
  2894. if (Info.checkingPotentialConstantExpression())
  2895. return false;
  2896. // FIXME: This diagnostic is bogus; we do support captures. Is this code
  2897. // still reachable at all?
  2898. Info.FFDiag(E->getBeginLoc(),
  2899. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2900. << "captures not currently allowed";
  2901. return false;
  2902. }
  2903. }
  2904. // If we're currently evaluating the initializer of this declaration, use that
  2905. // in-flight value.
  2906. if (Info.EvaluatingDecl == Base) {
  2907. Result = Info.EvaluatingDeclValue;
  2908. return true;
  2909. }
  2910. if (isa<ParmVarDecl>(VD)) {
  2911. // Assume parameters of a potential constant expression are usable in
  2912. // constant expressions.
  2913. if (!Info.checkingPotentialConstantExpression() ||
  2914. !Info.CurrentCall->Callee ||
  2915. !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  2916. if (Info.getLangOpts().CPlusPlus11) {
  2917. Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
  2918. << VD;
  2919. NoteLValueLocation(Info, Base);
  2920. } else {
  2921. Info.FFDiag(E);
  2922. }
  2923. }
  2924. return false;
  2925. }
  2926. // Dig out the initializer, and use the declaration which it's attached to.
  2927. // FIXME: We should eventually check whether the variable has a reachable
  2928. // initializing declaration.
  2929. const Expr *Init = VD->getAnyInitializer(VD);
  2930. if (!Init) {
  2931. // Don't diagnose during potential constant expression checking; an
  2932. // initializer might be added later.
  2933. if (!Info.checkingPotentialConstantExpression()) {
  2934. Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
  2935. << VD;
  2936. NoteLValueLocation(Info, Base);
  2937. }
  2938. return false;
  2939. }
  2940. if (Init->isValueDependent()) {
  2941. // The DeclRefExpr is not value-dependent, but the variable it refers to
  2942. // has a value-dependent initializer. This should only happen in
  2943. // constant-folding cases, where the variable is not actually of a suitable
  2944. // type for use in a constant expression (otherwise the DeclRefExpr would
  2945. // have been value-dependent too), so diagnose that.
  2946. assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
  2947. if (!Info.checkingPotentialConstantExpression()) {
  2948. Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
  2949. ? diag::note_constexpr_ltor_non_constexpr
  2950. : diag::note_constexpr_ltor_non_integral, 1)
  2951. << VD << VD->getType();
  2952. NoteLValueLocation(Info, Base);
  2953. }
  2954. return false;
  2955. }
  2956. // Check that we can fold the initializer. In C++, we will have already done
  2957. // this in the cases where it matters for conformance.
  2958. if (!VD->evaluateValue()) {
  2959. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
  2960. NoteLValueLocation(Info, Base);
  2961. return false;
  2962. }
  2963. // Check that the variable is actually usable in constant expressions. For a
  2964. // const integral variable or a reference, we might have a non-constant
  2965. // initializer that we can nonetheless evaluate the initializer for. Such
  2966. // variables are not usable in constant expressions. In C++98, the
  2967. // initializer also syntactically needs to be an ICE.
  2968. //
  2969. // FIXME: We don't diagnose cases that aren't potentially usable in constant
  2970. // expressions here; doing so would regress diagnostics for things like
  2971. // reading from a volatile constexpr variable.
  2972. if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
  2973. VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
  2974. ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
  2975. !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
  2976. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
  2977. NoteLValueLocation(Info, Base);
  2978. }
  2979. // Never use the initializer of a weak variable, not even for constant
  2980. // folding. We can't be sure that this is the definition that will be used.
  2981. if (VD->isWeak()) {
  2982. Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
  2983. NoteLValueLocation(Info, Base);
  2984. return false;
  2985. }
  2986. Result = VD->getEvaluatedValue();
  2987. return true;
  2988. }
  2989. /// Get the base index of the given base class within an APValue representing
  2990. /// the given derived class.
  2991. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2992. const CXXRecordDecl *Base) {
  2993. Base = Base->getCanonicalDecl();
  2994. unsigned Index = 0;
  2995. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2996. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2997. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2998. return Index;
  2999. }
  3000. llvm_unreachable("base class missing from derived class's bases list");
  3001. }
  3002. /// Extract the value of a character from a string literal.
  3003. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  3004. uint64_t Index) {
  3005. assert(!isa<SourceLocExpr>(Lit) &&
  3006. "SourceLocExpr should have already been converted to a StringLiteral");
  3007. // FIXME: Support MakeStringConstant
  3008. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  3009. std::string Str;
  3010. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  3011. assert(Index <= Str.size() && "Index too large");
  3012. return APSInt::getUnsigned(Str.c_str()[Index]);
  3013. }
  3014. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  3015. Lit = PE->getFunctionName();
  3016. const StringLiteral *S = cast<StringLiteral>(Lit);
  3017. const ConstantArrayType *CAT =
  3018. Info.Ctx.getAsConstantArrayType(S->getType());
  3019. assert(CAT && "string literal isn't an array");
  3020. QualType CharType = CAT->getElementType();
  3021. assert(CharType->isIntegerType() && "unexpected character type");
  3022. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  3023. CharType->isUnsignedIntegerType());
  3024. if (Index < S->getLength())
  3025. Value = S->getCodeUnit(Index);
  3026. return Value;
  3027. }
  3028. // Expand a string literal into an array of characters.
  3029. //
  3030. // FIXME: This is inefficient; we should probably introduce something similar
  3031. // to the LLVM ConstantDataArray to make this cheaper.
  3032. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  3033. APValue &Result,
  3034. QualType AllocType = QualType()) {
  3035. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  3036. AllocType.isNull() ? S->getType() : AllocType);
  3037. assert(CAT && "string literal isn't an array");
  3038. QualType CharType = CAT->getElementType();
  3039. assert(CharType->isIntegerType() && "unexpected character type");
  3040. unsigned Elts = CAT->getSize().getZExtValue();
  3041. Result = APValue(APValue::UninitArray(),
  3042. std::min(S->getLength(), Elts), Elts);
  3043. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  3044. CharType->isUnsignedIntegerType());
  3045. if (Result.hasArrayFiller())
  3046. Result.getArrayFiller() = APValue(Value);
  3047. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  3048. Value = S->getCodeUnit(I);
  3049. Result.getArrayInitializedElt(I) = APValue(Value);
  3050. }
  3051. }
  3052. // Expand an array so that it has more than Index filled elements.
  3053. static void expandArray(APValue &Array, unsigned Index) {
  3054. unsigned Size = Array.getArraySize();
  3055. assert(Index < Size);
  3056. // Always at least double the number of elements for which we store a value.
  3057. unsigned OldElts = Array.getArrayInitializedElts();
  3058. unsigned NewElts = std::max(Index+1, OldElts * 2);
  3059. NewElts = std::min(Size, std::max(NewElts, 8u));
  3060. // Copy the data across.
  3061. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  3062. for (unsigned I = 0; I != OldElts; ++I)
  3063. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  3064. for (unsigned I = OldElts; I != NewElts; ++I)
  3065. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  3066. if (NewValue.hasArrayFiller())
  3067. NewValue.getArrayFiller() = Array.getArrayFiller();
  3068. Array.swap(NewValue);
  3069. }
  3070. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  3071. /// conversion. If it's of class type, we may assume that the copy operation
  3072. /// is trivial. Note that this is never true for a union type with fields
  3073. /// (because the copy always "reads" the active member) and always true for
  3074. /// a non-class type.
  3075. static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
  3076. static bool isReadByLvalueToRvalueConversion(QualType T) {
  3077. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  3078. return !RD || isReadByLvalueToRvalueConversion(RD);
  3079. }
  3080. static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
  3081. // FIXME: A trivial copy of a union copies the object representation, even if
  3082. // the union is empty.
  3083. if (RD->isUnion())
  3084. return !RD->field_empty();
  3085. if (RD->isEmpty())
  3086. return false;
  3087. for (auto *Field : RD->fields())
  3088. if (!Field->isUnnamedBitfield() &&
  3089. isReadByLvalueToRvalueConversion(Field->getType()))
  3090. return true;
  3091. for (auto &BaseSpec : RD->bases())
  3092. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  3093. return true;
  3094. return false;
  3095. }
  3096. /// Diagnose an attempt to read from any unreadable field within the specified
  3097. /// type, which might be a class type.
  3098. static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
  3099. QualType T) {
  3100. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  3101. if (!RD)
  3102. return false;
  3103. if (!RD->hasMutableFields())
  3104. return false;
  3105. for (auto *Field : RD->fields()) {
  3106. // If we're actually going to read this field in some way, then it can't
  3107. // be mutable. If we're in a union, then assigning to a mutable field
  3108. // (even an empty one) can change the active member, so that's not OK.
  3109. // FIXME: Add core issue number for the union case.
  3110. if (Field->isMutable() &&
  3111. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  3112. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
  3113. Info.Note(Field->getLocation(), diag::note_declared_at);
  3114. return true;
  3115. }
  3116. if (diagnoseMutableFields(Info, E, AK, Field->getType()))
  3117. return true;
  3118. }
  3119. for (auto &BaseSpec : RD->bases())
  3120. if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
  3121. return true;
  3122. // All mutable fields were empty, and thus not actually read.
  3123. return false;
  3124. }
  3125. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  3126. APValue::LValueBase Base,
  3127. bool MutableSubobject = false) {
  3128. // A temporary or transient heap allocation we created.
  3129. if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
  3130. return true;
  3131. switch (Info.IsEvaluatingDecl) {
  3132. case EvalInfo::EvaluatingDeclKind::None:
  3133. return false;
  3134. case EvalInfo::EvaluatingDeclKind::Ctor:
  3135. // The variable whose initializer we're evaluating.
  3136. if (Info.EvaluatingDecl == Base)
  3137. return true;
  3138. // A temporary lifetime-extended by the variable whose initializer we're
  3139. // evaluating.
  3140. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  3141. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  3142. return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
  3143. return false;
  3144. case EvalInfo::EvaluatingDeclKind::Dtor:
  3145. // C++2a [expr.const]p6:
  3146. // [during constant destruction] the lifetime of a and its non-mutable
  3147. // subobjects (but not its mutable subobjects) [are] considered to start
  3148. // within e.
  3149. if (MutableSubobject || Base != Info.EvaluatingDecl)
  3150. return false;
  3151. // FIXME: We can meaningfully extend this to cover non-const objects, but
  3152. // we will need special handling: we should be able to access only
  3153. // subobjects of such objects that are themselves declared const.
  3154. QualType T = getType(Base);
  3155. return T.isConstQualified() || T->isReferenceType();
  3156. }
  3157. llvm_unreachable("unknown evaluating decl kind");
  3158. }
  3159. namespace {
  3160. /// A handle to a complete object (an object that is not a subobject of
  3161. /// another object).
  3162. struct CompleteObject {
  3163. /// The identity of the object.
  3164. APValue::LValueBase Base;
  3165. /// The value of the complete object.
  3166. APValue *Value;
  3167. /// The type of the complete object.
  3168. QualType Type;
  3169. CompleteObject() : Value(nullptr) {}
  3170. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  3171. : Base(Base), Value(Value), Type(Type) {}
  3172. bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
  3173. // If this isn't a "real" access (eg, if it's just accessing the type
  3174. // info), allow it. We assume the type doesn't change dynamically for
  3175. // subobjects of constexpr objects (even though we'd hit UB here if it
  3176. // did). FIXME: Is this right?
  3177. if (!isAnyAccess(AK))
  3178. return true;
  3179. // In C++14 onwards, it is permitted to read a mutable member whose
  3180. // lifetime began within the evaluation.
  3181. // FIXME: Should we also allow this in C++11?
  3182. if (!Info.getLangOpts().CPlusPlus14)
  3183. return false;
  3184. return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
  3185. }
  3186. explicit operator bool() const { return !Type.isNull(); }
  3187. };
  3188. } // end anonymous namespace
  3189. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  3190. bool IsMutable = false) {
  3191. // C++ [basic.type.qualifier]p1:
  3192. // - A const object is an object of type const T or a non-mutable subobject
  3193. // of a const object.
  3194. if (ObjType.isConstQualified() && !IsMutable)
  3195. SubobjType.addConst();
  3196. // - A volatile object is an object of type const T or a subobject of a
  3197. // volatile object.
  3198. if (ObjType.isVolatileQualified())
  3199. SubobjType.addVolatile();
  3200. return SubobjType;
  3201. }
  3202. /// Find the designated sub-object of an rvalue.
  3203. template<typename SubobjectHandler>
  3204. typename SubobjectHandler::result_type
  3205. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  3206. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  3207. if (Sub.Invalid)
  3208. // A diagnostic will have already been produced.
  3209. return handler.failed();
  3210. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  3211. if (Info.getLangOpts().CPlusPlus11)
  3212. Info.FFDiag(E, Sub.isOnePastTheEnd()
  3213. ? diag::note_constexpr_access_past_end
  3214. : diag::note_constexpr_access_unsized_array)
  3215. << handler.AccessKind;
  3216. else
  3217. Info.FFDiag(E);
  3218. return handler.failed();
  3219. }
  3220. APValue *O = Obj.Value;
  3221. QualType ObjType = Obj.Type;
  3222. const FieldDecl *LastField = nullptr;
  3223. const FieldDecl *VolatileField = nullptr;
  3224. // Walk the designator's path to find the subobject.
  3225. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  3226. // Reading an indeterminate value is undefined, but assigning over one is OK.
  3227. if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
  3228. (O->isIndeterminate() &&
  3229. !isValidIndeterminateAccess(handler.AccessKind))) {
  3230. if (!Info.checkingPotentialConstantExpression())
  3231. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  3232. << handler.AccessKind << O->isIndeterminate();
  3233. return handler.failed();
  3234. }
  3235. // C++ [class.ctor]p5, C++ [class.dtor]p5:
  3236. // const and volatile semantics are not applied on an object under
  3237. // {con,de}struction.
  3238. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  3239. ObjType->isRecordType() &&
  3240. Info.isEvaluatingCtorDtor(
  3241. Obj.Base,
  3242. llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
  3243. ConstructionPhase::None) {
  3244. ObjType = Info.Ctx.getCanonicalType(ObjType);
  3245. ObjType.removeLocalConst();
  3246. ObjType.removeLocalVolatile();
  3247. }
  3248. // If this is our last pass, check that the final object type is OK.
  3249. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  3250. // Accesses to volatile objects are prohibited.
  3251. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  3252. if (Info.getLangOpts().CPlusPlus) {
  3253. int DiagKind;
  3254. SourceLocation Loc;
  3255. const NamedDecl *Decl = nullptr;
  3256. if (VolatileField) {
  3257. DiagKind = 2;
  3258. Loc = VolatileField->getLocation();
  3259. Decl = VolatileField;
  3260. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  3261. DiagKind = 1;
  3262. Loc = VD->getLocation();
  3263. Decl = VD;
  3264. } else {
  3265. DiagKind = 0;
  3266. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  3267. Loc = E->getExprLoc();
  3268. }
  3269. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  3270. << handler.AccessKind << DiagKind << Decl;
  3271. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  3272. } else {
  3273. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  3274. }
  3275. return handler.failed();
  3276. }
  3277. // If we are reading an object of class type, there may still be more
  3278. // things we need to check: if there are any mutable subobjects, we
  3279. // cannot perform this read. (This only happens when performing a trivial
  3280. // copy or assignment.)
  3281. if (ObjType->isRecordType() &&
  3282. !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
  3283. diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
  3284. return handler.failed();
  3285. }
  3286. if (I == N) {
  3287. if (!handler.found(*O, ObjType))
  3288. return false;
  3289. // If we modified a bit-field, truncate it to the right width.
  3290. if (isModification(handler.AccessKind) &&
  3291. LastField && LastField->isBitField() &&
  3292. !truncateBitfieldValue(Info, E, *O, LastField))
  3293. return false;
  3294. return true;
  3295. }
  3296. LastField = nullptr;
  3297. if (ObjType->isArrayType()) {
  3298. // Next subobject is an array element.
  3299. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  3300. assert(CAT && "vla in literal type?");
  3301. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  3302. if (CAT->getSize().ule(Index)) {
  3303. // Note, it should not be possible to form a pointer with a valid
  3304. // designator which points more than one past the end of the array.
  3305. if (Info.getLangOpts().CPlusPlus11)
  3306. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  3307. << handler.AccessKind;
  3308. else
  3309. Info.FFDiag(E);
  3310. return handler.failed();
  3311. }
  3312. ObjType = CAT->getElementType();
  3313. if (O->getArrayInitializedElts() > Index)
  3314. O = &O->getArrayInitializedElt(Index);
  3315. else if (!isRead(handler.AccessKind)) {
  3316. expandArray(*O, Index);
  3317. O = &O->getArrayInitializedElt(Index);
  3318. } else
  3319. O = &O->getArrayFiller();
  3320. } else if (ObjType->isAnyComplexType()) {
  3321. // Next subobject is a complex number.
  3322. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  3323. if (Index > 1) {
  3324. if (Info.getLangOpts().CPlusPlus11)
  3325. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  3326. << handler.AccessKind;
  3327. else
  3328. Info.FFDiag(E);
  3329. return handler.failed();
  3330. }
  3331. ObjType = getSubobjectType(
  3332. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  3333. assert(I == N - 1 && "extracting subobject of scalar?");
  3334. if (O->isComplexInt()) {
  3335. return handler.found(Index ? O->getComplexIntImag()
  3336. : O->getComplexIntReal(), ObjType);
  3337. } else {
  3338. assert(O->isComplexFloat());
  3339. return handler.found(Index ? O->getComplexFloatImag()
  3340. : O->getComplexFloatReal(), ObjType);
  3341. }
  3342. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  3343. if (Field->isMutable() &&
  3344. !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
  3345. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
  3346. << handler.AccessKind << Field;
  3347. Info.Note(Field->getLocation(), diag::note_declared_at);
  3348. return handler.failed();
  3349. }
  3350. // Next subobject is a class, struct or union field.
  3351. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  3352. if (RD->isUnion()) {
  3353. const FieldDecl *UnionField = O->getUnionField();
  3354. if (!UnionField ||
  3355. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  3356. if (I == N - 1 && handler.AccessKind == AK_Construct) {
  3357. // Placement new onto an inactive union member makes it active.
  3358. O->setUnion(Field, APValue());
  3359. } else {
  3360. // FIXME: If O->getUnionValue() is absent, report that there's no
  3361. // active union member rather than reporting the prior active union
  3362. // member. We'll need to fix nullptr_t to not use APValue() as its
  3363. // representation first.
  3364. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  3365. << handler.AccessKind << Field << !UnionField << UnionField;
  3366. return handler.failed();
  3367. }
  3368. }
  3369. O = &O->getUnionValue();
  3370. } else
  3371. O = &O->getStructField(Field->getFieldIndex());
  3372. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  3373. LastField = Field;
  3374. if (Field->getType().isVolatileQualified())
  3375. VolatileField = Field;
  3376. } else {
  3377. // Next subobject is a base class.
  3378. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  3379. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  3380. O = &O->getStructBase(getBaseIndex(Derived, Base));
  3381. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  3382. }
  3383. }
  3384. }
  3385. namespace {
  3386. struct ExtractSubobjectHandler {
  3387. EvalInfo &Info;
  3388. const Expr *E;
  3389. APValue &Result;
  3390. const AccessKinds AccessKind;
  3391. typedef bool result_type;
  3392. bool failed() { return false; }
  3393. bool found(APValue &Subobj, QualType SubobjType) {
  3394. Result = Subobj;
  3395. if (AccessKind == AK_ReadObjectRepresentation)
  3396. return true;
  3397. return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
  3398. }
  3399. bool found(APSInt &Value, QualType SubobjType) {
  3400. Result = APValue(Value);
  3401. return true;
  3402. }
  3403. bool found(APFloat &Value, QualType SubobjType) {
  3404. Result = APValue(Value);
  3405. return true;
  3406. }
  3407. };
  3408. } // end anonymous namespace
  3409. /// Extract the designated sub-object of an rvalue.
  3410. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  3411. const CompleteObject &Obj,
  3412. const SubobjectDesignator &Sub, APValue &Result,
  3413. AccessKinds AK = AK_Read) {
  3414. assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
  3415. ExtractSubobjectHandler Handler = {Info, E, Result, AK};
  3416. return findSubobject(Info, E, Obj, Sub, Handler);
  3417. }
  3418. namespace {
  3419. struct ModifySubobjectHandler {
  3420. EvalInfo &Info;
  3421. APValue &NewVal;
  3422. const Expr *E;
  3423. typedef bool result_type;
  3424. static const AccessKinds AccessKind = AK_Assign;
  3425. bool checkConst(QualType QT) {
  3426. // Assigning to a const object has undefined behavior.
  3427. if (QT.isConstQualified()) {
  3428. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3429. return false;
  3430. }
  3431. return true;
  3432. }
  3433. bool failed() { return false; }
  3434. bool found(APValue &Subobj, QualType SubobjType) {
  3435. if (!checkConst(SubobjType))
  3436. return false;
  3437. // We've been given ownership of NewVal, so just swap it in.
  3438. Subobj.swap(NewVal);
  3439. return true;
  3440. }
  3441. bool found(APSInt &Value, QualType SubobjType) {
  3442. if (!checkConst(SubobjType))
  3443. return false;
  3444. if (!NewVal.isInt()) {
  3445. // Maybe trying to write a cast pointer value into a complex?
  3446. Info.FFDiag(E);
  3447. return false;
  3448. }
  3449. Value = NewVal.getInt();
  3450. return true;
  3451. }
  3452. bool found(APFloat &Value, QualType SubobjType) {
  3453. if (!checkConst(SubobjType))
  3454. return false;
  3455. Value = NewVal.getFloat();
  3456. return true;
  3457. }
  3458. };
  3459. } // end anonymous namespace
  3460. const AccessKinds ModifySubobjectHandler::AccessKind;
  3461. /// Update the designated sub-object of an rvalue to the given value.
  3462. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  3463. const CompleteObject &Obj,
  3464. const SubobjectDesignator &Sub,
  3465. APValue &NewVal) {
  3466. ModifySubobjectHandler Handler = { Info, NewVal, E };
  3467. return findSubobject(Info, E, Obj, Sub, Handler);
  3468. }
  3469. /// Find the position where two subobject designators diverge, or equivalently
  3470. /// the length of the common initial subsequence.
  3471. static unsigned FindDesignatorMismatch(QualType ObjType,
  3472. const SubobjectDesignator &A,
  3473. const SubobjectDesignator &B,
  3474. bool &WasArrayIndex) {
  3475. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  3476. for (/**/; I != N; ++I) {
  3477. if (!ObjType.isNull() &&
  3478. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  3479. // Next subobject is an array element.
  3480. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  3481. WasArrayIndex = true;
  3482. return I;
  3483. }
  3484. if (ObjType->isAnyComplexType())
  3485. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  3486. else
  3487. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  3488. } else {
  3489. if (A.Entries[I].getAsBaseOrMember() !=
  3490. B.Entries[I].getAsBaseOrMember()) {
  3491. WasArrayIndex = false;
  3492. return I;
  3493. }
  3494. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  3495. // Next subobject is a field.
  3496. ObjType = FD->getType();
  3497. else
  3498. // Next subobject is a base class.
  3499. ObjType = QualType();
  3500. }
  3501. }
  3502. WasArrayIndex = false;
  3503. return I;
  3504. }
  3505. /// Determine whether the given subobject designators refer to elements of the
  3506. /// same array object.
  3507. static bool AreElementsOfSameArray(QualType ObjType,
  3508. const SubobjectDesignator &A,
  3509. const SubobjectDesignator &B) {
  3510. if (A.Entries.size() != B.Entries.size())
  3511. return false;
  3512. bool IsArray = A.MostDerivedIsArrayElement;
  3513. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  3514. // A is a subobject of the array element.
  3515. return false;
  3516. // If A (and B) designates an array element, the last entry will be the array
  3517. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  3518. // of length 1' case, and the entire path must match.
  3519. bool WasArrayIndex;
  3520. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  3521. return CommonLength >= A.Entries.size() - IsArray;
  3522. }
  3523. /// Find the complete object to which an LValue refers.
  3524. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  3525. AccessKinds AK, const LValue &LVal,
  3526. QualType LValType) {
  3527. if (LVal.InvalidBase) {
  3528. Info.FFDiag(E);
  3529. return CompleteObject();
  3530. }
  3531. if (!LVal.Base) {
  3532. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  3533. return CompleteObject();
  3534. }
  3535. CallStackFrame *Frame = nullptr;
  3536. unsigned Depth = 0;
  3537. if (LVal.getLValueCallIndex()) {
  3538. std::tie(Frame, Depth) =
  3539. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  3540. if (!Frame) {
  3541. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  3542. << AK << LVal.Base.is<const ValueDecl*>();
  3543. NoteLValueLocation(Info, LVal.Base);
  3544. return CompleteObject();
  3545. }
  3546. }
  3547. bool IsAccess = isAnyAccess(AK);
  3548. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  3549. // is not a constant expression (even if the object is non-volatile). We also
  3550. // apply this rule to C++98, in order to conform to the expected 'volatile'
  3551. // semantics.
  3552. if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
  3553. if (Info.getLangOpts().CPlusPlus)
  3554. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  3555. << AK << LValType;
  3556. else
  3557. Info.FFDiag(E);
  3558. return CompleteObject();
  3559. }
  3560. // Compute value storage location and type of base object.
  3561. APValue *BaseVal = nullptr;
  3562. QualType BaseType = getType(LVal.Base);
  3563. if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
  3564. lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3565. // This is the object whose initializer we're evaluating, so its lifetime
  3566. // started in the current evaluation.
  3567. BaseVal = Info.EvaluatingDeclValue;
  3568. } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
  3569. // Allow reading from a GUID declaration.
  3570. if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
  3571. if (isModification(AK)) {
  3572. // All the remaining cases do not permit modification of the object.
  3573. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3574. return CompleteObject();
  3575. }
  3576. APValue &V = GD->getAsAPValue();
  3577. if (V.isAbsent()) {
  3578. Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
  3579. << GD->getType();
  3580. return CompleteObject();
  3581. }
  3582. return CompleteObject(LVal.Base, &V, GD->getType());
  3583. }
  3584. // Allow reading the APValue from an UnnamedGlobalConstantDecl.
  3585. if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
  3586. if (isModification(AK)) {
  3587. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3588. return CompleteObject();
  3589. }
  3590. return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
  3591. GCD->getType());
  3592. }
  3593. // Allow reading from template parameter objects.
  3594. if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
  3595. if (isModification(AK)) {
  3596. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3597. return CompleteObject();
  3598. }
  3599. return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
  3600. TPO->getType());
  3601. }
  3602. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  3603. // In C++11, constexpr, non-volatile variables initialized with constant
  3604. // expressions are constant expressions too. Inside constexpr functions,
  3605. // parameters are constant expressions even if they're non-const.
  3606. // In C++1y, objects local to a constant expression (those with a Frame) are
  3607. // both readable and writable inside constant expressions.
  3608. // In C, such things can also be folded, although they are not ICEs.
  3609. const VarDecl *VD = dyn_cast<VarDecl>(D);
  3610. if (VD) {
  3611. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  3612. VD = VDef;
  3613. }
  3614. if (!VD || VD->isInvalidDecl()) {
  3615. Info.FFDiag(E);
  3616. return CompleteObject();
  3617. }
  3618. bool IsConstant = BaseType.isConstant(Info.Ctx);
  3619. // Unless we're looking at a local variable or argument in a constexpr call,
  3620. // the variable we're reading must be const.
  3621. if (!Frame) {
  3622. if (IsAccess && isa<ParmVarDecl>(VD)) {
  3623. // Access of a parameter that's not associated with a frame isn't going
  3624. // to work out, but we can leave it to evaluateVarDeclInit to provide a
  3625. // suitable diagnostic.
  3626. } else if (Info.getLangOpts().CPlusPlus14 &&
  3627. lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3628. // OK, we can read and modify an object if we're in the process of
  3629. // evaluating its initializer, because its lifetime began in this
  3630. // evaluation.
  3631. } else if (isModification(AK)) {
  3632. // All the remaining cases do not permit modification of the object.
  3633. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3634. return CompleteObject();
  3635. } else if (VD->isConstexpr()) {
  3636. // OK, we can read this variable.
  3637. } else if (BaseType->isIntegralOrEnumerationType()) {
  3638. if (!IsConstant) {
  3639. if (!IsAccess)
  3640. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3641. if (Info.getLangOpts().CPlusPlus) {
  3642. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  3643. Info.Note(VD->getLocation(), diag::note_declared_at);
  3644. } else {
  3645. Info.FFDiag(E);
  3646. }
  3647. return CompleteObject();
  3648. }
  3649. } else if (!IsAccess) {
  3650. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3651. } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
  3652. BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
  3653. // This variable might end up being constexpr. Don't diagnose it yet.
  3654. } else if (IsConstant) {
  3655. // Keep evaluating to see what we can do. In particular, we support
  3656. // folding of const floating-point types, in order to make static const
  3657. // data members of such types (supported as an extension) more useful.
  3658. if (Info.getLangOpts().CPlusPlus) {
  3659. Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
  3660. ? diag::note_constexpr_ltor_non_constexpr
  3661. : diag::note_constexpr_ltor_non_integral, 1)
  3662. << VD << BaseType;
  3663. Info.Note(VD->getLocation(), diag::note_declared_at);
  3664. } else {
  3665. Info.CCEDiag(E);
  3666. }
  3667. } else {
  3668. // Never allow reading a non-const value.
  3669. if (Info.getLangOpts().CPlusPlus) {
  3670. Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
  3671. ? diag::note_constexpr_ltor_non_constexpr
  3672. : diag::note_constexpr_ltor_non_integral, 1)
  3673. << VD << BaseType;
  3674. Info.Note(VD->getLocation(), diag::note_declared_at);
  3675. } else {
  3676. Info.FFDiag(E);
  3677. }
  3678. return CompleteObject();
  3679. }
  3680. }
  3681. if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
  3682. return CompleteObject();
  3683. } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
  3684. std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
  3685. if (!Alloc) {
  3686. Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
  3687. return CompleteObject();
  3688. }
  3689. return CompleteObject(LVal.Base, &(*Alloc)->Value,
  3690. LVal.Base.getDynamicAllocType());
  3691. } else {
  3692. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3693. if (!Frame) {
  3694. if (const MaterializeTemporaryExpr *MTE =
  3695. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  3696. assert(MTE->getStorageDuration() == SD_Static &&
  3697. "should have a frame for a non-global materialized temporary");
  3698. // C++20 [expr.const]p4: [DR2126]
  3699. // An object or reference is usable in constant expressions if it is
  3700. // - a temporary object of non-volatile const-qualified literal type
  3701. // whose lifetime is extended to that of a variable that is usable
  3702. // in constant expressions
  3703. //
  3704. // C++20 [expr.const]p5:
  3705. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3706. // - a non-volatile glvalue that refers to an object that is usable
  3707. // in constant expressions, or
  3708. // - a non-volatile glvalue of literal type that refers to a
  3709. // non-volatile object whose lifetime began within the evaluation
  3710. // of E;
  3711. //
  3712. // C++11 misses the 'began within the evaluation of e' check and
  3713. // instead allows all temporaries, including things like:
  3714. // int &&r = 1;
  3715. // int x = ++r;
  3716. // constexpr int k = r;
  3717. // Therefore we use the C++14-onwards rules in C++11 too.
  3718. //
  3719. // Note that temporaries whose lifetimes began while evaluating a
  3720. // variable's constructor are not usable while evaluating the
  3721. // corresponding destructor, not even if they're of const-qualified
  3722. // types.
  3723. if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
  3724. !lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3725. if (!IsAccess)
  3726. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3727. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3728. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3729. return CompleteObject();
  3730. }
  3731. BaseVal = MTE->getOrCreateValue(false);
  3732. assert(BaseVal && "got reference to unevaluated temporary");
  3733. } else {
  3734. if (!IsAccess)
  3735. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3736. APValue Val;
  3737. LVal.moveInto(Val);
  3738. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  3739. << AK
  3740. << Val.getAsString(Info.Ctx,
  3741. Info.Ctx.getLValueReferenceType(LValType));
  3742. NoteLValueLocation(Info, LVal.Base);
  3743. return CompleteObject();
  3744. }
  3745. } else {
  3746. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3747. assert(BaseVal && "missing value for temporary");
  3748. }
  3749. }
  3750. // In C++14, we can't safely access any mutable state when we might be
  3751. // evaluating after an unmodeled side effect. Parameters are modeled as state
  3752. // in the caller, but aren't visible once the call returns, so they can be
  3753. // modified in a speculatively-evaluated call.
  3754. //
  3755. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3756. // to be read here (but take care with 'mutable' fields).
  3757. unsigned VisibleDepth = Depth;
  3758. if (llvm::isa_and_nonnull<ParmVarDecl>(
  3759. LVal.Base.dyn_cast<const ValueDecl *>()))
  3760. ++VisibleDepth;
  3761. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3762. Info.EvalStatus.HasSideEffects) ||
  3763. (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
  3764. return CompleteObject();
  3765. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3766. }
  3767. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3768. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3769. /// glvalue referred to by an entity of reference type.
  3770. ///
  3771. /// \param Info - Information about the ongoing evaluation.
  3772. /// \param Conv - The expression for which we are performing the conversion.
  3773. /// Used for diagnostics.
  3774. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3775. /// case of a non-class type).
  3776. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3777. /// \param RVal - The produced value will be placed here.
  3778. /// \param WantObjectRepresentation - If true, we're looking for the object
  3779. /// representation rather than the value, and in particular,
  3780. /// there is no requirement that the result be fully initialized.
  3781. static bool
  3782. handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
  3783. const LValue &LVal, APValue &RVal,
  3784. bool WantObjectRepresentation = false) {
  3785. if (LVal.Designator.Invalid)
  3786. return false;
  3787. // Check for special cases where there is no existing APValue to look at.
  3788. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3789. AccessKinds AK =
  3790. WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
  3791. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3792. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3793. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3794. // initializer until now for such expressions. Such an expression can't be
  3795. // an ICE in C, so this only matters for fold.
  3796. if (Type.isVolatileQualified()) {
  3797. Info.FFDiag(Conv);
  3798. return false;
  3799. }
  3800. APValue Lit;
  3801. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3802. return false;
  3803. // According to GCC info page:
  3804. //
  3805. // 6.28 Compound Literals
  3806. //
  3807. // As an optimization, G++ sometimes gives array compound literals longer
  3808. // lifetimes: when the array either appears outside a function or has a
  3809. // const-qualified type. If foo and its initializer had elements of type
  3810. // char *const rather than char *, or if foo were a global variable, the
  3811. // array would have static storage duration. But it is probably safest
  3812. // just to avoid the use of array compound literals in C++ code.
  3813. //
  3814. // Obey that rule by checking constness for converted array types.
  3815. QualType CLETy = CLE->getType();
  3816. if (CLETy->isArrayType() && !Type->isArrayType()) {
  3817. if (!CLETy.isConstant(Info.Ctx)) {
  3818. Info.FFDiag(Conv);
  3819. Info.Note(CLE->getExprLoc(), diag::note_declared_at);
  3820. return false;
  3821. }
  3822. }
  3823. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3824. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
  3825. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3826. // Special-case character extraction so we don't have to construct an
  3827. // APValue for the whole string.
  3828. assert(LVal.Designator.Entries.size() <= 1 &&
  3829. "Can only read characters from string literals");
  3830. if (LVal.Designator.Entries.empty()) {
  3831. // Fail for now for LValue to RValue conversion of an array.
  3832. // (This shouldn't show up in C/C++, but it could be triggered by a
  3833. // weird EvaluateAsRValue call from a tool.)
  3834. Info.FFDiag(Conv);
  3835. return false;
  3836. }
  3837. if (LVal.Designator.isOnePastTheEnd()) {
  3838. if (Info.getLangOpts().CPlusPlus11)
  3839. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
  3840. else
  3841. Info.FFDiag(Conv);
  3842. return false;
  3843. }
  3844. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3845. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3846. return true;
  3847. }
  3848. }
  3849. CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
  3850. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
  3851. }
  3852. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3853. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3854. QualType LValType, APValue &Val) {
  3855. if (LVal.Designator.Invalid)
  3856. return false;
  3857. if (!Info.getLangOpts().CPlusPlus14) {
  3858. Info.FFDiag(E);
  3859. return false;
  3860. }
  3861. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3862. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3863. }
  3864. namespace {
  3865. struct CompoundAssignSubobjectHandler {
  3866. EvalInfo &Info;
  3867. const CompoundAssignOperator *E;
  3868. QualType PromotedLHSType;
  3869. BinaryOperatorKind Opcode;
  3870. const APValue &RHS;
  3871. static const AccessKinds AccessKind = AK_Assign;
  3872. typedef bool result_type;
  3873. bool checkConst(QualType QT) {
  3874. // Assigning to a const object has undefined behavior.
  3875. if (QT.isConstQualified()) {
  3876. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3877. return false;
  3878. }
  3879. return true;
  3880. }
  3881. bool failed() { return false; }
  3882. bool found(APValue &Subobj, QualType SubobjType) {
  3883. switch (Subobj.getKind()) {
  3884. case APValue::Int:
  3885. return found(Subobj.getInt(), SubobjType);
  3886. case APValue::Float:
  3887. return found(Subobj.getFloat(), SubobjType);
  3888. case APValue::ComplexInt:
  3889. case APValue::ComplexFloat:
  3890. // FIXME: Implement complex compound assignment.
  3891. Info.FFDiag(E);
  3892. return false;
  3893. case APValue::LValue:
  3894. return foundPointer(Subobj, SubobjType);
  3895. case APValue::Vector:
  3896. return foundVector(Subobj, SubobjType);
  3897. default:
  3898. // FIXME: can this happen?
  3899. Info.FFDiag(E);
  3900. return false;
  3901. }
  3902. }
  3903. bool foundVector(APValue &Value, QualType SubobjType) {
  3904. if (!checkConst(SubobjType))
  3905. return false;
  3906. if (!SubobjType->isVectorType()) {
  3907. Info.FFDiag(E);
  3908. return false;
  3909. }
  3910. return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
  3911. }
  3912. bool found(APSInt &Value, QualType SubobjType) {
  3913. if (!checkConst(SubobjType))
  3914. return false;
  3915. if (!SubobjType->isIntegerType()) {
  3916. // We don't support compound assignment on integer-cast-to-pointer
  3917. // values.
  3918. Info.FFDiag(E);
  3919. return false;
  3920. }
  3921. if (RHS.isInt()) {
  3922. APSInt LHS =
  3923. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3924. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3925. return false;
  3926. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3927. return true;
  3928. } else if (RHS.isFloat()) {
  3929. const FPOptions FPO = E->getFPFeaturesInEffect(
  3930. Info.Ctx.getLangOpts());
  3931. APFloat FValue(0.0);
  3932. return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
  3933. PromotedLHSType, FValue) &&
  3934. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3935. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3936. Value);
  3937. }
  3938. Info.FFDiag(E);
  3939. return false;
  3940. }
  3941. bool found(APFloat &Value, QualType SubobjType) {
  3942. return checkConst(SubobjType) &&
  3943. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3944. Value) &&
  3945. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3946. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3947. }
  3948. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3949. if (!checkConst(SubobjType))
  3950. return false;
  3951. QualType PointeeType;
  3952. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3953. PointeeType = PT->getPointeeType();
  3954. if (PointeeType.isNull() || !RHS.isInt() ||
  3955. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3956. Info.FFDiag(E);
  3957. return false;
  3958. }
  3959. APSInt Offset = RHS.getInt();
  3960. if (Opcode == BO_Sub)
  3961. negateAsSigned(Offset);
  3962. LValue LVal;
  3963. LVal.setFrom(Info.Ctx, Subobj);
  3964. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3965. return false;
  3966. LVal.moveInto(Subobj);
  3967. return true;
  3968. }
  3969. };
  3970. } // end anonymous namespace
  3971. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3972. /// Perform a compound assignment of LVal <op>= RVal.
  3973. static bool handleCompoundAssignment(EvalInfo &Info,
  3974. const CompoundAssignOperator *E,
  3975. const LValue &LVal, QualType LValType,
  3976. QualType PromotedLValType,
  3977. BinaryOperatorKind Opcode,
  3978. const APValue &RVal) {
  3979. if (LVal.Designator.Invalid)
  3980. return false;
  3981. if (!Info.getLangOpts().CPlusPlus14) {
  3982. Info.FFDiag(E);
  3983. return false;
  3984. }
  3985. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3986. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3987. RVal };
  3988. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3989. }
  3990. namespace {
  3991. struct IncDecSubobjectHandler {
  3992. EvalInfo &Info;
  3993. const UnaryOperator *E;
  3994. AccessKinds AccessKind;
  3995. APValue *Old;
  3996. typedef bool result_type;
  3997. bool checkConst(QualType QT) {
  3998. // Assigning to a const object has undefined behavior.
  3999. if (QT.isConstQualified()) {
  4000. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  4001. return false;
  4002. }
  4003. return true;
  4004. }
  4005. bool failed() { return false; }
  4006. bool found(APValue &Subobj, QualType SubobjType) {
  4007. // Stash the old value. Also clear Old, so we don't clobber it later
  4008. // if we're post-incrementing a complex.
  4009. if (Old) {
  4010. *Old = Subobj;
  4011. Old = nullptr;
  4012. }
  4013. switch (Subobj.getKind()) {
  4014. case APValue::Int:
  4015. return found(Subobj.getInt(), SubobjType);
  4016. case APValue::Float:
  4017. return found(Subobj.getFloat(), SubobjType);
  4018. case APValue::ComplexInt:
  4019. return found(Subobj.getComplexIntReal(),
  4020. SubobjType->castAs<ComplexType>()->getElementType()
  4021. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  4022. case APValue::ComplexFloat:
  4023. return found(Subobj.getComplexFloatReal(),
  4024. SubobjType->castAs<ComplexType>()->getElementType()
  4025. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  4026. case APValue::LValue:
  4027. return foundPointer(Subobj, SubobjType);
  4028. default:
  4029. // FIXME: can this happen?
  4030. Info.FFDiag(E);
  4031. return false;
  4032. }
  4033. }
  4034. bool found(APSInt &Value, QualType SubobjType) {
  4035. if (!checkConst(SubobjType))
  4036. return false;
  4037. if (!SubobjType->isIntegerType()) {
  4038. // We don't support increment / decrement on integer-cast-to-pointer
  4039. // values.
  4040. Info.FFDiag(E);
  4041. return false;
  4042. }
  4043. if (Old) *Old = APValue(Value);
  4044. // bool arithmetic promotes to int, and the conversion back to bool
  4045. // doesn't reduce mod 2^n, so special-case it.
  4046. if (SubobjType->isBooleanType()) {
  4047. if (AccessKind == AK_Increment)
  4048. Value = 1;
  4049. else
  4050. Value = !Value;
  4051. return true;
  4052. }
  4053. bool WasNegative = Value.isNegative();
  4054. if (AccessKind == AK_Increment) {
  4055. ++Value;
  4056. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  4057. APSInt ActualValue(Value, /*IsUnsigned*/true);
  4058. return HandleOverflow(Info, E, ActualValue, SubobjType);
  4059. }
  4060. } else {
  4061. --Value;
  4062. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  4063. unsigned BitWidth = Value.getBitWidth();
  4064. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  4065. ActualValue.setBit(BitWidth);
  4066. return HandleOverflow(Info, E, ActualValue, SubobjType);
  4067. }
  4068. }
  4069. return true;
  4070. }
  4071. bool found(APFloat &Value, QualType SubobjType) {
  4072. if (!checkConst(SubobjType))
  4073. return false;
  4074. if (Old) *Old = APValue(Value);
  4075. APFloat One(Value.getSemantics(), 1);
  4076. if (AccessKind == AK_Increment)
  4077. Value.add(One, APFloat::rmNearestTiesToEven);
  4078. else
  4079. Value.subtract(One, APFloat::rmNearestTiesToEven);
  4080. return true;
  4081. }
  4082. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  4083. if (!checkConst(SubobjType))
  4084. return false;
  4085. QualType PointeeType;
  4086. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  4087. PointeeType = PT->getPointeeType();
  4088. else {
  4089. Info.FFDiag(E);
  4090. return false;
  4091. }
  4092. LValue LVal;
  4093. LVal.setFrom(Info.Ctx, Subobj);
  4094. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  4095. AccessKind == AK_Increment ? 1 : -1))
  4096. return false;
  4097. LVal.moveInto(Subobj);
  4098. return true;
  4099. }
  4100. };
  4101. } // end anonymous namespace
  4102. /// Perform an increment or decrement on LVal.
  4103. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  4104. QualType LValType, bool IsIncrement, APValue *Old) {
  4105. if (LVal.Designator.Invalid)
  4106. return false;
  4107. if (!Info.getLangOpts().CPlusPlus14) {
  4108. Info.FFDiag(E);
  4109. return false;
  4110. }
  4111. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  4112. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  4113. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  4114. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  4115. }
  4116. /// Build an lvalue for the object argument of a member function call.
  4117. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  4118. LValue &This) {
  4119. if (Object->getType()->isPointerType() && Object->isPRValue())
  4120. return EvaluatePointer(Object, This, Info);
  4121. if (Object->isGLValue())
  4122. return EvaluateLValue(Object, This, Info);
  4123. if (Object->getType()->isLiteralType(Info.Ctx))
  4124. return EvaluateTemporary(Object, This, Info);
  4125. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  4126. return false;
  4127. }
  4128. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  4129. /// lvalue referring to the result.
  4130. ///
  4131. /// \param Info - Information about the ongoing evaluation.
  4132. /// \param LV - An lvalue referring to the base of the member pointer.
  4133. /// \param RHS - The member pointer expression.
  4134. /// \param IncludeMember - Specifies whether the member itself is included in
  4135. /// the resulting LValue subobject designator. This is not possible when
  4136. /// creating a bound member function.
  4137. /// \return The field or method declaration to which the member pointer refers,
  4138. /// or 0 if evaluation fails.
  4139. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  4140. QualType LVType,
  4141. LValue &LV,
  4142. const Expr *RHS,
  4143. bool IncludeMember = true) {
  4144. MemberPtr MemPtr;
  4145. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  4146. return nullptr;
  4147. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  4148. // member value, the behavior is undefined.
  4149. if (!MemPtr.getDecl()) {
  4150. // FIXME: Specific diagnostic.
  4151. Info.FFDiag(RHS);
  4152. return nullptr;
  4153. }
  4154. if (MemPtr.isDerivedMember()) {
  4155. // This is a member of some derived class. Truncate LV appropriately.
  4156. // The end of the derived-to-base path for the base object must match the
  4157. // derived-to-base path for the member pointer.
  4158. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  4159. LV.Designator.Entries.size()) {
  4160. Info.FFDiag(RHS);
  4161. return nullptr;
  4162. }
  4163. unsigned PathLengthToMember =
  4164. LV.Designator.Entries.size() - MemPtr.Path.size();
  4165. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  4166. const CXXRecordDecl *LVDecl = getAsBaseClass(
  4167. LV.Designator.Entries[PathLengthToMember + I]);
  4168. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  4169. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  4170. Info.FFDiag(RHS);
  4171. return nullptr;
  4172. }
  4173. }
  4174. // Truncate the lvalue to the appropriate derived class.
  4175. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  4176. PathLengthToMember))
  4177. return nullptr;
  4178. } else if (!MemPtr.Path.empty()) {
  4179. // Extend the LValue path with the member pointer's path.
  4180. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  4181. MemPtr.Path.size() + IncludeMember);
  4182. // Walk down to the appropriate base class.
  4183. if (const PointerType *PT = LVType->getAs<PointerType>())
  4184. LVType = PT->getPointeeType();
  4185. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  4186. assert(RD && "member pointer access on non-class-type expression");
  4187. // The first class in the path is that of the lvalue.
  4188. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  4189. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  4190. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  4191. return nullptr;
  4192. RD = Base;
  4193. }
  4194. // Finally cast to the class containing the member.
  4195. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  4196. MemPtr.getContainingRecord()))
  4197. return nullptr;
  4198. }
  4199. // Add the member. Note that we cannot build bound member functions here.
  4200. if (IncludeMember) {
  4201. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  4202. if (!HandleLValueMember(Info, RHS, LV, FD))
  4203. return nullptr;
  4204. } else if (const IndirectFieldDecl *IFD =
  4205. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  4206. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  4207. return nullptr;
  4208. } else {
  4209. llvm_unreachable("can't construct reference to bound member function");
  4210. }
  4211. }
  4212. return MemPtr.getDecl();
  4213. }
  4214. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  4215. const BinaryOperator *BO,
  4216. LValue &LV,
  4217. bool IncludeMember = true) {
  4218. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  4219. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  4220. if (Info.noteFailure()) {
  4221. MemberPtr MemPtr;
  4222. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  4223. }
  4224. return nullptr;
  4225. }
  4226. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  4227. BO->getRHS(), IncludeMember);
  4228. }
  4229. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  4230. /// the provided lvalue, which currently refers to the base object.
  4231. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  4232. LValue &Result) {
  4233. SubobjectDesignator &D = Result.Designator;
  4234. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  4235. return false;
  4236. QualType TargetQT = E->getType();
  4237. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  4238. TargetQT = PT->getPointeeType();
  4239. // Check this cast lands within the final derived-to-base subobject path.
  4240. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  4241. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  4242. << D.MostDerivedType << TargetQT;
  4243. return false;
  4244. }
  4245. // Check the type of the final cast. We don't need to check the path,
  4246. // since a cast can only be formed if the path is unique.
  4247. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  4248. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  4249. const CXXRecordDecl *FinalType;
  4250. if (NewEntriesSize == D.MostDerivedPathLength)
  4251. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  4252. else
  4253. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  4254. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  4255. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  4256. << D.MostDerivedType << TargetQT;
  4257. return false;
  4258. }
  4259. // Truncate the lvalue to the appropriate derived class.
  4260. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  4261. }
  4262. /// Get the value to use for a default-initialized object of type T.
  4263. /// Return false if it encounters something invalid.
  4264. static bool getDefaultInitValue(QualType T, APValue &Result) {
  4265. bool Success = true;
  4266. if (auto *RD = T->getAsCXXRecordDecl()) {
  4267. if (RD->isInvalidDecl()) {
  4268. Result = APValue();
  4269. return false;
  4270. }
  4271. if (RD->isUnion()) {
  4272. Result = APValue((const FieldDecl *)nullptr);
  4273. return true;
  4274. }
  4275. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4276. std::distance(RD->field_begin(), RD->field_end()));
  4277. unsigned Index = 0;
  4278. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  4279. End = RD->bases_end();
  4280. I != End; ++I, ++Index)
  4281. Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
  4282. for (const auto *I : RD->fields()) {
  4283. if (I->isUnnamedBitfield())
  4284. continue;
  4285. Success &= getDefaultInitValue(I->getType(),
  4286. Result.getStructField(I->getFieldIndex()));
  4287. }
  4288. return Success;
  4289. }
  4290. if (auto *AT =
  4291. dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
  4292. Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  4293. if (Result.hasArrayFiller())
  4294. Success &=
  4295. getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
  4296. return Success;
  4297. }
  4298. Result = APValue::IndeterminateValue();
  4299. return true;
  4300. }
  4301. namespace {
  4302. enum EvalStmtResult {
  4303. /// Evaluation failed.
  4304. ESR_Failed,
  4305. /// Hit a 'return' statement.
  4306. ESR_Returned,
  4307. /// Evaluation succeeded.
  4308. ESR_Succeeded,
  4309. /// Hit a 'continue' statement.
  4310. ESR_Continue,
  4311. /// Hit a 'break' statement.
  4312. ESR_Break,
  4313. /// Still scanning for 'case' or 'default' statement.
  4314. ESR_CaseNotFound
  4315. };
  4316. }
  4317. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  4318. if (VD->isInvalidDecl())
  4319. return false;
  4320. // We don't need to evaluate the initializer for a static local.
  4321. if (!VD->hasLocalStorage())
  4322. return true;
  4323. LValue Result;
  4324. APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
  4325. ScopeKind::Block, Result);
  4326. const Expr *InitE = VD->getInit();
  4327. if (!InitE) {
  4328. if (VD->getType()->isDependentType())
  4329. return Info.noteSideEffect();
  4330. return getDefaultInitValue(VD->getType(), Val);
  4331. }
  4332. if (InitE->isValueDependent())
  4333. return false;
  4334. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  4335. // Wipe out any partially-computed value, to allow tracking that this
  4336. // evaluation failed.
  4337. Val = APValue();
  4338. return false;
  4339. }
  4340. return true;
  4341. }
  4342. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  4343. bool OK = true;
  4344. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  4345. OK &= EvaluateVarDecl(Info, VD);
  4346. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  4347. for (auto *BD : DD->bindings())
  4348. if (auto *VD = BD->getHoldingVar())
  4349. OK &= EvaluateDecl(Info, VD);
  4350. return OK;
  4351. }
  4352. static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
  4353. assert(E->isValueDependent());
  4354. if (Info.noteSideEffect())
  4355. return true;
  4356. assert(E->containsErrors() && "valid value-dependent expression should never "
  4357. "reach invalid code path.");
  4358. return false;
  4359. }
  4360. /// Evaluate a condition (either a variable declaration or an expression).
  4361. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  4362. const Expr *Cond, bool &Result) {
  4363. if (Cond->isValueDependent())
  4364. return false;
  4365. FullExpressionRAII Scope(Info);
  4366. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  4367. return false;
  4368. if (!EvaluateAsBooleanCondition(Cond, Result, Info))
  4369. return false;
  4370. return Scope.destroy();
  4371. }
  4372. namespace {
  4373. /// A location where the result (returned value) of evaluating a
  4374. /// statement should be stored.
  4375. struct StmtResult {
  4376. /// The APValue that should be filled in with the returned value.
  4377. APValue &Value;
  4378. /// The location containing the result, if any (used to support RVO).
  4379. const LValue *Slot;
  4380. };
  4381. struct TempVersionRAII {
  4382. CallStackFrame &Frame;
  4383. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  4384. Frame.pushTempVersion();
  4385. }
  4386. ~TempVersionRAII() {
  4387. Frame.popTempVersion();
  4388. }
  4389. };
  4390. }
  4391. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  4392. const Stmt *S,
  4393. const SwitchCase *SC = nullptr);
  4394. /// Evaluate the body of a loop, and translate the result as appropriate.
  4395. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  4396. const Stmt *Body,
  4397. const SwitchCase *Case = nullptr) {
  4398. BlockScopeRAII Scope(Info);
  4399. EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
  4400. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  4401. ESR = ESR_Failed;
  4402. switch (ESR) {
  4403. case ESR_Break:
  4404. return ESR_Succeeded;
  4405. case ESR_Succeeded:
  4406. case ESR_Continue:
  4407. return ESR_Continue;
  4408. case ESR_Failed:
  4409. case ESR_Returned:
  4410. case ESR_CaseNotFound:
  4411. return ESR;
  4412. }
  4413. llvm_unreachable("Invalid EvalStmtResult!");
  4414. }
  4415. /// Evaluate a switch statement.
  4416. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  4417. const SwitchStmt *SS) {
  4418. BlockScopeRAII Scope(Info);
  4419. // Evaluate the switch condition.
  4420. APSInt Value;
  4421. {
  4422. if (const Stmt *Init = SS->getInit()) {
  4423. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  4424. if (ESR != ESR_Succeeded) {
  4425. if (ESR != ESR_Failed && !Scope.destroy())
  4426. ESR = ESR_Failed;
  4427. return ESR;
  4428. }
  4429. }
  4430. FullExpressionRAII CondScope(Info);
  4431. if (SS->getConditionVariable() &&
  4432. !EvaluateDecl(Info, SS->getConditionVariable()))
  4433. return ESR_Failed;
  4434. if (SS->getCond()->isValueDependent()) {
  4435. if (!EvaluateDependentExpr(SS->getCond(), Info))
  4436. return ESR_Failed;
  4437. } else {
  4438. if (!EvaluateInteger(SS->getCond(), Value, Info))
  4439. return ESR_Failed;
  4440. }
  4441. if (!CondScope.destroy())
  4442. return ESR_Failed;
  4443. }
  4444. // Find the switch case corresponding to the value of the condition.
  4445. // FIXME: Cache this lookup.
  4446. const SwitchCase *Found = nullptr;
  4447. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  4448. SC = SC->getNextSwitchCase()) {
  4449. if (isa<DefaultStmt>(SC)) {
  4450. Found = SC;
  4451. continue;
  4452. }
  4453. const CaseStmt *CS = cast<CaseStmt>(SC);
  4454. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  4455. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  4456. : LHS;
  4457. if (LHS <= Value && Value <= RHS) {
  4458. Found = SC;
  4459. break;
  4460. }
  4461. }
  4462. if (!Found)
  4463. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4464. // Search the switch body for the switch case and evaluate it from there.
  4465. EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
  4466. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  4467. return ESR_Failed;
  4468. switch (ESR) {
  4469. case ESR_Break:
  4470. return ESR_Succeeded;
  4471. case ESR_Succeeded:
  4472. case ESR_Continue:
  4473. case ESR_Failed:
  4474. case ESR_Returned:
  4475. return ESR;
  4476. case ESR_CaseNotFound:
  4477. // This can only happen if the switch case is nested within a statement
  4478. // expression. We have no intention of supporting that.
  4479. Info.FFDiag(Found->getBeginLoc(),
  4480. diag::note_constexpr_stmt_expr_unsupported);
  4481. return ESR_Failed;
  4482. }
  4483. llvm_unreachable("Invalid EvalStmtResult!");
  4484. }
  4485. static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
  4486. // An expression E is a core constant expression unless the evaluation of E
  4487. // would evaluate one of the following: [C++2b] - a control flow that passes
  4488. // through a declaration of a variable with static or thread storage duration
  4489. // unless that variable is usable in constant expressions.
  4490. if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
  4491. !VD->isUsableInConstantExpressions(Info.Ctx)) {
  4492. Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
  4493. << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
  4494. return false;
  4495. }
  4496. return true;
  4497. }
  4498. // Evaluate a statement.
  4499. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  4500. const Stmt *S, const SwitchCase *Case) {
  4501. if (!Info.nextStep(S))
  4502. return ESR_Failed;
  4503. // If we're hunting down a 'case' or 'default' label, recurse through
  4504. // substatements until we hit the label.
  4505. if (Case) {
  4506. switch (S->getStmtClass()) {
  4507. case Stmt::CompoundStmtClass:
  4508. // FIXME: Precompute which substatement of a compound statement we
  4509. // would jump to, and go straight there rather than performing a
  4510. // linear scan each time.
  4511. case Stmt::LabelStmtClass:
  4512. case Stmt::AttributedStmtClass:
  4513. case Stmt::DoStmtClass:
  4514. break;
  4515. case Stmt::CaseStmtClass:
  4516. case Stmt::DefaultStmtClass:
  4517. if (Case == S)
  4518. Case = nullptr;
  4519. break;
  4520. case Stmt::IfStmtClass: {
  4521. // FIXME: Precompute which side of an 'if' we would jump to, and go
  4522. // straight there rather than scanning both sides.
  4523. const IfStmt *IS = cast<IfStmt>(S);
  4524. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  4525. // preceded by our switch label.
  4526. BlockScopeRAII Scope(Info);
  4527. // Step into the init statement in case it brings an (uninitialized)
  4528. // variable into scope.
  4529. if (const Stmt *Init = IS->getInit()) {
  4530. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  4531. if (ESR != ESR_CaseNotFound) {
  4532. assert(ESR != ESR_Succeeded);
  4533. return ESR;
  4534. }
  4535. }
  4536. // Condition variable must be initialized if it exists.
  4537. // FIXME: We can skip evaluating the body if there's a condition
  4538. // variable, as there can't be any case labels within it.
  4539. // (The same is true for 'for' statements.)
  4540. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  4541. if (ESR == ESR_Failed)
  4542. return ESR;
  4543. if (ESR != ESR_CaseNotFound)
  4544. return Scope.destroy() ? ESR : ESR_Failed;
  4545. if (!IS->getElse())
  4546. return ESR_CaseNotFound;
  4547. ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
  4548. if (ESR == ESR_Failed)
  4549. return ESR;
  4550. if (ESR != ESR_CaseNotFound)
  4551. return Scope.destroy() ? ESR : ESR_Failed;
  4552. return ESR_CaseNotFound;
  4553. }
  4554. case Stmt::WhileStmtClass: {
  4555. EvalStmtResult ESR =
  4556. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  4557. if (ESR != ESR_Continue)
  4558. return ESR;
  4559. break;
  4560. }
  4561. case Stmt::ForStmtClass: {
  4562. const ForStmt *FS = cast<ForStmt>(S);
  4563. BlockScopeRAII Scope(Info);
  4564. // Step into the init statement in case it brings an (uninitialized)
  4565. // variable into scope.
  4566. if (const Stmt *Init = FS->getInit()) {
  4567. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  4568. if (ESR != ESR_CaseNotFound) {
  4569. assert(ESR != ESR_Succeeded);
  4570. return ESR;
  4571. }
  4572. }
  4573. EvalStmtResult ESR =
  4574. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  4575. if (ESR != ESR_Continue)
  4576. return ESR;
  4577. if (const auto *Inc = FS->getInc()) {
  4578. if (Inc->isValueDependent()) {
  4579. if (!EvaluateDependentExpr(Inc, Info))
  4580. return ESR_Failed;
  4581. } else {
  4582. FullExpressionRAII IncScope(Info);
  4583. if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
  4584. return ESR_Failed;
  4585. }
  4586. }
  4587. break;
  4588. }
  4589. case Stmt::DeclStmtClass: {
  4590. // Start the lifetime of any uninitialized variables we encounter. They
  4591. // might be used by the selected branch of the switch.
  4592. const DeclStmt *DS = cast<DeclStmt>(S);
  4593. for (const auto *D : DS->decls()) {
  4594. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  4595. if (!CheckLocalVariableDeclaration(Info, VD))
  4596. return ESR_Failed;
  4597. if (VD->hasLocalStorage() && !VD->getInit())
  4598. if (!EvaluateVarDecl(Info, VD))
  4599. return ESR_Failed;
  4600. // FIXME: If the variable has initialization that can't be jumped
  4601. // over, bail out of any immediately-surrounding compound-statement
  4602. // too. There can't be any case labels here.
  4603. }
  4604. }
  4605. return ESR_CaseNotFound;
  4606. }
  4607. default:
  4608. return ESR_CaseNotFound;
  4609. }
  4610. }
  4611. switch (S->getStmtClass()) {
  4612. default:
  4613. if (const Expr *E = dyn_cast<Expr>(S)) {
  4614. if (E->isValueDependent()) {
  4615. if (!EvaluateDependentExpr(E, Info))
  4616. return ESR_Failed;
  4617. } else {
  4618. // Don't bother evaluating beyond an expression-statement which couldn't
  4619. // be evaluated.
  4620. // FIXME: Do we need the FullExpressionRAII object here?
  4621. // VisitExprWithCleanups should create one when necessary.
  4622. FullExpressionRAII Scope(Info);
  4623. if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
  4624. return ESR_Failed;
  4625. }
  4626. return ESR_Succeeded;
  4627. }
  4628. Info.FFDiag(S->getBeginLoc());
  4629. return ESR_Failed;
  4630. case Stmt::NullStmtClass:
  4631. return ESR_Succeeded;
  4632. case Stmt::DeclStmtClass: {
  4633. const DeclStmt *DS = cast<DeclStmt>(S);
  4634. for (const auto *D : DS->decls()) {
  4635. const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
  4636. if (VD && !CheckLocalVariableDeclaration(Info, VD))
  4637. return ESR_Failed;
  4638. // Each declaration initialization is its own full-expression.
  4639. FullExpressionRAII Scope(Info);
  4640. if (!EvaluateDecl(Info, D) && !Info.noteFailure())
  4641. return ESR_Failed;
  4642. if (!Scope.destroy())
  4643. return ESR_Failed;
  4644. }
  4645. return ESR_Succeeded;
  4646. }
  4647. case Stmt::ReturnStmtClass: {
  4648. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  4649. FullExpressionRAII Scope(Info);
  4650. if (RetExpr && RetExpr->isValueDependent()) {
  4651. EvaluateDependentExpr(RetExpr, Info);
  4652. // We know we returned, but we don't know what the value is.
  4653. return ESR_Failed;
  4654. }
  4655. if (RetExpr &&
  4656. !(Result.Slot
  4657. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  4658. : Evaluate(Result.Value, Info, RetExpr)))
  4659. return ESR_Failed;
  4660. return Scope.destroy() ? ESR_Returned : ESR_Failed;
  4661. }
  4662. case Stmt::CompoundStmtClass: {
  4663. BlockScopeRAII Scope(Info);
  4664. const CompoundStmt *CS = cast<CompoundStmt>(S);
  4665. for (const auto *BI : CS->body()) {
  4666. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  4667. if (ESR == ESR_Succeeded)
  4668. Case = nullptr;
  4669. else if (ESR != ESR_CaseNotFound) {
  4670. if (ESR != ESR_Failed && !Scope.destroy())
  4671. return ESR_Failed;
  4672. return ESR;
  4673. }
  4674. }
  4675. if (Case)
  4676. return ESR_CaseNotFound;
  4677. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4678. }
  4679. case Stmt::IfStmtClass: {
  4680. const IfStmt *IS = cast<IfStmt>(S);
  4681. // Evaluate the condition, as either a var decl or as an expression.
  4682. BlockScopeRAII Scope(Info);
  4683. if (const Stmt *Init = IS->getInit()) {
  4684. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  4685. if (ESR != ESR_Succeeded) {
  4686. if (ESR != ESR_Failed && !Scope.destroy())
  4687. return ESR_Failed;
  4688. return ESR;
  4689. }
  4690. }
  4691. bool Cond;
  4692. if (IS->isConsteval()) {
  4693. Cond = IS->isNonNegatedConsteval();
  4694. // If we are not in a constant context, if consteval should not evaluate
  4695. // to true.
  4696. if (!Info.InConstantContext)
  4697. Cond = !Cond;
  4698. } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
  4699. Cond))
  4700. return ESR_Failed;
  4701. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  4702. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  4703. if (ESR != ESR_Succeeded) {
  4704. if (ESR != ESR_Failed && !Scope.destroy())
  4705. return ESR_Failed;
  4706. return ESR;
  4707. }
  4708. }
  4709. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4710. }
  4711. case Stmt::WhileStmtClass: {
  4712. const WhileStmt *WS = cast<WhileStmt>(S);
  4713. while (true) {
  4714. BlockScopeRAII Scope(Info);
  4715. bool Continue;
  4716. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  4717. Continue))
  4718. return ESR_Failed;
  4719. if (!Continue)
  4720. break;
  4721. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  4722. if (ESR != ESR_Continue) {
  4723. if (ESR != ESR_Failed && !Scope.destroy())
  4724. return ESR_Failed;
  4725. return ESR;
  4726. }
  4727. if (!Scope.destroy())
  4728. return ESR_Failed;
  4729. }
  4730. return ESR_Succeeded;
  4731. }
  4732. case Stmt::DoStmtClass: {
  4733. const DoStmt *DS = cast<DoStmt>(S);
  4734. bool Continue;
  4735. do {
  4736. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  4737. if (ESR != ESR_Continue)
  4738. return ESR;
  4739. Case = nullptr;
  4740. if (DS->getCond()->isValueDependent()) {
  4741. EvaluateDependentExpr(DS->getCond(), Info);
  4742. // Bailout as we don't know whether to keep going or terminate the loop.
  4743. return ESR_Failed;
  4744. }
  4745. FullExpressionRAII CondScope(Info);
  4746. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
  4747. !CondScope.destroy())
  4748. return ESR_Failed;
  4749. } while (Continue);
  4750. return ESR_Succeeded;
  4751. }
  4752. case Stmt::ForStmtClass: {
  4753. const ForStmt *FS = cast<ForStmt>(S);
  4754. BlockScopeRAII ForScope(Info);
  4755. if (FS->getInit()) {
  4756. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4757. if (ESR != ESR_Succeeded) {
  4758. if (ESR != ESR_Failed && !ForScope.destroy())
  4759. return ESR_Failed;
  4760. return ESR;
  4761. }
  4762. }
  4763. while (true) {
  4764. BlockScopeRAII IterScope(Info);
  4765. bool Continue = true;
  4766. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  4767. FS->getCond(), Continue))
  4768. return ESR_Failed;
  4769. if (!Continue)
  4770. break;
  4771. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4772. if (ESR != ESR_Continue) {
  4773. if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
  4774. return ESR_Failed;
  4775. return ESR;
  4776. }
  4777. if (const auto *Inc = FS->getInc()) {
  4778. if (Inc->isValueDependent()) {
  4779. if (!EvaluateDependentExpr(Inc, Info))
  4780. return ESR_Failed;
  4781. } else {
  4782. FullExpressionRAII IncScope(Info);
  4783. if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
  4784. return ESR_Failed;
  4785. }
  4786. }
  4787. if (!IterScope.destroy())
  4788. return ESR_Failed;
  4789. }
  4790. return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
  4791. }
  4792. case Stmt::CXXForRangeStmtClass: {
  4793. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  4794. BlockScopeRAII Scope(Info);
  4795. // Evaluate the init-statement if present.
  4796. if (FS->getInit()) {
  4797. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4798. if (ESR != ESR_Succeeded) {
  4799. if (ESR != ESR_Failed && !Scope.destroy())
  4800. return ESR_Failed;
  4801. return ESR;
  4802. }
  4803. }
  4804. // Initialize the __range variable.
  4805. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  4806. if (ESR != ESR_Succeeded) {
  4807. if (ESR != ESR_Failed && !Scope.destroy())
  4808. return ESR_Failed;
  4809. return ESR;
  4810. }
  4811. // In error-recovery cases it's possible to get here even if we failed to
  4812. // synthesize the __begin and __end variables.
  4813. if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
  4814. return ESR_Failed;
  4815. // Create the __begin and __end iterators.
  4816. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  4817. if (ESR != ESR_Succeeded) {
  4818. if (ESR != ESR_Failed && !Scope.destroy())
  4819. return ESR_Failed;
  4820. return ESR;
  4821. }
  4822. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  4823. if (ESR != ESR_Succeeded) {
  4824. if (ESR != ESR_Failed && !Scope.destroy())
  4825. return ESR_Failed;
  4826. return ESR;
  4827. }
  4828. while (true) {
  4829. // Condition: __begin != __end.
  4830. {
  4831. if (FS->getCond()->isValueDependent()) {
  4832. EvaluateDependentExpr(FS->getCond(), Info);
  4833. // We don't know whether to keep going or terminate the loop.
  4834. return ESR_Failed;
  4835. }
  4836. bool Continue = true;
  4837. FullExpressionRAII CondExpr(Info);
  4838. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  4839. return ESR_Failed;
  4840. if (!Continue)
  4841. break;
  4842. }
  4843. // User's variable declaration, initialized by *__begin.
  4844. BlockScopeRAII InnerScope(Info);
  4845. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  4846. if (ESR != ESR_Succeeded) {
  4847. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4848. return ESR_Failed;
  4849. return ESR;
  4850. }
  4851. // Loop body.
  4852. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4853. if (ESR != ESR_Continue) {
  4854. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4855. return ESR_Failed;
  4856. return ESR;
  4857. }
  4858. if (FS->getInc()->isValueDependent()) {
  4859. if (!EvaluateDependentExpr(FS->getInc(), Info))
  4860. return ESR_Failed;
  4861. } else {
  4862. // Increment: ++__begin
  4863. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  4864. return ESR_Failed;
  4865. }
  4866. if (!InnerScope.destroy())
  4867. return ESR_Failed;
  4868. }
  4869. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4870. }
  4871. case Stmt::SwitchStmtClass:
  4872. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  4873. case Stmt::ContinueStmtClass:
  4874. return ESR_Continue;
  4875. case Stmt::BreakStmtClass:
  4876. return ESR_Break;
  4877. case Stmt::LabelStmtClass:
  4878. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  4879. case Stmt::AttributedStmtClass:
  4880. // As a general principle, C++11 attributes can be ignored without
  4881. // any semantic impact.
  4882. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  4883. Case);
  4884. case Stmt::CaseStmtClass:
  4885. case Stmt::DefaultStmtClass:
  4886. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  4887. case Stmt::CXXTryStmtClass:
  4888. // Evaluate try blocks by evaluating all sub statements.
  4889. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  4890. }
  4891. }
  4892. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  4893. /// default constructor. If so, we'll fold it whether or not it's marked as
  4894. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  4895. /// so we need special handling.
  4896. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  4897. const CXXConstructorDecl *CD,
  4898. bool IsValueInitialization) {
  4899. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  4900. return false;
  4901. // Value-initialization does not call a trivial default constructor, so such a
  4902. // call is a core constant expression whether or not the constructor is
  4903. // constexpr.
  4904. if (!CD->isConstexpr() && !IsValueInitialization) {
  4905. if (Info.getLangOpts().CPlusPlus11) {
  4906. // FIXME: If DiagDecl is an implicitly-declared special member function,
  4907. // we should be much more explicit about why it's not constexpr.
  4908. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  4909. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  4910. Info.Note(CD->getLocation(), diag::note_declared_at);
  4911. } else {
  4912. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  4913. }
  4914. }
  4915. return true;
  4916. }
  4917. /// CheckConstexprFunction - Check that a function can be called in a constant
  4918. /// expression.
  4919. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  4920. const FunctionDecl *Declaration,
  4921. const FunctionDecl *Definition,
  4922. const Stmt *Body) {
  4923. // Potential constant expressions can contain calls to declared, but not yet
  4924. // defined, constexpr functions.
  4925. if (Info.checkingPotentialConstantExpression() && !Definition &&
  4926. Declaration->isConstexpr())
  4927. return false;
  4928. // Bail out if the function declaration itself is invalid. We will
  4929. // have produced a relevant diagnostic while parsing it, so just
  4930. // note the problematic sub-expression.
  4931. if (Declaration->isInvalidDecl()) {
  4932. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4933. return false;
  4934. }
  4935. // DR1872: An instantiated virtual constexpr function can't be called in a
  4936. // constant expression (prior to C++20). We can still constant-fold such a
  4937. // call.
  4938. if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
  4939. cast<CXXMethodDecl>(Declaration)->isVirtual())
  4940. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  4941. if (Definition && Definition->isInvalidDecl()) {
  4942. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4943. return false;
  4944. }
  4945. // Can we evaluate this function call?
  4946. if (Definition && Definition->isConstexpr() && Body)
  4947. return true;
  4948. if (Info.getLangOpts().CPlusPlus11) {
  4949. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4950. // If this function is not constexpr because it is an inherited
  4951. // non-constexpr constructor, diagnose that directly.
  4952. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4953. if (CD && CD->isInheritingConstructor()) {
  4954. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4955. if (!Inherited->isConstexpr())
  4956. DiagDecl = CD = Inherited;
  4957. }
  4958. // FIXME: If DiagDecl is an implicitly-declared special member function
  4959. // or an inheriting constructor, we should be much more explicit about why
  4960. // it's not constexpr.
  4961. if (CD && CD->isInheritingConstructor())
  4962. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4963. << CD->getInheritedConstructor().getConstructor()->getParent();
  4964. else
  4965. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4966. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4967. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4968. } else {
  4969. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4970. }
  4971. return false;
  4972. }
  4973. namespace {
  4974. struct CheckDynamicTypeHandler {
  4975. AccessKinds AccessKind;
  4976. typedef bool result_type;
  4977. bool failed() { return false; }
  4978. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4979. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4980. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4981. };
  4982. } // end anonymous namespace
  4983. /// Check that we can access the notional vptr of an object / determine its
  4984. /// dynamic type.
  4985. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4986. AccessKinds AK, bool Polymorphic) {
  4987. if (This.Designator.Invalid)
  4988. return false;
  4989. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4990. if (!Obj)
  4991. return false;
  4992. if (!Obj.Value) {
  4993. // The object is not usable in constant expressions, so we can't inspect
  4994. // its value to see if it's in-lifetime or what the active union members
  4995. // are. We can still check for a one-past-the-end lvalue.
  4996. if (This.Designator.isOnePastTheEnd() ||
  4997. This.Designator.isMostDerivedAnUnsizedArray()) {
  4998. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4999. ? diag::note_constexpr_access_past_end
  5000. : diag::note_constexpr_access_unsized_array)
  5001. << AK;
  5002. return false;
  5003. } else if (Polymorphic) {
  5004. // Conservatively refuse to perform a polymorphic operation if we would
  5005. // not be able to read a notional 'vptr' value.
  5006. APValue Val;
  5007. This.moveInto(Val);
  5008. QualType StarThisType =
  5009. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  5010. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  5011. << AK << Val.getAsString(Info.Ctx, StarThisType);
  5012. return false;
  5013. }
  5014. return true;
  5015. }
  5016. CheckDynamicTypeHandler Handler{AK};
  5017. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  5018. }
  5019. /// Check that the pointee of the 'this' pointer in a member function call is
  5020. /// either within its lifetime or in its period of construction or destruction.
  5021. static bool
  5022. checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  5023. const LValue &This,
  5024. const CXXMethodDecl *NamedMember) {
  5025. return checkDynamicType(
  5026. Info, E, This,
  5027. isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
  5028. }
  5029. struct DynamicType {
  5030. /// The dynamic class type of the object.
  5031. const CXXRecordDecl *Type;
  5032. /// The corresponding path length in the lvalue.
  5033. unsigned PathLength;
  5034. };
  5035. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  5036. unsigned PathLength) {
  5037. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  5038. Designator.Entries.size() && "invalid path length");
  5039. return (PathLength == Designator.MostDerivedPathLength)
  5040. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  5041. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  5042. }
  5043. /// Determine the dynamic type of an object.
  5044. static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
  5045. const Expr *E,
  5046. LValue &This,
  5047. AccessKinds AK) {
  5048. // If we don't have an lvalue denoting an object of class type, there is no
  5049. // meaningful dynamic type. (We consider objects of non-class type to have no
  5050. // dynamic type.)
  5051. if (!checkDynamicType(Info, E, This, AK, true))
  5052. return std::nullopt;
  5053. // Refuse to compute a dynamic type in the presence of virtual bases. This
  5054. // shouldn't happen other than in constant-folding situations, since literal
  5055. // types can't have virtual bases.
  5056. //
  5057. // Note that consumers of DynamicType assume that the type has no virtual
  5058. // bases, and will need modifications if this restriction is relaxed.
  5059. const CXXRecordDecl *Class =
  5060. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  5061. if (!Class || Class->getNumVBases()) {
  5062. Info.FFDiag(E);
  5063. return std::nullopt;
  5064. }
  5065. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  5066. // binary search here instead. But the overwhelmingly common case is that
  5067. // we're not in the middle of a constructor, so it probably doesn't matter
  5068. // in practice.
  5069. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  5070. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  5071. PathLength <= Path.size(); ++PathLength) {
  5072. switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
  5073. Path.slice(0, PathLength))) {
  5074. case ConstructionPhase::Bases:
  5075. case ConstructionPhase::DestroyingBases:
  5076. // We're constructing or destroying a base class. This is not the dynamic
  5077. // type.
  5078. break;
  5079. case ConstructionPhase::None:
  5080. case ConstructionPhase::AfterBases:
  5081. case ConstructionPhase::AfterFields:
  5082. case ConstructionPhase::Destroying:
  5083. // We've finished constructing the base classes and not yet started
  5084. // destroying them again, so this is the dynamic type.
  5085. return DynamicType{getBaseClassType(This.Designator, PathLength),
  5086. PathLength};
  5087. }
  5088. }
  5089. // CWG issue 1517: we're constructing a base class of the object described by
  5090. // 'This', so that object has not yet begun its period of construction and
  5091. // any polymorphic operation on it results in undefined behavior.
  5092. Info.FFDiag(E);
  5093. return std::nullopt;
  5094. }
  5095. /// Perform virtual dispatch.
  5096. static const CXXMethodDecl *HandleVirtualDispatch(
  5097. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  5098. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  5099. std::optional<DynamicType> DynType = ComputeDynamicType(
  5100. Info, E, This,
  5101. isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
  5102. if (!DynType)
  5103. return nullptr;
  5104. // Find the final overrider. It must be declared in one of the classes on the
  5105. // path from the dynamic type to the static type.
  5106. // FIXME: If we ever allow literal types to have virtual base classes, that
  5107. // won't be true.
  5108. const CXXMethodDecl *Callee = Found;
  5109. unsigned PathLength = DynType->PathLength;
  5110. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  5111. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  5112. const CXXMethodDecl *Overrider =
  5113. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  5114. if (Overrider) {
  5115. Callee = Overrider;
  5116. break;
  5117. }
  5118. }
  5119. // C++2a [class.abstract]p6:
  5120. // the effect of making a virtual call to a pure virtual function [...] is
  5121. // undefined
  5122. if (Callee->isPure()) {
  5123. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  5124. Info.Note(Callee->getLocation(), diag::note_declared_at);
  5125. return nullptr;
  5126. }
  5127. // If necessary, walk the rest of the path to determine the sequence of
  5128. // covariant adjustment steps to apply.
  5129. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  5130. Found->getReturnType())) {
  5131. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  5132. for (unsigned CovariantPathLength = PathLength + 1;
  5133. CovariantPathLength != This.Designator.Entries.size();
  5134. ++CovariantPathLength) {
  5135. const CXXRecordDecl *NextClass =
  5136. getBaseClassType(This.Designator, CovariantPathLength);
  5137. const CXXMethodDecl *Next =
  5138. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  5139. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  5140. Next->getReturnType(), CovariantAdjustmentPath.back()))
  5141. CovariantAdjustmentPath.push_back(Next->getReturnType());
  5142. }
  5143. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  5144. CovariantAdjustmentPath.back()))
  5145. CovariantAdjustmentPath.push_back(Found->getReturnType());
  5146. }
  5147. // Perform 'this' adjustment.
  5148. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  5149. return nullptr;
  5150. return Callee;
  5151. }
  5152. /// Perform the adjustment from a value returned by a virtual function to
  5153. /// a value of the statically expected type, which may be a pointer or
  5154. /// reference to a base class of the returned type.
  5155. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  5156. APValue &Result,
  5157. ArrayRef<QualType> Path) {
  5158. assert(Result.isLValue() &&
  5159. "unexpected kind of APValue for covariant return");
  5160. if (Result.isNullPointer())
  5161. return true;
  5162. LValue LVal;
  5163. LVal.setFrom(Info.Ctx, Result);
  5164. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  5165. for (unsigned I = 1; I != Path.size(); ++I) {
  5166. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  5167. assert(OldClass && NewClass && "unexpected kind of covariant return");
  5168. if (OldClass != NewClass &&
  5169. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  5170. return false;
  5171. OldClass = NewClass;
  5172. }
  5173. LVal.moveInto(Result);
  5174. return true;
  5175. }
  5176. /// Determine whether \p Base, which is known to be a direct base class of
  5177. /// \p Derived, is a public base class.
  5178. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  5179. const CXXRecordDecl *Base) {
  5180. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  5181. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  5182. if (BaseClass && declaresSameEntity(BaseClass, Base))
  5183. return BaseSpec.getAccessSpecifier() == AS_public;
  5184. }
  5185. llvm_unreachable("Base is not a direct base of Derived");
  5186. }
  5187. /// Apply the given dynamic cast operation on the provided lvalue.
  5188. ///
  5189. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  5190. /// to find a suitable target subobject.
  5191. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  5192. LValue &Ptr) {
  5193. // We can't do anything with a non-symbolic pointer value.
  5194. SubobjectDesignator &D = Ptr.Designator;
  5195. if (D.Invalid)
  5196. return false;
  5197. // C++ [expr.dynamic.cast]p6:
  5198. // If v is a null pointer value, the result is a null pointer value.
  5199. if (Ptr.isNullPointer() && !E->isGLValue())
  5200. return true;
  5201. // For all the other cases, we need the pointer to point to an object within
  5202. // its lifetime / period of construction / destruction, and we need to know
  5203. // its dynamic type.
  5204. std::optional<DynamicType> DynType =
  5205. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  5206. if (!DynType)
  5207. return false;
  5208. // C++ [expr.dynamic.cast]p7:
  5209. // If T is "pointer to cv void", then the result is a pointer to the most
  5210. // derived object
  5211. if (E->getType()->isVoidPointerType())
  5212. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  5213. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  5214. assert(C && "dynamic_cast target is not void pointer nor class");
  5215. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  5216. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  5217. // C++ [expr.dynamic.cast]p9:
  5218. if (!E->isGLValue()) {
  5219. // The value of a failed cast to pointer type is the null pointer value
  5220. // of the required result type.
  5221. Ptr.setNull(Info.Ctx, E->getType());
  5222. return true;
  5223. }
  5224. // A failed cast to reference type throws [...] std::bad_cast.
  5225. unsigned DiagKind;
  5226. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  5227. DynType->Type->isDerivedFrom(C)))
  5228. DiagKind = 0;
  5229. else if (!Paths || Paths->begin() == Paths->end())
  5230. DiagKind = 1;
  5231. else if (Paths->isAmbiguous(CQT))
  5232. DiagKind = 2;
  5233. else {
  5234. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  5235. DiagKind = 3;
  5236. }
  5237. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  5238. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  5239. << Info.Ctx.getRecordType(DynType->Type)
  5240. << E->getType().getUnqualifiedType();
  5241. return false;
  5242. };
  5243. // Runtime check, phase 1:
  5244. // Walk from the base subobject towards the derived object looking for the
  5245. // target type.
  5246. for (int PathLength = Ptr.Designator.Entries.size();
  5247. PathLength >= (int)DynType->PathLength; --PathLength) {
  5248. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  5249. if (declaresSameEntity(Class, C))
  5250. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  5251. // We can only walk across public inheritance edges.
  5252. if (PathLength > (int)DynType->PathLength &&
  5253. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  5254. Class))
  5255. return RuntimeCheckFailed(nullptr);
  5256. }
  5257. // Runtime check, phase 2:
  5258. // Search the dynamic type for an unambiguous public base of type C.
  5259. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  5260. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  5261. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  5262. Paths.front().Access == AS_public) {
  5263. // Downcast to the dynamic type...
  5264. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  5265. return false;
  5266. // ... then upcast to the chosen base class subobject.
  5267. for (CXXBasePathElement &Elem : Paths.front())
  5268. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  5269. return false;
  5270. return true;
  5271. }
  5272. // Otherwise, the runtime check fails.
  5273. return RuntimeCheckFailed(&Paths);
  5274. }
  5275. namespace {
  5276. struct StartLifetimeOfUnionMemberHandler {
  5277. EvalInfo &Info;
  5278. const Expr *LHSExpr;
  5279. const FieldDecl *Field;
  5280. bool DuringInit;
  5281. bool Failed = false;
  5282. static const AccessKinds AccessKind = AK_Assign;
  5283. typedef bool result_type;
  5284. bool failed() { return Failed; }
  5285. bool found(APValue &Subobj, QualType SubobjType) {
  5286. // We are supposed to perform no initialization but begin the lifetime of
  5287. // the object. We interpret that as meaning to do what default
  5288. // initialization of the object would do if all constructors involved were
  5289. // trivial:
  5290. // * All base, non-variant member, and array element subobjects' lifetimes
  5291. // begin
  5292. // * No variant members' lifetimes begin
  5293. // * All scalar subobjects whose lifetimes begin have indeterminate values
  5294. assert(SubobjType->isUnionType());
  5295. if (declaresSameEntity(Subobj.getUnionField(), Field)) {
  5296. // This union member is already active. If it's also in-lifetime, there's
  5297. // nothing to do.
  5298. if (Subobj.getUnionValue().hasValue())
  5299. return true;
  5300. } else if (DuringInit) {
  5301. // We're currently in the process of initializing a different union
  5302. // member. If we carried on, that initialization would attempt to
  5303. // store to an inactive union member, resulting in undefined behavior.
  5304. Info.FFDiag(LHSExpr,
  5305. diag::note_constexpr_union_member_change_during_init);
  5306. return false;
  5307. }
  5308. APValue Result;
  5309. Failed = !getDefaultInitValue(Field->getType(), Result);
  5310. Subobj.setUnion(Field, Result);
  5311. return true;
  5312. }
  5313. bool found(APSInt &Value, QualType SubobjType) {
  5314. llvm_unreachable("wrong value kind for union object");
  5315. }
  5316. bool found(APFloat &Value, QualType SubobjType) {
  5317. llvm_unreachable("wrong value kind for union object");
  5318. }
  5319. };
  5320. } // end anonymous namespace
  5321. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  5322. /// Handle a builtin simple-assignment or a call to a trivial assignment
  5323. /// operator whose left-hand side might involve a union member access. If it
  5324. /// does, implicitly start the lifetime of any accessed union elements per
  5325. /// C++20 [class.union]5.
  5326. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  5327. const LValue &LHS) {
  5328. if (LHS.InvalidBase || LHS.Designator.Invalid)
  5329. return false;
  5330. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  5331. // C++ [class.union]p5:
  5332. // define the set S(E) of subexpressions of E as follows:
  5333. unsigned PathLength = LHS.Designator.Entries.size();
  5334. for (const Expr *E = LHSExpr; E != nullptr;) {
  5335. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  5336. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  5337. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  5338. // Note that we can't implicitly start the lifetime of a reference,
  5339. // so we don't need to proceed any further if we reach one.
  5340. if (!FD || FD->getType()->isReferenceType())
  5341. break;
  5342. // ... and also contains A.B if B names a union member ...
  5343. if (FD->getParent()->isUnion()) {
  5344. // ... of a non-class, non-array type, or of a class type with a
  5345. // trivial default constructor that is not deleted, or an array of
  5346. // such types.
  5347. auto *RD =
  5348. FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  5349. if (!RD || RD->hasTrivialDefaultConstructor())
  5350. UnionPathLengths.push_back({PathLength - 1, FD});
  5351. }
  5352. E = ME->getBase();
  5353. --PathLength;
  5354. assert(declaresSameEntity(FD,
  5355. LHS.Designator.Entries[PathLength]
  5356. .getAsBaseOrMember().getPointer()));
  5357. // -- If E is of the form A[B] and is interpreted as a built-in array
  5358. // subscripting operator, S(E) is [S(the array operand, if any)].
  5359. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  5360. // Step over an ArrayToPointerDecay implicit cast.
  5361. auto *Base = ASE->getBase()->IgnoreImplicit();
  5362. if (!Base->getType()->isArrayType())
  5363. break;
  5364. E = Base;
  5365. --PathLength;
  5366. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5367. // Step over a derived-to-base conversion.
  5368. E = ICE->getSubExpr();
  5369. if (ICE->getCastKind() == CK_NoOp)
  5370. continue;
  5371. if (ICE->getCastKind() != CK_DerivedToBase &&
  5372. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  5373. break;
  5374. // Walk path backwards as we walk up from the base to the derived class.
  5375. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  5376. --PathLength;
  5377. (void)Elt;
  5378. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  5379. LHS.Designator.Entries[PathLength]
  5380. .getAsBaseOrMember().getPointer()));
  5381. }
  5382. // -- Otherwise, S(E) is empty.
  5383. } else {
  5384. break;
  5385. }
  5386. }
  5387. // Common case: no unions' lifetimes are started.
  5388. if (UnionPathLengths.empty())
  5389. return true;
  5390. // if modification of X [would access an inactive union member], an object
  5391. // of the type of X is implicitly created
  5392. CompleteObject Obj =
  5393. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  5394. if (!Obj)
  5395. return false;
  5396. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  5397. llvm::reverse(UnionPathLengths)) {
  5398. // Form a designator for the union object.
  5399. SubobjectDesignator D = LHS.Designator;
  5400. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  5401. bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
  5402. ConstructionPhase::AfterBases;
  5403. StartLifetimeOfUnionMemberHandler StartLifetime{
  5404. Info, LHSExpr, LengthAndField.second, DuringInit};
  5405. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  5406. return false;
  5407. }
  5408. return true;
  5409. }
  5410. static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
  5411. CallRef Call, EvalInfo &Info,
  5412. bool NonNull = false) {
  5413. LValue LV;
  5414. // Create the parameter slot and register its destruction. For a vararg
  5415. // argument, create a temporary.
  5416. // FIXME: For calling conventions that destroy parameters in the callee,
  5417. // should we consider performing destruction when the function returns
  5418. // instead?
  5419. APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
  5420. : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
  5421. ScopeKind::Call, LV);
  5422. if (!EvaluateInPlace(V, Info, LV, Arg))
  5423. return false;
  5424. // Passing a null pointer to an __attribute__((nonnull)) parameter results in
  5425. // undefined behavior, so is non-constant.
  5426. if (NonNull && V.isLValue() && V.isNullPointer()) {
  5427. Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
  5428. return false;
  5429. }
  5430. return true;
  5431. }
  5432. /// Evaluate the arguments to a function call.
  5433. static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
  5434. EvalInfo &Info, const FunctionDecl *Callee,
  5435. bool RightToLeft = false) {
  5436. bool Success = true;
  5437. llvm::SmallBitVector ForbiddenNullArgs;
  5438. if (Callee->hasAttr<NonNullAttr>()) {
  5439. ForbiddenNullArgs.resize(Args.size());
  5440. for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
  5441. if (!Attr->args_size()) {
  5442. ForbiddenNullArgs.set();
  5443. break;
  5444. } else
  5445. for (auto Idx : Attr->args()) {
  5446. unsigned ASTIdx = Idx.getASTIndex();
  5447. if (ASTIdx >= Args.size())
  5448. continue;
  5449. ForbiddenNullArgs[ASTIdx] = true;
  5450. }
  5451. }
  5452. }
  5453. for (unsigned I = 0; I < Args.size(); I++) {
  5454. unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
  5455. const ParmVarDecl *PVD =
  5456. Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
  5457. bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
  5458. if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
  5459. // If we're checking for a potential constant expression, evaluate all
  5460. // initializers even if some of them fail.
  5461. if (!Info.noteFailure())
  5462. return false;
  5463. Success = false;
  5464. }
  5465. }
  5466. return Success;
  5467. }
  5468. /// Perform a trivial copy from Param, which is the parameter of a copy or move
  5469. /// constructor or assignment operator.
  5470. static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
  5471. const Expr *E, APValue &Result,
  5472. bool CopyObjectRepresentation) {
  5473. // Find the reference argument.
  5474. CallStackFrame *Frame = Info.CurrentCall;
  5475. APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
  5476. if (!RefValue) {
  5477. Info.FFDiag(E);
  5478. return false;
  5479. }
  5480. // Copy out the contents of the RHS object.
  5481. LValue RefLValue;
  5482. RefLValue.setFrom(Info.Ctx, *RefValue);
  5483. return handleLValueToRValueConversion(
  5484. Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
  5485. CopyObjectRepresentation);
  5486. }
  5487. /// Evaluate a function call.
  5488. static bool HandleFunctionCall(SourceLocation CallLoc,
  5489. const FunctionDecl *Callee, const LValue *This,
  5490. ArrayRef<const Expr *> Args, CallRef Call,
  5491. const Stmt *Body, EvalInfo &Info,
  5492. APValue &Result, const LValue *ResultSlot) {
  5493. if (!Info.CheckCallLimit(CallLoc))
  5494. return false;
  5495. CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
  5496. // For a trivial copy or move assignment, perform an APValue copy. This is
  5497. // essential for unions, where the operations performed by the assignment
  5498. // operator cannot be represented as statements.
  5499. //
  5500. // Skip this for non-union classes with no fields; in that case, the defaulted
  5501. // copy/move does not actually read the object.
  5502. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  5503. if (MD && MD->isDefaulted() &&
  5504. (MD->getParent()->isUnion() ||
  5505. (MD->isTrivial() &&
  5506. isReadByLvalueToRvalueConversion(MD->getParent())))) {
  5507. assert(This &&
  5508. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  5509. APValue RHSValue;
  5510. if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
  5511. MD->getParent()->isUnion()))
  5512. return false;
  5513. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  5514. RHSValue))
  5515. return false;
  5516. This->moveInto(Result);
  5517. return true;
  5518. } else if (MD && isLambdaCallOperator(MD)) {
  5519. // We're in a lambda; determine the lambda capture field maps unless we're
  5520. // just constexpr checking a lambda's call operator. constexpr checking is
  5521. // done before the captures have been added to the closure object (unless
  5522. // we're inferring constexpr-ness), so we don't have access to them in this
  5523. // case. But since we don't need the captures to constexpr check, we can
  5524. // just ignore them.
  5525. if (!Info.checkingPotentialConstantExpression())
  5526. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  5527. Frame.LambdaThisCaptureField);
  5528. }
  5529. StmtResult Ret = {Result, ResultSlot};
  5530. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  5531. if (ESR == ESR_Succeeded) {
  5532. if (Callee->getReturnType()->isVoidType())
  5533. return true;
  5534. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  5535. }
  5536. return ESR == ESR_Returned;
  5537. }
  5538. /// Evaluate a constructor call.
  5539. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  5540. CallRef Call,
  5541. const CXXConstructorDecl *Definition,
  5542. EvalInfo &Info, APValue &Result) {
  5543. SourceLocation CallLoc = E->getExprLoc();
  5544. if (!Info.CheckCallLimit(CallLoc))
  5545. return false;
  5546. const CXXRecordDecl *RD = Definition->getParent();
  5547. if (RD->getNumVBases()) {
  5548. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  5549. return false;
  5550. }
  5551. EvalInfo::EvaluatingConstructorRAII EvalObj(
  5552. Info,
  5553. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  5554. RD->getNumBases());
  5555. CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
  5556. // FIXME: Creating an APValue just to hold a nonexistent return value is
  5557. // wasteful.
  5558. APValue RetVal;
  5559. StmtResult Ret = {RetVal, nullptr};
  5560. // If it's a delegating constructor, delegate.
  5561. if (Definition->isDelegatingConstructor()) {
  5562. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  5563. if ((*I)->getInit()->isValueDependent()) {
  5564. if (!EvaluateDependentExpr((*I)->getInit(), Info))
  5565. return false;
  5566. } else {
  5567. FullExpressionRAII InitScope(Info);
  5568. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
  5569. !InitScope.destroy())
  5570. return false;
  5571. }
  5572. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  5573. }
  5574. // For a trivial copy or move constructor, perform an APValue copy. This is
  5575. // essential for unions (or classes with anonymous union members), where the
  5576. // operations performed by the constructor cannot be represented by
  5577. // ctor-initializers.
  5578. //
  5579. // Skip this for empty non-union classes; we should not perform an
  5580. // lvalue-to-rvalue conversion on them because their copy constructor does not
  5581. // actually read them.
  5582. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  5583. (Definition->getParent()->isUnion() ||
  5584. (Definition->isTrivial() &&
  5585. isReadByLvalueToRvalueConversion(Definition->getParent())))) {
  5586. return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
  5587. Definition->getParent()->isUnion());
  5588. }
  5589. // Reserve space for the struct members.
  5590. if (!Result.hasValue()) {
  5591. if (!RD->isUnion())
  5592. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  5593. std::distance(RD->field_begin(), RD->field_end()));
  5594. else
  5595. // A union starts with no active member.
  5596. Result = APValue((const FieldDecl*)nullptr);
  5597. }
  5598. if (RD->isInvalidDecl()) return false;
  5599. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5600. // A scope for temporaries lifetime-extended by reference members.
  5601. BlockScopeRAII LifetimeExtendedScope(Info);
  5602. bool Success = true;
  5603. unsigned BasesSeen = 0;
  5604. #ifndef NDEBUG
  5605. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  5606. #endif
  5607. CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
  5608. auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
  5609. // We might be initializing the same field again if this is an indirect
  5610. // field initialization.
  5611. if (FieldIt == RD->field_end() ||
  5612. FieldIt->getFieldIndex() > FD->getFieldIndex()) {
  5613. assert(Indirect && "fields out of order?");
  5614. return;
  5615. }
  5616. // Default-initialize any fields with no explicit initializer.
  5617. for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
  5618. assert(FieldIt != RD->field_end() && "missing field?");
  5619. if (!FieldIt->isUnnamedBitfield())
  5620. Success &= getDefaultInitValue(
  5621. FieldIt->getType(),
  5622. Result.getStructField(FieldIt->getFieldIndex()));
  5623. }
  5624. ++FieldIt;
  5625. };
  5626. for (const auto *I : Definition->inits()) {
  5627. LValue Subobject = This;
  5628. LValue SubobjectParent = This;
  5629. APValue *Value = &Result;
  5630. // Determine the subobject to initialize.
  5631. FieldDecl *FD = nullptr;
  5632. if (I->isBaseInitializer()) {
  5633. QualType BaseType(I->getBaseClass(), 0);
  5634. #ifndef NDEBUG
  5635. // Non-virtual base classes are initialized in the order in the class
  5636. // definition. We have already checked for virtual base classes.
  5637. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  5638. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  5639. "base class initializers not in expected order");
  5640. ++BaseIt;
  5641. #endif
  5642. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  5643. BaseType->getAsCXXRecordDecl(), &Layout))
  5644. return false;
  5645. Value = &Result.getStructBase(BasesSeen++);
  5646. } else if ((FD = I->getMember())) {
  5647. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  5648. return false;
  5649. if (RD->isUnion()) {
  5650. Result = APValue(FD);
  5651. Value = &Result.getUnionValue();
  5652. } else {
  5653. SkipToField(FD, false);
  5654. Value = &Result.getStructField(FD->getFieldIndex());
  5655. }
  5656. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  5657. // Walk the indirect field decl's chain to find the object to initialize,
  5658. // and make sure we've initialized every step along it.
  5659. auto IndirectFieldChain = IFD->chain();
  5660. for (auto *C : IndirectFieldChain) {
  5661. FD = cast<FieldDecl>(C);
  5662. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  5663. // Switch the union field if it differs. This happens if we had
  5664. // preceding zero-initialization, and we're now initializing a union
  5665. // subobject other than the first.
  5666. // FIXME: In this case, the values of the other subobjects are
  5667. // specified, since zero-initialization sets all padding bits to zero.
  5668. if (!Value->hasValue() ||
  5669. (Value->isUnion() && Value->getUnionField() != FD)) {
  5670. if (CD->isUnion())
  5671. *Value = APValue(FD);
  5672. else
  5673. // FIXME: This immediately starts the lifetime of all members of
  5674. // an anonymous struct. It would be preferable to strictly start
  5675. // member lifetime in initialization order.
  5676. Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
  5677. }
  5678. // Store Subobject as its parent before updating it for the last element
  5679. // in the chain.
  5680. if (C == IndirectFieldChain.back())
  5681. SubobjectParent = Subobject;
  5682. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  5683. return false;
  5684. if (CD->isUnion())
  5685. Value = &Value->getUnionValue();
  5686. else {
  5687. if (C == IndirectFieldChain.front() && !RD->isUnion())
  5688. SkipToField(FD, true);
  5689. Value = &Value->getStructField(FD->getFieldIndex());
  5690. }
  5691. }
  5692. } else {
  5693. llvm_unreachable("unknown base initializer kind");
  5694. }
  5695. // Need to override This for implicit field initializers as in this case
  5696. // This refers to innermost anonymous struct/union containing initializer,
  5697. // not to currently constructed class.
  5698. const Expr *Init = I->getInit();
  5699. if (Init->isValueDependent()) {
  5700. if (!EvaluateDependentExpr(Init, Info))
  5701. return false;
  5702. } else {
  5703. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  5704. isa<CXXDefaultInitExpr>(Init));
  5705. FullExpressionRAII InitScope(Info);
  5706. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  5707. (FD && FD->isBitField() &&
  5708. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  5709. // If we're checking for a potential constant expression, evaluate all
  5710. // initializers even if some of them fail.
  5711. if (!Info.noteFailure())
  5712. return false;
  5713. Success = false;
  5714. }
  5715. }
  5716. // This is the point at which the dynamic type of the object becomes this
  5717. // class type.
  5718. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  5719. EvalObj.finishedConstructingBases();
  5720. }
  5721. // Default-initialize any remaining fields.
  5722. if (!RD->isUnion()) {
  5723. for (; FieldIt != RD->field_end(); ++FieldIt) {
  5724. if (!FieldIt->isUnnamedBitfield())
  5725. Success &= getDefaultInitValue(
  5726. FieldIt->getType(),
  5727. Result.getStructField(FieldIt->getFieldIndex()));
  5728. }
  5729. }
  5730. EvalObj.finishedConstructingFields();
  5731. return Success &&
  5732. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
  5733. LifetimeExtendedScope.destroy();
  5734. }
  5735. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  5736. ArrayRef<const Expr*> Args,
  5737. const CXXConstructorDecl *Definition,
  5738. EvalInfo &Info, APValue &Result) {
  5739. CallScopeRAII CallScope(Info);
  5740. CallRef Call = Info.CurrentCall->createCall(Definition);
  5741. if (!EvaluateArgs(Args, Call, Info, Definition))
  5742. return false;
  5743. return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
  5744. CallScope.destroy();
  5745. }
  5746. static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
  5747. const LValue &This, APValue &Value,
  5748. QualType T) {
  5749. // Objects can only be destroyed while they're within their lifetimes.
  5750. // FIXME: We have no representation for whether an object of type nullptr_t
  5751. // is in its lifetime; it usually doesn't matter. Perhaps we should model it
  5752. // as indeterminate instead?
  5753. if (Value.isAbsent() && !T->isNullPtrType()) {
  5754. APValue Printable;
  5755. This.moveInto(Printable);
  5756. Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
  5757. << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
  5758. return false;
  5759. }
  5760. // Invent an expression for location purposes.
  5761. // FIXME: We shouldn't need to do this.
  5762. OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
  5763. // For arrays, destroy elements right-to-left.
  5764. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
  5765. uint64_t Size = CAT->getSize().getZExtValue();
  5766. QualType ElemT = CAT->getElementType();
  5767. LValue ElemLV = This;
  5768. ElemLV.addArray(Info, &LocE, CAT);
  5769. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
  5770. return false;
  5771. // Ensure that we have actual array elements available to destroy; the
  5772. // destructors might mutate the value, so we can't run them on the array
  5773. // filler.
  5774. if (Size && Size > Value.getArrayInitializedElts())
  5775. expandArray(Value, Value.getArraySize() - 1);
  5776. for (; Size != 0; --Size) {
  5777. APValue &Elem = Value.getArrayInitializedElt(Size - 1);
  5778. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
  5779. !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
  5780. return false;
  5781. }
  5782. // End the lifetime of this array now.
  5783. Value = APValue();
  5784. return true;
  5785. }
  5786. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  5787. if (!RD) {
  5788. if (T.isDestructedType()) {
  5789. Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
  5790. return false;
  5791. }
  5792. Value = APValue();
  5793. return true;
  5794. }
  5795. if (RD->getNumVBases()) {
  5796. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  5797. return false;
  5798. }
  5799. const CXXDestructorDecl *DD = RD->getDestructor();
  5800. if (!DD && !RD->hasTrivialDestructor()) {
  5801. Info.FFDiag(CallLoc);
  5802. return false;
  5803. }
  5804. if (!DD || DD->isTrivial() ||
  5805. (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
  5806. // A trivial destructor just ends the lifetime of the object. Check for
  5807. // this case before checking for a body, because we might not bother
  5808. // building a body for a trivial destructor. Note that it doesn't matter
  5809. // whether the destructor is constexpr in this case; all trivial
  5810. // destructors are constexpr.
  5811. //
  5812. // If an anonymous union would be destroyed, some enclosing destructor must
  5813. // have been explicitly defined, and the anonymous union destruction should
  5814. // have no effect.
  5815. Value = APValue();
  5816. return true;
  5817. }
  5818. if (!Info.CheckCallLimit(CallLoc))
  5819. return false;
  5820. const FunctionDecl *Definition = nullptr;
  5821. const Stmt *Body = DD->getBody(Definition);
  5822. if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
  5823. return false;
  5824. CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
  5825. // We're now in the period of destruction of this object.
  5826. unsigned BasesLeft = RD->getNumBases();
  5827. EvalInfo::EvaluatingDestructorRAII EvalObj(
  5828. Info,
  5829. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
  5830. if (!EvalObj.DidInsert) {
  5831. // C++2a [class.dtor]p19:
  5832. // the behavior is undefined if the destructor is invoked for an object
  5833. // whose lifetime has ended
  5834. // (Note that formally the lifetime ends when the period of destruction
  5835. // begins, even though certain uses of the object remain valid until the
  5836. // period of destruction ends.)
  5837. Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
  5838. return false;
  5839. }
  5840. // FIXME: Creating an APValue just to hold a nonexistent return value is
  5841. // wasteful.
  5842. APValue RetVal;
  5843. StmtResult Ret = {RetVal, nullptr};
  5844. if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
  5845. return false;
  5846. // A union destructor does not implicitly destroy its members.
  5847. if (RD->isUnion())
  5848. return true;
  5849. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5850. // We don't have a good way to iterate fields in reverse, so collect all the
  5851. // fields first and then walk them backwards.
  5852. SmallVector<FieldDecl*, 16> Fields(RD->fields());
  5853. for (const FieldDecl *FD : llvm::reverse(Fields)) {
  5854. if (FD->isUnnamedBitfield())
  5855. continue;
  5856. LValue Subobject = This;
  5857. if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
  5858. return false;
  5859. APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
  5860. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5861. FD->getType()))
  5862. return false;
  5863. }
  5864. if (BasesLeft != 0)
  5865. EvalObj.startedDestroyingBases();
  5866. // Destroy base classes in reverse order.
  5867. for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
  5868. --BasesLeft;
  5869. QualType BaseType = Base.getType();
  5870. LValue Subobject = This;
  5871. if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
  5872. BaseType->getAsCXXRecordDecl(), &Layout))
  5873. return false;
  5874. APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
  5875. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5876. BaseType))
  5877. return false;
  5878. }
  5879. assert(BasesLeft == 0 && "NumBases was wrong?");
  5880. // The period of destruction ends now. The object is gone.
  5881. Value = APValue();
  5882. return true;
  5883. }
  5884. namespace {
  5885. struct DestroyObjectHandler {
  5886. EvalInfo &Info;
  5887. const Expr *E;
  5888. const LValue &This;
  5889. const AccessKinds AccessKind;
  5890. typedef bool result_type;
  5891. bool failed() { return false; }
  5892. bool found(APValue &Subobj, QualType SubobjType) {
  5893. return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
  5894. SubobjType);
  5895. }
  5896. bool found(APSInt &Value, QualType SubobjType) {
  5897. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5898. return false;
  5899. }
  5900. bool found(APFloat &Value, QualType SubobjType) {
  5901. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5902. return false;
  5903. }
  5904. };
  5905. }
  5906. /// Perform a destructor or pseudo-destructor call on the given object, which
  5907. /// might in general not be a complete object.
  5908. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  5909. const LValue &This, QualType ThisType) {
  5910. CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
  5911. DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
  5912. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  5913. }
  5914. /// Destroy and end the lifetime of the given complete object.
  5915. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  5916. APValue::LValueBase LVBase, APValue &Value,
  5917. QualType T) {
  5918. // If we've had an unmodeled side-effect, we can't rely on mutable state
  5919. // (such as the object we're about to destroy) being correct.
  5920. if (Info.EvalStatus.HasSideEffects)
  5921. return false;
  5922. LValue LV;
  5923. LV.set({LVBase});
  5924. return HandleDestructionImpl(Info, Loc, LV, Value, T);
  5925. }
  5926. /// Perform a call to 'perator new' or to `__builtin_operator_new'.
  5927. static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
  5928. LValue &Result) {
  5929. if (Info.checkingPotentialConstantExpression() ||
  5930. Info.SpeculativeEvaluationDepth)
  5931. return false;
  5932. // This is permitted only within a call to std::allocator<T>::allocate.
  5933. auto Caller = Info.getStdAllocatorCaller("allocate");
  5934. if (!Caller) {
  5935. Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
  5936. ? diag::note_constexpr_new_untyped
  5937. : diag::note_constexpr_new);
  5938. return false;
  5939. }
  5940. QualType ElemType = Caller.ElemType;
  5941. if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
  5942. Info.FFDiag(E->getExprLoc(),
  5943. diag::note_constexpr_new_not_complete_object_type)
  5944. << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
  5945. return false;
  5946. }
  5947. APSInt ByteSize;
  5948. if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
  5949. return false;
  5950. bool IsNothrow = false;
  5951. for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
  5952. EvaluateIgnoredValue(Info, E->getArg(I));
  5953. IsNothrow |= E->getType()->isNothrowT();
  5954. }
  5955. CharUnits ElemSize;
  5956. if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
  5957. return false;
  5958. APInt Size, Remainder;
  5959. APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
  5960. APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
  5961. if (Remainder != 0) {
  5962. // This likely indicates a bug in the implementation of 'std::allocator'.
  5963. Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
  5964. << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
  5965. return false;
  5966. }
  5967. if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  5968. if (IsNothrow) {
  5969. Result.setNull(Info.Ctx, E->getType());
  5970. return true;
  5971. }
  5972. Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
  5973. return false;
  5974. }
  5975. QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
  5976. ArrayType::Normal, 0);
  5977. APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
  5978. *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
  5979. Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
  5980. return true;
  5981. }
  5982. static bool hasVirtualDestructor(QualType T) {
  5983. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  5984. if (CXXDestructorDecl *DD = RD->getDestructor())
  5985. return DD->isVirtual();
  5986. return false;
  5987. }
  5988. static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
  5989. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  5990. if (CXXDestructorDecl *DD = RD->getDestructor())
  5991. return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
  5992. return nullptr;
  5993. }
  5994. /// Check that the given object is a suitable pointer to a heap allocation that
  5995. /// still exists and is of the right kind for the purpose of a deletion.
  5996. ///
  5997. /// On success, returns the heap allocation to deallocate. On failure, produces
  5998. /// a diagnostic and returns std::nullopt.
  5999. static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
  6000. const LValue &Pointer,
  6001. DynAlloc::Kind DeallocKind) {
  6002. auto PointerAsString = [&] {
  6003. return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
  6004. };
  6005. DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
  6006. if (!DA) {
  6007. Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
  6008. << PointerAsString();
  6009. if (Pointer.Base)
  6010. NoteLValueLocation(Info, Pointer.Base);
  6011. return std::nullopt;
  6012. }
  6013. std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
  6014. if (!Alloc) {
  6015. Info.FFDiag(E, diag::note_constexpr_double_delete);
  6016. return std::nullopt;
  6017. }
  6018. QualType AllocType = Pointer.Base.getDynamicAllocType();
  6019. if (DeallocKind != (*Alloc)->getKind()) {
  6020. Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
  6021. << DeallocKind << (*Alloc)->getKind() << AllocType;
  6022. NoteLValueLocation(Info, Pointer.Base);
  6023. return std::nullopt;
  6024. }
  6025. bool Subobject = false;
  6026. if (DeallocKind == DynAlloc::New) {
  6027. Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
  6028. Pointer.Designator.isOnePastTheEnd();
  6029. } else {
  6030. Subobject = Pointer.Designator.Entries.size() != 1 ||
  6031. Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
  6032. }
  6033. if (Subobject) {
  6034. Info.FFDiag(E, diag::note_constexpr_delete_subobject)
  6035. << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
  6036. return std::nullopt;
  6037. }
  6038. return Alloc;
  6039. }
  6040. // Perform a call to 'operator delete' or '__builtin_operator_delete'.
  6041. bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
  6042. if (Info.checkingPotentialConstantExpression() ||
  6043. Info.SpeculativeEvaluationDepth)
  6044. return false;
  6045. // This is permitted only within a call to std::allocator<T>::deallocate.
  6046. if (!Info.getStdAllocatorCaller("deallocate")) {
  6047. Info.FFDiag(E->getExprLoc());
  6048. return true;
  6049. }
  6050. LValue Pointer;
  6051. if (!EvaluatePointer(E->getArg(0), Pointer, Info))
  6052. return false;
  6053. for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
  6054. EvaluateIgnoredValue(Info, E->getArg(I));
  6055. if (Pointer.Designator.Invalid)
  6056. return false;
  6057. // Deleting a null pointer would have no effect, but it's not permitted by
  6058. // std::allocator<T>::deallocate's contract.
  6059. if (Pointer.isNullPointer()) {
  6060. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
  6061. return true;
  6062. }
  6063. if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
  6064. return false;
  6065. Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
  6066. return true;
  6067. }
  6068. //===----------------------------------------------------------------------===//
  6069. // Generic Evaluation
  6070. //===----------------------------------------------------------------------===//
  6071. namespace {
  6072. class BitCastBuffer {
  6073. // FIXME: We're going to need bit-level granularity when we support
  6074. // bit-fields.
  6075. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  6076. // we don't support a host or target where that is the case. Still, we should
  6077. // use a more generic type in case we ever do.
  6078. SmallVector<std::optional<unsigned char>, 32> Bytes;
  6079. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  6080. "Need at least 8 bit unsigned char");
  6081. bool TargetIsLittleEndian;
  6082. public:
  6083. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  6084. : Bytes(Width.getQuantity()),
  6085. TargetIsLittleEndian(TargetIsLittleEndian) {}
  6086. [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
  6087. SmallVectorImpl<unsigned char> &Output) const {
  6088. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  6089. // If a byte of an integer is uninitialized, then the whole integer is
  6090. // uninitialized.
  6091. if (!Bytes[I.getQuantity()])
  6092. return false;
  6093. Output.push_back(*Bytes[I.getQuantity()]);
  6094. }
  6095. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  6096. std::reverse(Output.begin(), Output.end());
  6097. return true;
  6098. }
  6099. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  6100. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  6101. std::reverse(Input.begin(), Input.end());
  6102. size_t Index = 0;
  6103. for (unsigned char Byte : Input) {
  6104. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  6105. Bytes[Offset.getQuantity() + Index] = Byte;
  6106. ++Index;
  6107. }
  6108. }
  6109. size_t size() { return Bytes.size(); }
  6110. };
  6111. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  6112. /// target would represent the value at runtime.
  6113. class APValueToBufferConverter {
  6114. EvalInfo &Info;
  6115. BitCastBuffer Buffer;
  6116. const CastExpr *BCE;
  6117. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  6118. const CastExpr *BCE)
  6119. : Info(Info),
  6120. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  6121. BCE(BCE) {}
  6122. bool visit(const APValue &Val, QualType Ty) {
  6123. return visit(Val, Ty, CharUnits::fromQuantity(0));
  6124. }
  6125. // Write out Val with type Ty into Buffer starting at Offset.
  6126. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  6127. assert((size_t)Offset.getQuantity() <= Buffer.size());
  6128. // As a special case, nullptr_t has an indeterminate value.
  6129. if (Ty->isNullPtrType())
  6130. return true;
  6131. // Dig through Src to find the byte at SrcOffset.
  6132. switch (Val.getKind()) {
  6133. case APValue::Indeterminate:
  6134. case APValue::None:
  6135. return true;
  6136. case APValue::Int:
  6137. return visitInt(Val.getInt(), Ty, Offset);
  6138. case APValue::Float:
  6139. return visitFloat(Val.getFloat(), Ty, Offset);
  6140. case APValue::Array:
  6141. return visitArray(Val, Ty, Offset);
  6142. case APValue::Struct:
  6143. return visitRecord(Val, Ty, Offset);
  6144. case APValue::ComplexInt:
  6145. case APValue::ComplexFloat:
  6146. case APValue::Vector:
  6147. case APValue::FixedPoint:
  6148. // FIXME: We should support these.
  6149. case APValue::Union:
  6150. case APValue::MemberPointer:
  6151. case APValue::AddrLabelDiff: {
  6152. Info.FFDiag(BCE->getBeginLoc(),
  6153. diag::note_constexpr_bit_cast_unsupported_type)
  6154. << Ty;
  6155. return false;
  6156. }
  6157. case APValue::LValue:
  6158. llvm_unreachable("LValue subobject in bit_cast?");
  6159. }
  6160. llvm_unreachable("Unhandled APValue::ValueKind");
  6161. }
  6162. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  6163. const RecordDecl *RD = Ty->getAsRecordDecl();
  6164. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6165. // Visit the base classes.
  6166. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  6167. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  6168. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  6169. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  6170. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  6171. Layout.getBaseClassOffset(BaseDecl) + Offset))
  6172. return false;
  6173. }
  6174. }
  6175. // Visit the fields.
  6176. unsigned FieldIdx = 0;
  6177. for (FieldDecl *FD : RD->fields()) {
  6178. if (FD->isBitField()) {
  6179. Info.FFDiag(BCE->getBeginLoc(),
  6180. diag::note_constexpr_bit_cast_unsupported_bitfield);
  6181. return false;
  6182. }
  6183. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  6184. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  6185. "only bit-fields can have sub-char alignment");
  6186. CharUnits FieldOffset =
  6187. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  6188. QualType FieldTy = FD->getType();
  6189. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  6190. return false;
  6191. ++FieldIdx;
  6192. }
  6193. return true;
  6194. }
  6195. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  6196. const auto *CAT =
  6197. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  6198. if (!CAT)
  6199. return false;
  6200. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  6201. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  6202. unsigned ArraySize = Val.getArraySize();
  6203. // First, initialize the initialized elements.
  6204. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  6205. const APValue &SubObj = Val.getArrayInitializedElt(I);
  6206. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  6207. return false;
  6208. }
  6209. // Next, initialize the rest of the array using the filler.
  6210. if (Val.hasArrayFiller()) {
  6211. const APValue &Filler = Val.getArrayFiller();
  6212. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  6213. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  6214. return false;
  6215. }
  6216. }
  6217. return true;
  6218. }
  6219. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  6220. APSInt AdjustedVal = Val;
  6221. unsigned Width = AdjustedVal.getBitWidth();
  6222. if (Ty->isBooleanType()) {
  6223. Width = Info.Ctx.getTypeSize(Ty);
  6224. AdjustedVal = AdjustedVal.extend(Width);
  6225. }
  6226. SmallVector<unsigned char, 8> Bytes(Width / 8);
  6227. llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
  6228. Buffer.writeObject(Offset, Bytes);
  6229. return true;
  6230. }
  6231. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  6232. APSInt AsInt(Val.bitcastToAPInt());
  6233. return visitInt(AsInt, Ty, Offset);
  6234. }
  6235. public:
  6236. static std::optional<BitCastBuffer>
  6237. convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
  6238. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  6239. APValueToBufferConverter Converter(Info, DstSize, BCE);
  6240. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  6241. return std::nullopt;
  6242. return Converter.Buffer;
  6243. }
  6244. };
  6245. /// Write an BitCastBuffer into an APValue.
  6246. class BufferToAPValueConverter {
  6247. EvalInfo &Info;
  6248. const BitCastBuffer &Buffer;
  6249. const CastExpr *BCE;
  6250. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  6251. const CastExpr *BCE)
  6252. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  6253. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  6254. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  6255. // Ideally this will be unreachable.
  6256. std::nullopt_t unsupportedType(QualType Ty) {
  6257. Info.FFDiag(BCE->getBeginLoc(),
  6258. diag::note_constexpr_bit_cast_unsupported_type)
  6259. << Ty;
  6260. return std::nullopt;
  6261. }
  6262. std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
  6263. Info.FFDiag(BCE->getBeginLoc(),
  6264. diag::note_constexpr_bit_cast_unrepresentable_value)
  6265. << Ty << toString(Val, /*Radix=*/10);
  6266. return std::nullopt;
  6267. }
  6268. std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  6269. const EnumType *EnumSugar = nullptr) {
  6270. if (T->isNullPtrType()) {
  6271. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  6272. return APValue((Expr *)nullptr,
  6273. /*Offset=*/CharUnits::fromQuantity(NullValue),
  6274. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  6275. }
  6276. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  6277. // Work around floating point types that contain unused padding bytes. This
  6278. // is really just `long double` on x86, which is the only fundamental type
  6279. // with padding bytes.
  6280. if (T->isRealFloatingType()) {
  6281. const llvm::fltSemantics &Semantics =
  6282. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  6283. unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
  6284. assert(NumBits % 8 == 0);
  6285. CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
  6286. if (NumBytes != SizeOf)
  6287. SizeOf = NumBytes;
  6288. }
  6289. SmallVector<uint8_t, 8> Bytes;
  6290. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  6291. // If this is std::byte or unsigned char, then its okay to store an
  6292. // indeterminate value.
  6293. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  6294. bool IsUChar =
  6295. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  6296. T->isSpecificBuiltinType(BuiltinType::Char_U));
  6297. if (!IsStdByte && !IsUChar) {
  6298. QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
  6299. Info.FFDiag(BCE->getExprLoc(),
  6300. diag::note_constexpr_bit_cast_indet_dest)
  6301. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  6302. return std::nullopt;
  6303. }
  6304. return APValue::IndeterminateValue();
  6305. }
  6306. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  6307. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  6308. if (T->isIntegralOrEnumerationType()) {
  6309. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  6310. unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
  6311. if (IntWidth != Val.getBitWidth()) {
  6312. APSInt Truncated = Val.trunc(IntWidth);
  6313. if (Truncated.extend(Val.getBitWidth()) != Val)
  6314. return unrepresentableValue(QualType(T, 0), Val);
  6315. Val = Truncated;
  6316. }
  6317. return APValue(Val);
  6318. }
  6319. if (T->isRealFloatingType()) {
  6320. const llvm::fltSemantics &Semantics =
  6321. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  6322. return APValue(APFloat(Semantics, Val));
  6323. }
  6324. return unsupportedType(QualType(T, 0));
  6325. }
  6326. std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  6327. const RecordDecl *RD = RTy->getAsRecordDecl();
  6328. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6329. unsigned NumBases = 0;
  6330. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  6331. NumBases = CXXRD->getNumBases();
  6332. APValue ResultVal(APValue::UninitStruct(), NumBases,
  6333. std::distance(RD->field_begin(), RD->field_end()));
  6334. // Visit the base classes.
  6335. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  6336. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  6337. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  6338. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  6339. if (BaseDecl->isEmpty() ||
  6340. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  6341. continue;
  6342. std::optional<APValue> SubObj = visitType(
  6343. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  6344. if (!SubObj)
  6345. return std::nullopt;
  6346. ResultVal.getStructBase(I) = *SubObj;
  6347. }
  6348. }
  6349. // Visit the fields.
  6350. unsigned FieldIdx = 0;
  6351. for (FieldDecl *FD : RD->fields()) {
  6352. // FIXME: We don't currently support bit-fields. A lot of the logic for
  6353. // this is in CodeGen, so we need to factor it around.
  6354. if (FD->isBitField()) {
  6355. Info.FFDiag(BCE->getBeginLoc(),
  6356. diag::note_constexpr_bit_cast_unsupported_bitfield);
  6357. return std::nullopt;
  6358. }
  6359. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  6360. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  6361. CharUnits FieldOffset =
  6362. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  6363. Offset;
  6364. QualType FieldTy = FD->getType();
  6365. std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  6366. if (!SubObj)
  6367. return std::nullopt;
  6368. ResultVal.getStructField(FieldIdx) = *SubObj;
  6369. ++FieldIdx;
  6370. }
  6371. return ResultVal;
  6372. }
  6373. std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  6374. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  6375. assert(!RepresentationType.isNull() &&
  6376. "enum forward decl should be caught by Sema");
  6377. const auto *AsBuiltin =
  6378. RepresentationType.getCanonicalType()->castAs<BuiltinType>();
  6379. // Recurse into the underlying type. Treat std::byte transparently as
  6380. // unsigned char.
  6381. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  6382. }
  6383. std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  6384. size_t Size = Ty->getSize().getLimitedValue();
  6385. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  6386. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  6387. for (size_t I = 0; I != Size; ++I) {
  6388. std::optional<APValue> ElementValue =
  6389. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  6390. if (!ElementValue)
  6391. return std::nullopt;
  6392. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  6393. }
  6394. return ArrayValue;
  6395. }
  6396. std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  6397. return unsupportedType(QualType(Ty, 0));
  6398. }
  6399. std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  6400. QualType Can = Ty.getCanonicalType();
  6401. switch (Can->getTypeClass()) {
  6402. #define TYPE(Class, Base) \
  6403. case Type::Class: \
  6404. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  6405. #define ABSTRACT_TYPE(Class, Base)
  6406. #define NON_CANONICAL_TYPE(Class, Base) \
  6407. case Type::Class: \
  6408. llvm_unreachable("non-canonical type should be impossible!");
  6409. #define DEPENDENT_TYPE(Class, Base) \
  6410. case Type::Class: \
  6411. llvm_unreachable( \
  6412. "dependent types aren't supported in the constant evaluator!");
  6413. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  6414. case Type::Class: \
  6415. llvm_unreachable("either dependent or not canonical!");
  6416. #include "clang/AST/TypeNodes.inc"
  6417. }
  6418. llvm_unreachable("Unhandled Type::TypeClass");
  6419. }
  6420. public:
  6421. // Pull out a full value of type DstType.
  6422. static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  6423. const CastExpr *BCE) {
  6424. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  6425. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  6426. }
  6427. };
  6428. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  6429. QualType Ty, EvalInfo *Info,
  6430. const ASTContext &Ctx,
  6431. bool CheckingDest) {
  6432. Ty = Ty.getCanonicalType();
  6433. auto diag = [&](int Reason) {
  6434. if (Info)
  6435. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  6436. << CheckingDest << (Reason == 4) << Reason;
  6437. return false;
  6438. };
  6439. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  6440. if (Info)
  6441. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  6442. << NoteTy << Construct << Ty;
  6443. return false;
  6444. };
  6445. if (Ty->isUnionType())
  6446. return diag(0);
  6447. if (Ty->isPointerType())
  6448. return diag(1);
  6449. if (Ty->isMemberPointerType())
  6450. return diag(2);
  6451. if (Ty.isVolatileQualified())
  6452. return diag(3);
  6453. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  6454. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  6455. for (CXXBaseSpecifier &BS : CXXRD->bases())
  6456. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  6457. CheckingDest))
  6458. return note(1, BS.getType(), BS.getBeginLoc());
  6459. }
  6460. for (FieldDecl *FD : Record->fields()) {
  6461. if (FD->getType()->isReferenceType())
  6462. return diag(4);
  6463. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  6464. CheckingDest))
  6465. return note(0, FD->getType(), FD->getBeginLoc());
  6466. }
  6467. }
  6468. if (Ty->isArrayType() &&
  6469. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  6470. Info, Ctx, CheckingDest))
  6471. return false;
  6472. return true;
  6473. }
  6474. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  6475. const ASTContext &Ctx,
  6476. const CastExpr *BCE) {
  6477. bool DestOK = checkBitCastConstexprEligibilityType(
  6478. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  6479. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  6480. BCE->getBeginLoc(),
  6481. BCE->getSubExpr()->getType(), Info, Ctx, false);
  6482. return SourceOK;
  6483. }
  6484. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  6485. APValue &SourceValue,
  6486. const CastExpr *BCE) {
  6487. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  6488. "no host or target supports non 8-bit chars");
  6489. assert(SourceValue.isLValue() &&
  6490. "LValueToRValueBitcast requires an lvalue operand!");
  6491. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  6492. return false;
  6493. LValue SourceLValue;
  6494. APValue SourceRValue;
  6495. SourceLValue.setFrom(Info.Ctx, SourceValue);
  6496. if (!handleLValueToRValueConversion(
  6497. Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
  6498. SourceRValue, /*WantObjectRepresentation=*/true))
  6499. return false;
  6500. // Read out SourceValue into a char buffer.
  6501. std::optional<BitCastBuffer> Buffer =
  6502. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  6503. if (!Buffer)
  6504. return false;
  6505. // Write out the buffer into a new APValue.
  6506. std::optional<APValue> MaybeDestValue =
  6507. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  6508. if (!MaybeDestValue)
  6509. return false;
  6510. DestValue = std::move(*MaybeDestValue);
  6511. return true;
  6512. }
  6513. template <class Derived>
  6514. class ExprEvaluatorBase
  6515. : public ConstStmtVisitor<Derived, bool> {
  6516. private:
  6517. Derived &getDerived() { return static_cast<Derived&>(*this); }
  6518. bool DerivedSuccess(const APValue &V, const Expr *E) {
  6519. return getDerived().Success(V, E);
  6520. }
  6521. bool DerivedZeroInitialization(const Expr *E) {
  6522. return getDerived().ZeroInitialization(E);
  6523. }
  6524. // Check whether a conditional operator with a non-constant condition is a
  6525. // potential constant expression. If neither arm is a potential constant
  6526. // expression, then the conditional operator is not either.
  6527. template<typename ConditionalOperator>
  6528. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  6529. assert(Info.checkingPotentialConstantExpression());
  6530. // Speculatively evaluate both arms.
  6531. SmallVector<PartialDiagnosticAt, 8> Diag;
  6532. {
  6533. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  6534. StmtVisitorTy::Visit(E->getFalseExpr());
  6535. if (Diag.empty())
  6536. return;
  6537. }
  6538. {
  6539. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  6540. Diag.clear();
  6541. StmtVisitorTy::Visit(E->getTrueExpr());
  6542. if (Diag.empty())
  6543. return;
  6544. }
  6545. Error(E, diag::note_constexpr_conditional_never_const);
  6546. }
  6547. template<typename ConditionalOperator>
  6548. bool HandleConditionalOperator(const ConditionalOperator *E) {
  6549. bool BoolResult;
  6550. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  6551. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  6552. CheckPotentialConstantConditional(E);
  6553. return false;
  6554. }
  6555. if (Info.noteFailure()) {
  6556. StmtVisitorTy::Visit(E->getTrueExpr());
  6557. StmtVisitorTy::Visit(E->getFalseExpr());
  6558. }
  6559. return false;
  6560. }
  6561. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  6562. return StmtVisitorTy::Visit(EvalExpr);
  6563. }
  6564. protected:
  6565. EvalInfo &Info;
  6566. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  6567. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  6568. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  6569. return Info.CCEDiag(E, D);
  6570. }
  6571. bool ZeroInitialization(const Expr *E) { return Error(E); }
  6572. bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
  6573. unsigned BuiltinOp = E->getBuiltinCallee();
  6574. return BuiltinOp != 0 &&
  6575. Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
  6576. }
  6577. public:
  6578. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  6579. EvalInfo &getEvalInfo() { return Info; }
  6580. /// Report an evaluation error. This should only be called when an error is
  6581. /// first discovered. When propagating an error, just return false.
  6582. bool Error(const Expr *E, diag::kind D) {
  6583. Info.FFDiag(E, D);
  6584. return false;
  6585. }
  6586. bool Error(const Expr *E) {
  6587. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  6588. }
  6589. bool VisitStmt(const Stmt *) {
  6590. llvm_unreachable("Expression evaluator should not be called on stmts");
  6591. }
  6592. bool VisitExpr(const Expr *E) {
  6593. return Error(E);
  6594. }
  6595. bool VisitConstantExpr(const ConstantExpr *E) {
  6596. if (E->hasAPValueResult())
  6597. return DerivedSuccess(E->getAPValueResult(), E);
  6598. return StmtVisitorTy::Visit(E->getSubExpr());
  6599. }
  6600. bool VisitParenExpr(const ParenExpr *E)
  6601. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  6602. bool VisitUnaryExtension(const UnaryOperator *E)
  6603. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  6604. bool VisitUnaryPlus(const UnaryOperator *E)
  6605. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  6606. bool VisitChooseExpr(const ChooseExpr *E)
  6607. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  6608. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  6609. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  6610. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  6611. { return StmtVisitorTy::Visit(E->getReplacement()); }
  6612. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  6613. TempVersionRAII RAII(*Info.CurrentCall);
  6614. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  6615. return StmtVisitorTy::Visit(E->getExpr());
  6616. }
  6617. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  6618. TempVersionRAII RAII(*Info.CurrentCall);
  6619. // The initializer may not have been parsed yet, or might be erroneous.
  6620. if (!E->getExpr())
  6621. return Error(E);
  6622. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  6623. return StmtVisitorTy::Visit(E->getExpr());
  6624. }
  6625. bool VisitExprWithCleanups(const ExprWithCleanups *E) {
  6626. FullExpressionRAII Scope(Info);
  6627. return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
  6628. }
  6629. // Temporaries are registered when created, so we don't care about
  6630. // CXXBindTemporaryExpr.
  6631. bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
  6632. return StmtVisitorTy::Visit(E->getSubExpr());
  6633. }
  6634. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  6635. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  6636. return static_cast<Derived*>(this)->VisitCastExpr(E);
  6637. }
  6638. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  6639. if (!Info.Ctx.getLangOpts().CPlusPlus20)
  6640. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  6641. return static_cast<Derived*>(this)->VisitCastExpr(E);
  6642. }
  6643. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  6644. return static_cast<Derived*>(this)->VisitCastExpr(E);
  6645. }
  6646. bool VisitBinaryOperator(const BinaryOperator *E) {
  6647. switch (E->getOpcode()) {
  6648. default:
  6649. return Error(E);
  6650. case BO_Comma:
  6651. VisitIgnoredValue(E->getLHS());
  6652. return StmtVisitorTy::Visit(E->getRHS());
  6653. case BO_PtrMemD:
  6654. case BO_PtrMemI: {
  6655. LValue Obj;
  6656. if (!HandleMemberPointerAccess(Info, E, Obj))
  6657. return false;
  6658. APValue Result;
  6659. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  6660. return false;
  6661. return DerivedSuccess(Result, E);
  6662. }
  6663. }
  6664. }
  6665. bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
  6666. return StmtVisitorTy::Visit(E->getSemanticForm());
  6667. }
  6668. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  6669. // Evaluate and cache the common expression. We treat it as a temporary,
  6670. // even though it's not quite the same thing.
  6671. LValue CommonLV;
  6672. if (!Evaluate(Info.CurrentCall->createTemporary(
  6673. E->getOpaqueValue(),
  6674. getStorageType(Info.Ctx, E->getOpaqueValue()),
  6675. ScopeKind::FullExpression, CommonLV),
  6676. Info, E->getCommon()))
  6677. return false;
  6678. return HandleConditionalOperator(E);
  6679. }
  6680. bool VisitConditionalOperator(const ConditionalOperator *E) {
  6681. bool IsBcpCall = false;
  6682. // If the condition (ignoring parens) is a __builtin_constant_p call,
  6683. // the result is a constant expression if it can be folded without
  6684. // side-effects. This is an important GNU extension. See GCC PR38377
  6685. // for discussion.
  6686. if (const CallExpr *CallCE =
  6687. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  6688. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  6689. IsBcpCall = true;
  6690. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  6691. // constant expression; we can't check whether it's potentially foldable.
  6692. // FIXME: We should instead treat __builtin_constant_p as non-constant if
  6693. // it would return 'false' in this mode.
  6694. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  6695. return false;
  6696. FoldConstant Fold(Info, IsBcpCall);
  6697. if (!HandleConditionalOperator(E)) {
  6698. Fold.keepDiagnostics();
  6699. return false;
  6700. }
  6701. return true;
  6702. }
  6703. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  6704. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  6705. return DerivedSuccess(*Value, E);
  6706. const Expr *Source = E->getSourceExpr();
  6707. if (!Source)
  6708. return Error(E);
  6709. if (Source == E) {
  6710. assert(0 && "OpaqueValueExpr recursively refers to itself");
  6711. return Error(E);
  6712. }
  6713. return StmtVisitorTy::Visit(Source);
  6714. }
  6715. bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
  6716. for (const Expr *SemE : E->semantics()) {
  6717. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
  6718. // FIXME: We can't handle the case where an OpaqueValueExpr is also the
  6719. // result expression: there could be two different LValues that would
  6720. // refer to the same object in that case, and we can't model that.
  6721. if (SemE == E->getResultExpr())
  6722. return Error(E);
  6723. // Unique OVEs get evaluated if and when we encounter them when
  6724. // emitting the rest of the semantic form, rather than eagerly.
  6725. if (OVE->isUnique())
  6726. continue;
  6727. LValue LV;
  6728. if (!Evaluate(Info.CurrentCall->createTemporary(
  6729. OVE, getStorageType(Info.Ctx, OVE),
  6730. ScopeKind::FullExpression, LV),
  6731. Info, OVE->getSourceExpr()))
  6732. return false;
  6733. } else if (SemE == E->getResultExpr()) {
  6734. if (!StmtVisitorTy::Visit(SemE))
  6735. return false;
  6736. } else {
  6737. if (!EvaluateIgnoredValue(Info, SemE))
  6738. return false;
  6739. }
  6740. }
  6741. return true;
  6742. }
  6743. bool VisitCallExpr(const CallExpr *E) {
  6744. APValue Result;
  6745. if (!handleCallExpr(E, Result, nullptr))
  6746. return false;
  6747. return DerivedSuccess(Result, E);
  6748. }
  6749. bool handleCallExpr(const CallExpr *E, APValue &Result,
  6750. const LValue *ResultSlot) {
  6751. CallScopeRAII CallScope(Info);
  6752. const Expr *Callee = E->getCallee()->IgnoreParens();
  6753. QualType CalleeType = Callee->getType();
  6754. const FunctionDecl *FD = nullptr;
  6755. LValue *This = nullptr, ThisVal;
  6756. auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
  6757. bool HasQualifier = false;
  6758. CallRef Call;
  6759. // Extract function decl and 'this' pointer from the callee.
  6760. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  6761. const CXXMethodDecl *Member = nullptr;
  6762. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  6763. // Explicit bound member calls, such as x.f() or p->g();
  6764. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  6765. return false;
  6766. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  6767. if (!Member)
  6768. return Error(Callee);
  6769. This = &ThisVal;
  6770. HasQualifier = ME->hasQualifier();
  6771. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  6772. // Indirect bound member calls ('.*' or '->*').
  6773. const ValueDecl *D =
  6774. HandleMemberPointerAccess(Info, BE, ThisVal, false);
  6775. if (!D)
  6776. return false;
  6777. Member = dyn_cast<CXXMethodDecl>(D);
  6778. if (!Member)
  6779. return Error(Callee);
  6780. This = &ThisVal;
  6781. } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
  6782. if (!Info.getLangOpts().CPlusPlus20)
  6783. Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
  6784. return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
  6785. HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
  6786. } else
  6787. return Error(Callee);
  6788. FD = Member;
  6789. } else if (CalleeType->isFunctionPointerType()) {
  6790. LValue CalleeLV;
  6791. if (!EvaluatePointer(Callee, CalleeLV, Info))
  6792. return false;
  6793. if (!CalleeLV.getLValueOffset().isZero())
  6794. return Error(Callee);
  6795. FD = dyn_cast_or_null<FunctionDecl>(
  6796. CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
  6797. if (!FD)
  6798. return Error(Callee);
  6799. // Don't call function pointers which have been cast to some other type.
  6800. // Per DR (no number yet), the caller and callee can differ in noexcept.
  6801. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  6802. CalleeType->getPointeeType(), FD->getType())) {
  6803. return Error(E);
  6804. }
  6805. // For an (overloaded) assignment expression, evaluate the RHS before the
  6806. // LHS.
  6807. auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
  6808. if (OCE && OCE->isAssignmentOp()) {
  6809. assert(Args.size() == 2 && "wrong number of arguments in assignment");
  6810. Call = Info.CurrentCall->createCall(FD);
  6811. if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
  6812. Info, FD, /*RightToLeft=*/true))
  6813. return false;
  6814. }
  6815. // Overloaded operator calls to member functions are represented as normal
  6816. // calls with '*this' as the first argument.
  6817. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6818. if (MD && !MD->isStatic()) {
  6819. // FIXME: When selecting an implicit conversion for an overloaded
  6820. // operator delete, we sometimes try to evaluate calls to conversion
  6821. // operators without a 'this' parameter!
  6822. if (Args.empty())
  6823. return Error(E);
  6824. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  6825. return false;
  6826. This = &ThisVal;
  6827. // If this is syntactically a simple assignment using a trivial
  6828. // assignment operator, start the lifetimes of union members as needed,
  6829. // per C++20 [class.union]5.
  6830. if (Info.getLangOpts().CPlusPlus20 && OCE &&
  6831. OCE->getOperator() == OO_Equal && MD->isTrivial() &&
  6832. !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
  6833. return false;
  6834. Args = Args.slice(1);
  6835. } else if (MD && MD->isLambdaStaticInvoker()) {
  6836. // Map the static invoker for the lambda back to the call operator.
  6837. // Conveniently, we don't have to slice out the 'this' argument (as is
  6838. // being done for the non-static case), since a static member function
  6839. // doesn't have an implicit argument passed in.
  6840. const CXXRecordDecl *ClosureClass = MD->getParent();
  6841. assert(
  6842. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  6843. "Number of captures must be zero for conversion to function-ptr");
  6844. const CXXMethodDecl *LambdaCallOp =
  6845. ClosureClass->getLambdaCallOperator();
  6846. // Set 'FD', the function that will be called below, to the call
  6847. // operator. If the closure object represents a generic lambda, find
  6848. // the corresponding specialization of the call operator.
  6849. if (ClosureClass->isGenericLambda()) {
  6850. assert(MD->isFunctionTemplateSpecialization() &&
  6851. "A generic lambda's static-invoker function must be a "
  6852. "template specialization");
  6853. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  6854. FunctionTemplateDecl *CallOpTemplate =
  6855. LambdaCallOp->getDescribedFunctionTemplate();
  6856. void *InsertPos = nullptr;
  6857. FunctionDecl *CorrespondingCallOpSpecialization =
  6858. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  6859. assert(CorrespondingCallOpSpecialization &&
  6860. "We must always have a function call operator specialization "
  6861. "that corresponds to our static invoker specialization");
  6862. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  6863. } else
  6864. FD = LambdaCallOp;
  6865. } else if (FD->isReplaceableGlobalAllocationFunction()) {
  6866. if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
  6867. FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
  6868. LValue Ptr;
  6869. if (!HandleOperatorNewCall(Info, E, Ptr))
  6870. return false;
  6871. Ptr.moveInto(Result);
  6872. return CallScope.destroy();
  6873. } else {
  6874. return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
  6875. }
  6876. }
  6877. } else
  6878. return Error(E);
  6879. // Evaluate the arguments now if we've not already done so.
  6880. if (!Call) {
  6881. Call = Info.CurrentCall->createCall(FD);
  6882. if (!EvaluateArgs(Args, Call, Info, FD))
  6883. return false;
  6884. }
  6885. SmallVector<QualType, 4> CovariantAdjustmentPath;
  6886. if (This) {
  6887. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  6888. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  6889. // Perform virtual dispatch, if necessary.
  6890. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  6891. CovariantAdjustmentPath);
  6892. if (!FD)
  6893. return false;
  6894. } else {
  6895. // Check that the 'this' pointer points to an object of the right type.
  6896. // FIXME: If this is an assignment operator call, we may need to change
  6897. // the active union member before we check this.
  6898. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
  6899. return false;
  6900. }
  6901. }
  6902. // Destructor calls are different enough that they have their own codepath.
  6903. if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
  6904. assert(This && "no 'this' pointer for destructor call");
  6905. return HandleDestruction(Info, E, *This,
  6906. Info.Ctx.getRecordType(DD->getParent())) &&
  6907. CallScope.destroy();
  6908. }
  6909. const FunctionDecl *Definition = nullptr;
  6910. Stmt *Body = FD->getBody(Definition);
  6911. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  6912. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
  6913. Body, Info, Result, ResultSlot))
  6914. return false;
  6915. if (!CovariantAdjustmentPath.empty() &&
  6916. !HandleCovariantReturnAdjustment(Info, E, Result,
  6917. CovariantAdjustmentPath))
  6918. return false;
  6919. return CallScope.destroy();
  6920. }
  6921. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6922. return StmtVisitorTy::Visit(E->getInitializer());
  6923. }
  6924. bool VisitInitListExpr(const InitListExpr *E) {
  6925. if (E->getNumInits() == 0)
  6926. return DerivedZeroInitialization(E);
  6927. if (E->getNumInits() == 1)
  6928. return StmtVisitorTy::Visit(E->getInit(0));
  6929. return Error(E);
  6930. }
  6931. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  6932. return DerivedZeroInitialization(E);
  6933. }
  6934. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  6935. return DerivedZeroInitialization(E);
  6936. }
  6937. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  6938. return DerivedZeroInitialization(E);
  6939. }
  6940. /// A member expression where the object is a prvalue is itself a prvalue.
  6941. bool VisitMemberExpr(const MemberExpr *E) {
  6942. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  6943. "missing temporary materialization conversion");
  6944. assert(!E->isArrow() && "missing call to bound member function?");
  6945. APValue Val;
  6946. if (!Evaluate(Val, Info, E->getBase()))
  6947. return false;
  6948. QualType BaseTy = E->getBase()->getType();
  6949. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  6950. if (!FD) return Error(E);
  6951. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  6952. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6953. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6954. // Note: there is no lvalue base here. But this case should only ever
  6955. // happen in C or in C++98, where we cannot be evaluating a constexpr
  6956. // constructor, which is the only case the base matters.
  6957. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  6958. SubobjectDesignator Designator(BaseTy);
  6959. Designator.addDeclUnchecked(FD);
  6960. APValue Result;
  6961. return extractSubobject(Info, E, Obj, Designator, Result) &&
  6962. DerivedSuccess(Result, E);
  6963. }
  6964. bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
  6965. APValue Val;
  6966. if (!Evaluate(Val, Info, E->getBase()))
  6967. return false;
  6968. if (Val.isVector()) {
  6969. SmallVector<uint32_t, 4> Indices;
  6970. E->getEncodedElementAccess(Indices);
  6971. if (Indices.size() == 1) {
  6972. // Return scalar.
  6973. return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
  6974. } else {
  6975. // Construct new APValue vector.
  6976. SmallVector<APValue, 4> Elts;
  6977. for (unsigned I = 0; I < Indices.size(); ++I) {
  6978. Elts.push_back(Val.getVectorElt(Indices[I]));
  6979. }
  6980. APValue VecResult(Elts.data(), Indices.size());
  6981. return DerivedSuccess(VecResult, E);
  6982. }
  6983. }
  6984. return false;
  6985. }
  6986. bool VisitCastExpr(const CastExpr *E) {
  6987. switch (E->getCastKind()) {
  6988. default:
  6989. break;
  6990. case CK_AtomicToNonAtomic: {
  6991. APValue AtomicVal;
  6992. // This does not need to be done in place even for class/array types:
  6993. // atomic-to-non-atomic conversion implies copying the object
  6994. // representation.
  6995. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  6996. return false;
  6997. return DerivedSuccess(AtomicVal, E);
  6998. }
  6999. case CK_NoOp:
  7000. case CK_UserDefinedConversion:
  7001. return StmtVisitorTy::Visit(E->getSubExpr());
  7002. case CK_LValueToRValue: {
  7003. LValue LVal;
  7004. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  7005. return false;
  7006. APValue RVal;
  7007. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  7008. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  7009. LVal, RVal))
  7010. return false;
  7011. return DerivedSuccess(RVal, E);
  7012. }
  7013. case CK_LValueToRValueBitCast: {
  7014. APValue DestValue, SourceValue;
  7015. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  7016. return false;
  7017. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  7018. return false;
  7019. return DerivedSuccess(DestValue, E);
  7020. }
  7021. case CK_AddressSpaceConversion: {
  7022. APValue Value;
  7023. if (!Evaluate(Value, Info, E->getSubExpr()))
  7024. return false;
  7025. return DerivedSuccess(Value, E);
  7026. }
  7027. }
  7028. return Error(E);
  7029. }
  7030. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  7031. return VisitUnaryPostIncDec(UO);
  7032. }
  7033. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  7034. return VisitUnaryPostIncDec(UO);
  7035. }
  7036. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  7037. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  7038. return Error(UO);
  7039. LValue LVal;
  7040. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  7041. return false;
  7042. APValue RVal;
  7043. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  7044. UO->isIncrementOp(), &RVal))
  7045. return false;
  7046. return DerivedSuccess(RVal, UO);
  7047. }
  7048. bool VisitStmtExpr(const StmtExpr *E) {
  7049. // We will have checked the full-expressions inside the statement expression
  7050. // when they were completed, and don't need to check them again now.
  7051. llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
  7052. false);
  7053. const CompoundStmt *CS = E->getSubStmt();
  7054. if (CS->body_empty())
  7055. return true;
  7056. BlockScopeRAII Scope(Info);
  7057. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  7058. BE = CS->body_end();
  7059. /**/; ++BI) {
  7060. if (BI + 1 == BE) {
  7061. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  7062. if (!FinalExpr) {
  7063. Info.FFDiag((*BI)->getBeginLoc(),
  7064. diag::note_constexpr_stmt_expr_unsupported);
  7065. return false;
  7066. }
  7067. return this->Visit(FinalExpr) && Scope.destroy();
  7068. }
  7069. APValue ReturnValue;
  7070. StmtResult Result = { ReturnValue, nullptr };
  7071. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  7072. if (ESR != ESR_Succeeded) {
  7073. // FIXME: If the statement-expression terminated due to 'return',
  7074. // 'break', or 'continue', it would be nice to propagate that to
  7075. // the outer statement evaluation rather than bailing out.
  7076. if (ESR != ESR_Failed)
  7077. Info.FFDiag((*BI)->getBeginLoc(),
  7078. diag::note_constexpr_stmt_expr_unsupported);
  7079. return false;
  7080. }
  7081. }
  7082. llvm_unreachable("Return from function from the loop above.");
  7083. }
  7084. /// Visit a value which is evaluated, but whose value is ignored.
  7085. void VisitIgnoredValue(const Expr *E) {
  7086. EvaluateIgnoredValue(Info, E);
  7087. }
  7088. /// Potentially visit a MemberExpr's base expression.
  7089. void VisitIgnoredBaseExpression(const Expr *E) {
  7090. // While MSVC doesn't evaluate the base expression, it does diagnose the
  7091. // presence of side-effecting behavior.
  7092. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  7093. return;
  7094. VisitIgnoredValue(E);
  7095. }
  7096. };
  7097. } // namespace
  7098. //===----------------------------------------------------------------------===//
  7099. // Common base class for lvalue and temporary evaluation.
  7100. //===----------------------------------------------------------------------===//
  7101. namespace {
  7102. template<class Derived>
  7103. class LValueExprEvaluatorBase
  7104. : public ExprEvaluatorBase<Derived> {
  7105. protected:
  7106. LValue &Result;
  7107. bool InvalidBaseOK;
  7108. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  7109. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  7110. bool Success(APValue::LValueBase B) {
  7111. Result.set(B);
  7112. return true;
  7113. }
  7114. bool evaluatePointer(const Expr *E, LValue &Result) {
  7115. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  7116. }
  7117. public:
  7118. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  7119. : ExprEvaluatorBaseTy(Info), Result(Result),
  7120. InvalidBaseOK(InvalidBaseOK) {}
  7121. bool Success(const APValue &V, const Expr *E) {
  7122. Result.setFrom(this->Info.Ctx, V);
  7123. return true;
  7124. }
  7125. bool VisitMemberExpr(const MemberExpr *E) {
  7126. // Handle non-static data members.
  7127. QualType BaseTy;
  7128. bool EvalOK;
  7129. if (E->isArrow()) {
  7130. EvalOK = evaluatePointer(E->getBase(), Result);
  7131. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  7132. } else if (E->getBase()->isPRValue()) {
  7133. assert(E->getBase()->getType()->isRecordType());
  7134. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  7135. BaseTy = E->getBase()->getType();
  7136. } else {
  7137. EvalOK = this->Visit(E->getBase());
  7138. BaseTy = E->getBase()->getType();
  7139. }
  7140. if (!EvalOK) {
  7141. if (!InvalidBaseOK)
  7142. return false;
  7143. Result.setInvalid(E);
  7144. return true;
  7145. }
  7146. const ValueDecl *MD = E->getMemberDecl();
  7147. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  7148. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  7149. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  7150. (void)BaseTy;
  7151. if (!HandleLValueMember(this->Info, E, Result, FD))
  7152. return false;
  7153. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  7154. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  7155. return false;
  7156. } else
  7157. return this->Error(E);
  7158. if (MD->getType()->isReferenceType()) {
  7159. APValue RefValue;
  7160. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  7161. RefValue))
  7162. return false;
  7163. return Success(RefValue, E);
  7164. }
  7165. return true;
  7166. }
  7167. bool VisitBinaryOperator(const BinaryOperator *E) {
  7168. switch (E->getOpcode()) {
  7169. default:
  7170. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7171. case BO_PtrMemD:
  7172. case BO_PtrMemI:
  7173. return HandleMemberPointerAccess(this->Info, E, Result);
  7174. }
  7175. }
  7176. bool VisitCastExpr(const CastExpr *E) {
  7177. switch (E->getCastKind()) {
  7178. default:
  7179. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7180. case CK_DerivedToBase:
  7181. case CK_UncheckedDerivedToBase:
  7182. if (!this->Visit(E->getSubExpr()))
  7183. return false;
  7184. // Now figure out the necessary offset to add to the base LV to get from
  7185. // the derived class to the base class.
  7186. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  7187. Result);
  7188. }
  7189. }
  7190. };
  7191. }
  7192. //===----------------------------------------------------------------------===//
  7193. // LValue Evaluation
  7194. //
  7195. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  7196. // function designators (in C), decl references to void objects (in C), and
  7197. // temporaries (if building with -Wno-address-of-temporary).
  7198. //
  7199. // LValue evaluation produces values comprising a base expression of one of the
  7200. // following types:
  7201. // - Declarations
  7202. // * VarDecl
  7203. // * FunctionDecl
  7204. // - Literals
  7205. // * CompoundLiteralExpr in C (and in global scope in C++)
  7206. // * StringLiteral
  7207. // * PredefinedExpr
  7208. // * ObjCStringLiteralExpr
  7209. // * ObjCEncodeExpr
  7210. // * AddrLabelExpr
  7211. // * BlockExpr
  7212. // * CallExpr for a MakeStringConstant builtin
  7213. // - typeid(T) expressions, as TypeInfoLValues
  7214. // - Locals and temporaries
  7215. // * MaterializeTemporaryExpr
  7216. // * Any Expr, with a CallIndex indicating the function in which the temporary
  7217. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  7218. // from the AST (FIXME).
  7219. // * A MaterializeTemporaryExpr that has static storage duration, with no
  7220. // CallIndex, for a lifetime-extended temporary.
  7221. // * The ConstantExpr that is currently being evaluated during evaluation of an
  7222. // immediate invocation.
  7223. // plus an offset in bytes.
  7224. //===----------------------------------------------------------------------===//
  7225. namespace {
  7226. class LValueExprEvaluator
  7227. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  7228. public:
  7229. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  7230. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  7231. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  7232. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  7233. bool VisitCallExpr(const CallExpr *E);
  7234. bool VisitDeclRefExpr(const DeclRefExpr *E);
  7235. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  7236. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  7237. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  7238. bool VisitMemberExpr(const MemberExpr *E);
  7239. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  7240. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  7241. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  7242. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  7243. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  7244. bool VisitUnaryDeref(const UnaryOperator *E);
  7245. bool VisitUnaryReal(const UnaryOperator *E);
  7246. bool VisitUnaryImag(const UnaryOperator *E);
  7247. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  7248. return VisitUnaryPreIncDec(UO);
  7249. }
  7250. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  7251. return VisitUnaryPreIncDec(UO);
  7252. }
  7253. bool VisitBinAssign(const BinaryOperator *BO);
  7254. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  7255. bool VisitCastExpr(const CastExpr *E) {
  7256. switch (E->getCastKind()) {
  7257. default:
  7258. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  7259. case CK_LValueBitCast:
  7260. this->CCEDiag(E, diag::note_constexpr_invalid_cast)
  7261. << 2 << Info.Ctx.getLangOpts().CPlusPlus;
  7262. if (!Visit(E->getSubExpr()))
  7263. return false;
  7264. Result.Designator.setInvalid();
  7265. return true;
  7266. case CK_BaseToDerived:
  7267. if (!Visit(E->getSubExpr()))
  7268. return false;
  7269. return HandleBaseToDerivedCast(Info, E, Result);
  7270. case CK_Dynamic:
  7271. if (!Visit(E->getSubExpr()))
  7272. return false;
  7273. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  7274. }
  7275. }
  7276. };
  7277. } // end anonymous namespace
  7278. /// Evaluate an expression as an lvalue. This can be legitimately called on
  7279. /// expressions which are not glvalues, in three cases:
  7280. /// * function designators in C, and
  7281. /// * "extern void" objects
  7282. /// * @selector() expressions in Objective-C
  7283. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  7284. bool InvalidBaseOK) {
  7285. assert(!E->isValueDependent());
  7286. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  7287. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
  7288. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  7289. }
  7290. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  7291. const NamedDecl *D = E->getDecl();
  7292. if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
  7293. UnnamedGlobalConstantDecl>(D))
  7294. return Success(cast<ValueDecl>(D));
  7295. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  7296. return VisitVarDecl(E, VD);
  7297. if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
  7298. return Visit(BD->getBinding());
  7299. return Error(E);
  7300. }
  7301. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  7302. // If we are within a lambda's call operator, check whether the 'VD' referred
  7303. // to within 'E' actually represents a lambda-capture that maps to a
  7304. // data-member/field within the closure object, and if so, evaluate to the
  7305. // field or what the field refers to.
  7306. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  7307. isa<DeclRefExpr>(E) &&
  7308. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  7309. // We don't always have a complete capture-map when checking or inferring if
  7310. // the function call operator meets the requirements of a constexpr function
  7311. // - but we don't need to evaluate the captures to determine constexprness
  7312. // (dcl.constexpr C++17).
  7313. if (Info.checkingPotentialConstantExpression())
  7314. return false;
  7315. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  7316. // Start with 'Result' referring to the complete closure object...
  7317. Result = *Info.CurrentCall->This;
  7318. // ... then update it to refer to the field of the closure object
  7319. // that represents the capture.
  7320. if (!HandleLValueMember(Info, E, Result, FD))
  7321. return false;
  7322. // And if the field is of reference type, update 'Result' to refer to what
  7323. // the field refers to.
  7324. if (FD->getType()->isReferenceType()) {
  7325. APValue RVal;
  7326. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  7327. RVal))
  7328. return false;
  7329. Result.setFrom(Info.Ctx, RVal);
  7330. }
  7331. return true;
  7332. }
  7333. }
  7334. CallStackFrame *Frame = nullptr;
  7335. unsigned Version = 0;
  7336. if (VD->hasLocalStorage()) {
  7337. // Only if a local variable was declared in the function currently being
  7338. // evaluated, do we expect to be able to find its value in the current
  7339. // frame. (Otherwise it was likely declared in an enclosing context and
  7340. // could either have a valid evaluatable value (for e.g. a constexpr
  7341. // variable) or be ill-formed (and trigger an appropriate evaluation
  7342. // diagnostic)).
  7343. CallStackFrame *CurrFrame = Info.CurrentCall;
  7344. if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
  7345. // Function parameters are stored in some caller's frame. (Usually the
  7346. // immediate caller, but for an inherited constructor they may be more
  7347. // distant.)
  7348. if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
  7349. if (CurrFrame->Arguments) {
  7350. VD = CurrFrame->Arguments.getOrigParam(PVD);
  7351. Frame =
  7352. Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
  7353. Version = CurrFrame->Arguments.Version;
  7354. }
  7355. } else {
  7356. Frame = CurrFrame;
  7357. Version = CurrFrame->getCurrentTemporaryVersion(VD);
  7358. }
  7359. }
  7360. }
  7361. if (!VD->getType()->isReferenceType()) {
  7362. if (Frame) {
  7363. Result.set({VD, Frame->Index, Version});
  7364. return true;
  7365. }
  7366. return Success(VD);
  7367. }
  7368. if (!Info.getLangOpts().CPlusPlus11) {
  7369. Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
  7370. << VD << VD->getType();
  7371. Info.Note(VD->getLocation(), diag::note_declared_at);
  7372. }
  7373. APValue *V;
  7374. if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
  7375. return false;
  7376. if (!V->hasValue()) {
  7377. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  7378. // adjust the diagnostic to say that.
  7379. if (!Info.checkingPotentialConstantExpression())
  7380. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  7381. return false;
  7382. }
  7383. return Success(*V, E);
  7384. }
  7385. bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7386. if (!IsConstantEvaluatedBuiltinCall(E))
  7387. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7388. switch (E->getBuiltinCallee()) {
  7389. default:
  7390. return false;
  7391. case Builtin::BIas_const:
  7392. case Builtin::BIforward:
  7393. case Builtin::BImove:
  7394. case Builtin::BImove_if_noexcept:
  7395. if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
  7396. return Visit(E->getArg(0));
  7397. break;
  7398. }
  7399. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7400. }
  7401. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  7402. const MaterializeTemporaryExpr *E) {
  7403. // Walk through the expression to find the materialized temporary itself.
  7404. SmallVector<const Expr *, 2> CommaLHSs;
  7405. SmallVector<SubobjectAdjustment, 2> Adjustments;
  7406. const Expr *Inner =
  7407. E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  7408. // If we passed any comma operators, evaluate their LHSs.
  7409. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  7410. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  7411. return false;
  7412. // A materialized temporary with static storage duration can appear within the
  7413. // result of a constant expression evaluation, so we need to preserve its
  7414. // value for use outside this evaluation.
  7415. APValue *Value;
  7416. if (E->getStorageDuration() == SD_Static) {
  7417. // FIXME: What about SD_Thread?
  7418. Value = E->getOrCreateValue(true);
  7419. *Value = APValue();
  7420. Result.set(E);
  7421. } else {
  7422. Value = &Info.CurrentCall->createTemporary(
  7423. E, E->getType(),
  7424. E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
  7425. : ScopeKind::Block,
  7426. Result);
  7427. }
  7428. QualType Type = Inner->getType();
  7429. // Materialize the temporary itself.
  7430. if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
  7431. *Value = APValue();
  7432. return false;
  7433. }
  7434. // Adjust our lvalue to refer to the desired subobject.
  7435. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  7436. --I;
  7437. switch (Adjustments[I].Kind) {
  7438. case SubobjectAdjustment::DerivedToBaseAdjustment:
  7439. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  7440. Type, Result))
  7441. return false;
  7442. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  7443. break;
  7444. case SubobjectAdjustment::FieldAdjustment:
  7445. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  7446. return false;
  7447. Type = Adjustments[I].Field->getType();
  7448. break;
  7449. case SubobjectAdjustment::MemberPointerAdjustment:
  7450. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  7451. Adjustments[I].Ptr.RHS))
  7452. return false;
  7453. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  7454. break;
  7455. }
  7456. }
  7457. return true;
  7458. }
  7459. bool
  7460. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  7461. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  7462. "lvalue compound literal in c++?");
  7463. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  7464. // only see this when folding in C, so there's no standard to follow here.
  7465. return Success(E);
  7466. }
  7467. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  7468. TypeInfoLValue TypeInfo;
  7469. if (!E->isPotentiallyEvaluated()) {
  7470. if (E->isTypeOperand())
  7471. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  7472. else
  7473. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  7474. } else {
  7475. if (!Info.Ctx.getLangOpts().CPlusPlus20) {
  7476. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  7477. << E->getExprOperand()->getType()
  7478. << E->getExprOperand()->getSourceRange();
  7479. }
  7480. if (!Visit(E->getExprOperand()))
  7481. return false;
  7482. std::optional<DynamicType> DynType =
  7483. ComputeDynamicType(Info, E, Result, AK_TypeId);
  7484. if (!DynType)
  7485. return false;
  7486. TypeInfo =
  7487. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  7488. }
  7489. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  7490. }
  7491. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  7492. return Success(E->getGuidDecl());
  7493. }
  7494. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  7495. // Handle static data members.
  7496. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  7497. VisitIgnoredBaseExpression(E->getBase());
  7498. return VisitVarDecl(E, VD);
  7499. }
  7500. // Handle static member functions.
  7501. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  7502. if (MD->isStatic()) {
  7503. VisitIgnoredBaseExpression(E->getBase());
  7504. return Success(MD);
  7505. }
  7506. }
  7507. // Handle non-static data members.
  7508. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  7509. }
  7510. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  7511. // FIXME: Deal with vectors as array subscript bases.
  7512. if (E->getBase()->getType()->isVectorType() ||
  7513. E->getBase()->getType()->isVLSTBuiltinType())
  7514. return Error(E);
  7515. APSInt Index;
  7516. bool Success = true;
  7517. // C++17's rules require us to evaluate the LHS first, regardless of which
  7518. // side is the base.
  7519. for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
  7520. if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
  7521. : !EvaluateInteger(SubExpr, Index, Info)) {
  7522. if (!Info.noteFailure())
  7523. return false;
  7524. Success = false;
  7525. }
  7526. }
  7527. return Success &&
  7528. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  7529. }
  7530. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  7531. return evaluatePointer(E->getSubExpr(), Result);
  7532. }
  7533. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  7534. if (!Visit(E->getSubExpr()))
  7535. return false;
  7536. // __real is a no-op on scalar lvalues.
  7537. if (E->getSubExpr()->getType()->isAnyComplexType())
  7538. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  7539. return true;
  7540. }
  7541. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7542. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  7543. "lvalue __imag__ on scalar?");
  7544. if (!Visit(E->getSubExpr()))
  7545. return false;
  7546. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  7547. return true;
  7548. }
  7549. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  7550. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  7551. return Error(UO);
  7552. if (!this->Visit(UO->getSubExpr()))
  7553. return false;
  7554. return handleIncDec(
  7555. this->Info, UO, Result, UO->getSubExpr()->getType(),
  7556. UO->isIncrementOp(), nullptr);
  7557. }
  7558. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  7559. const CompoundAssignOperator *CAO) {
  7560. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  7561. return Error(CAO);
  7562. bool Success = true;
  7563. // C++17 onwards require that we evaluate the RHS first.
  7564. APValue RHS;
  7565. if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
  7566. if (!Info.noteFailure())
  7567. return false;
  7568. Success = false;
  7569. }
  7570. // The overall lvalue result is the result of evaluating the LHS.
  7571. if (!this->Visit(CAO->getLHS()) || !Success)
  7572. return false;
  7573. return handleCompoundAssignment(
  7574. this->Info, CAO,
  7575. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  7576. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  7577. }
  7578. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  7579. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  7580. return Error(E);
  7581. bool Success = true;
  7582. // C++17 onwards require that we evaluate the RHS first.
  7583. APValue NewVal;
  7584. if (!Evaluate(NewVal, this->Info, E->getRHS())) {
  7585. if (!Info.noteFailure())
  7586. return false;
  7587. Success = false;
  7588. }
  7589. if (!this->Visit(E->getLHS()) || !Success)
  7590. return false;
  7591. if (Info.getLangOpts().CPlusPlus20 &&
  7592. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  7593. return false;
  7594. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  7595. NewVal);
  7596. }
  7597. //===----------------------------------------------------------------------===//
  7598. // Pointer Evaluation
  7599. //===----------------------------------------------------------------------===//
  7600. /// Attempts to compute the number of bytes available at the pointer
  7601. /// returned by a function with the alloc_size attribute. Returns true if we
  7602. /// were successful. Places an unsigned number into `Result`.
  7603. ///
  7604. /// This expects the given CallExpr to be a call to a function with an
  7605. /// alloc_size attribute.
  7606. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  7607. const CallExpr *Call,
  7608. llvm::APInt &Result) {
  7609. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  7610. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  7611. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  7612. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  7613. if (Call->getNumArgs() <= SizeArgNo)
  7614. return false;
  7615. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  7616. Expr::EvalResult ExprResult;
  7617. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  7618. return false;
  7619. Into = ExprResult.Val.getInt();
  7620. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  7621. return false;
  7622. Into = Into.zext(BitsInSizeT);
  7623. return true;
  7624. };
  7625. APSInt SizeOfElem;
  7626. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  7627. return false;
  7628. if (!AllocSize->getNumElemsParam().isValid()) {
  7629. Result = std::move(SizeOfElem);
  7630. return true;
  7631. }
  7632. APSInt NumberOfElems;
  7633. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  7634. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  7635. return false;
  7636. bool Overflow;
  7637. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  7638. if (Overflow)
  7639. return false;
  7640. Result = std::move(BytesAvailable);
  7641. return true;
  7642. }
  7643. /// Convenience function. LVal's base must be a call to an alloc_size
  7644. /// function.
  7645. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  7646. const LValue &LVal,
  7647. llvm::APInt &Result) {
  7648. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7649. "Can't get the size of a non alloc_size function");
  7650. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  7651. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  7652. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  7653. }
  7654. /// Attempts to evaluate the given LValueBase as the result of a call to
  7655. /// a function with the alloc_size attribute. If it was possible to do so, this
  7656. /// function will return true, make Result's Base point to said function call,
  7657. /// and mark Result's Base as invalid.
  7658. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  7659. LValue &Result) {
  7660. if (Base.isNull())
  7661. return false;
  7662. // Because we do no form of static analysis, we only support const variables.
  7663. //
  7664. // Additionally, we can't support parameters, nor can we support static
  7665. // variables (in the latter case, use-before-assign isn't UB; in the former,
  7666. // we have no clue what they'll be assigned to).
  7667. const auto *VD =
  7668. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  7669. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  7670. return false;
  7671. const Expr *Init = VD->getAnyInitializer();
  7672. if (!Init || Init->getType().isNull())
  7673. return false;
  7674. const Expr *E = Init->IgnoreParens();
  7675. if (!tryUnwrapAllocSizeCall(E))
  7676. return false;
  7677. // Store E instead of E unwrapped so that the type of the LValue's base is
  7678. // what the user wanted.
  7679. Result.setInvalid(E);
  7680. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  7681. Result.addUnsizedArray(Info, E, Pointee);
  7682. return true;
  7683. }
  7684. namespace {
  7685. class PointerExprEvaluator
  7686. : public ExprEvaluatorBase<PointerExprEvaluator> {
  7687. LValue &Result;
  7688. bool InvalidBaseOK;
  7689. bool Success(const Expr *E) {
  7690. Result.set(E);
  7691. return true;
  7692. }
  7693. bool evaluateLValue(const Expr *E, LValue &Result) {
  7694. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  7695. }
  7696. bool evaluatePointer(const Expr *E, LValue &Result) {
  7697. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  7698. }
  7699. bool visitNonBuiltinCallExpr(const CallExpr *E);
  7700. public:
  7701. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  7702. : ExprEvaluatorBaseTy(info), Result(Result),
  7703. InvalidBaseOK(InvalidBaseOK) {}
  7704. bool Success(const APValue &V, const Expr *E) {
  7705. Result.setFrom(Info.Ctx, V);
  7706. return true;
  7707. }
  7708. bool ZeroInitialization(const Expr *E) {
  7709. Result.setNull(Info.Ctx, E->getType());
  7710. return true;
  7711. }
  7712. bool VisitBinaryOperator(const BinaryOperator *E);
  7713. bool VisitCastExpr(const CastExpr* E);
  7714. bool VisitUnaryAddrOf(const UnaryOperator *E);
  7715. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  7716. { return Success(E); }
  7717. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  7718. if (E->isExpressibleAsConstantInitializer())
  7719. return Success(E);
  7720. if (Info.noteFailure())
  7721. EvaluateIgnoredValue(Info, E->getSubExpr());
  7722. return Error(E);
  7723. }
  7724. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  7725. { return Success(E); }
  7726. bool VisitCallExpr(const CallExpr *E);
  7727. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  7728. bool VisitBlockExpr(const BlockExpr *E) {
  7729. if (!E->getBlockDecl()->hasCaptures())
  7730. return Success(E);
  7731. return Error(E);
  7732. }
  7733. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  7734. // Can't look at 'this' when checking a potential constant expression.
  7735. if (Info.checkingPotentialConstantExpression())
  7736. return false;
  7737. if (!Info.CurrentCall->This) {
  7738. if (Info.getLangOpts().CPlusPlus11)
  7739. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  7740. else
  7741. Info.FFDiag(E);
  7742. return false;
  7743. }
  7744. Result = *Info.CurrentCall->This;
  7745. // If we are inside a lambda's call operator, the 'this' expression refers
  7746. // to the enclosing '*this' object (either by value or reference) which is
  7747. // either copied into the closure object's field that represents the '*this'
  7748. // or refers to '*this'.
  7749. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  7750. // Ensure we actually have captured 'this'. (an error will have
  7751. // been previously reported if not).
  7752. if (!Info.CurrentCall->LambdaThisCaptureField)
  7753. return false;
  7754. // Update 'Result' to refer to the data member/field of the closure object
  7755. // that represents the '*this' capture.
  7756. if (!HandleLValueMember(Info, E, Result,
  7757. Info.CurrentCall->LambdaThisCaptureField))
  7758. return false;
  7759. // If we captured '*this' by reference, replace the field with its referent.
  7760. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  7761. ->isPointerType()) {
  7762. APValue RVal;
  7763. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  7764. RVal))
  7765. return false;
  7766. Result.setFrom(Info.Ctx, RVal);
  7767. }
  7768. }
  7769. return true;
  7770. }
  7771. bool VisitCXXNewExpr(const CXXNewExpr *E);
  7772. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  7773. assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
  7774. APValue LValResult = E->EvaluateInContext(
  7775. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  7776. Result.setFrom(Info.Ctx, LValResult);
  7777. return true;
  7778. }
  7779. bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
  7780. std::string ResultStr = E->ComputeName(Info.Ctx);
  7781. QualType CharTy = Info.Ctx.CharTy.withConst();
  7782. APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
  7783. ResultStr.size() + 1);
  7784. QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
  7785. ArrayType::Normal, 0);
  7786. StringLiteral *SL =
  7787. StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
  7788. /*Pascal*/ false, ArrayTy, E->getLocation());
  7789. evaluateLValue(SL, Result);
  7790. Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
  7791. return true;
  7792. }
  7793. // FIXME: Missing: @protocol, @selector
  7794. };
  7795. } // end anonymous namespace
  7796. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  7797. bool InvalidBaseOK) {
  7798. assert(!E->isValueDependent());
  7799. assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
  7800. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  7801. }
  7802. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  7803. if (E->getOpcode() != BO_Add &&
  7804. E->getOpcode() != BO_Sub)
  7805. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7806. const Expr *PExp = E->getLHS();
  7807. const Expr *IExp = E->getRHS();
  7808. if (IExp->getType()->isPointerType())
  7809. std::swap(PExp, IExp);
  7810. bool EvalPtrOK = evaluatePointer(PExp, Result);
  7811. if (!EvalPtrOK && !Info.noteFailure())
  7812. return false;
  7813. llvm::APSInt Offset;
  7814. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  7815. return false;
  7816. if (E->getOpcode() == BO_Sub)
  7817. negateAsSigned(Offset);
  7818. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  7819. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  7820. }
  7821. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  7822. return evaluateLValue(E->getSubExpr(), Result);
  7823. }
  7824. // Is the provided decl 'std::source_location::current'?
  7825. static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
  7826. if (!FD)
  7827. return false;
  7828. const IdentifierInfo *FnII = FD->getIdentifier();
  7829. if (!FnII || !FnII->isStr("current"))
  7830. return false;
  7831. const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
  7832. if (!RD)
  7833. return false;
  7834. const IdentifierInfo *ClassII = RD->getIdentifier();
  7835. return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
  7836. }
  7837. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7838. const Expr *SubExpr = E->getSubExpr();
  7839. switch (E->getCastKind()) {
  7840. default:
  7841. break;
  7842. case CK_BitCast:
  7843. case CK_CPointerToObjCPointerCast:
  7844. case CK_BlockPointerToObjCPointerCast:
  7845. case CK_AnyPointerToBlockPointerCast:
  7846. case CK_AddressSpaceConversion:
  7847. if (!Visit(SubExpr))
  7848. return false;
  7849. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  7850. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  7851. // also static_casts, but we disallow them as a resolution to DR1312.
  7852. if (!E->getType()->isVoidPointerType()) {
  7853. // In some circumstances, we permit casting from void* to cv1 T*, when the
  7854. // actual pointee object is actually a cv2 T.
  7855. bool VoidPtrCastMaybeOK =
  7856. !Result.InvalidBase && !Result.Designator.Invalid &&
  7857. !Result.IsNullPtr &&
  7858. Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
  7859. E->getType()->getPointeeType());
  7860. // 1. We'll allow it in std::allocator::allocate, and anything which that
  7861. // calls.
  7862. // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
  7863. // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
  7864. // We'll allow it in the body of std::source_location::current. GCC's
  7865. // implementation had a parameter of type `void*`, and casts from
  7866. // that back to `const __impl*` in its body.
  7867. if (VoidPtrCastMaybeOK &&
  7868. (Info.getStdAllocatorCaller("allocate") ||
  7869. IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
  7870. // Permitted.
  7871. } else {
  7872. Result.Designator.setInvalid();
  7873. if (SubExpr->getType()->isVoidPointerType())
  7874. CCEDiag(E, diag::note_constexpr_invalid_cast)
  7875. << 3 << SubExpr->getType();
  7876. else
  7877. CCEDiag(E, diag::note_constexpr_invalid_cast)
  7878. << 2 << Info.Ctx.getLangOpts().CPlusPlus;
  7879. }
  7880. }
  7881. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  7882. ZeroInitialization(E);
  7883. return true;
  7884. case CK_DerivedToBase:
  7885. case CK_UncheckedDerivedToBase:
  7886. if (!evaluatePointer(E->getSubExpr(), Result))
  7887. return false;
  7888. if (!Result.Base && Result.Offset.isZero())
  7889. return true;
  7890. // Now figure out the necessary offset to add to the base LV to get from
  7891. // the derived class to the base class.
  7892. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  7893. castAs<PointerType>()->getPointeeType(),
  7894. Result);
  7895. case CK_BaseToDerived:
  7896. if (!Visit(E->getSubExpr()))
  7897. return false;
  7898. if (!Result.Base && Result.Offset.isZero())
  7899. return true;
  7900. return HandleBaseToDerivedCast(Info, E, Result);
  7901. case CK_Dynamic:
  7902. if (!Visit(E->getSubExpr()))
  7903. return false;
  7904. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  7905. case CK_NullToPointer:
  7906. VisitIgnoredValue(E->getSubExpr());
  7907. return ZeroInitialization(E);
  7908. case CK_IntegralToPointer: {
  7909. CCEDiag(E, diag::note_constexpr_invalid_cast)
  7910. << 2 << Info.Ctx.getLangOpts().CPlusPlus;
  7911. APValue Value;
  7912. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  7913. break;
  7914. if (Value.isInt()) {
  7915. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  7916. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  7917. Result.Base = (Expr*)nullptr;
  7918. Result.InvalidBase = false;
  7919. Result.Offset = CharUnits::fromQuantity(N);
  7920. Result.Designator.setInvalid();
  7921. Result.IsNullPtr = false;
  7922. return true;
  7923. } else {
  7924. // Cast is of an lvalue, no need to change value.
  7925. Result.setFrom(Info.Ctx, Value);
  7926. return true;
  7927. }
  7928. }
  7929. case CK_ArrayToPointerDecay: {
  7930. if (SubExpr->isGLValue()) {
  7931. if (!evaluateLValue(SubExpr, Result))
  7932. return false;
  7933. } else {
  7934. APValue &Value = Info.CurrentCall->createTemporary(
  7935. SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
  7936. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  7937. return false;
  7938. }
  7939. // The result is a pointer to the first element of the array.
  7940. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  7941. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  7942. Result.addArray(Info, E, CAT);
  7943. else
  7944. Result.addUnsizedArray(Info, E, AT->getElementType());
  7945. return true;
  7946. }
  7947. case CK_FunctionToPointerDecay:
  7948. return evaluateLValue(SubExpr, Result);
  7949. case CK_LValueToRValue: {
  7950. LValue LVal;
  7951. if (!evaluateLValue(E->getSubExpr(), LVal))
  7952. return false;
  7953. APValue RVal;
  7954. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  7955. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  7956. LVal, RVal))
  7957. return InvalidBaseOK &&
  7958. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  7959. return Success(RVal, E);
  7960. }
  7961. }
  7962. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7963. }
  7964. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  7965. UnaryExprOrTypeTrait ExprKind) {
  7966. // C++ [expr.alignof]p3:
  7967. // When alignof is applied to a reference type, the result is the
  7968. // alignment of the referenced type.
  7969. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  7970. T = Ref->getPointeeType();
  7971. if (T.getQualifiers().hasUnaligned())
  7972. return CharUnits::One();
  7973. const bool AlignOfReturnsPreferred =
  7974. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  7975. // __alignof is defined to return the preferred alignment.
  7976. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  7977. // as well.
  7978. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  7979. return Info.Ctx.toCharUnitsFromBits(
  7980. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  7981. // alignof and _Alignof are defined to return the ABI alignment.
  7982. else if (ExprKind == UETT_AlignOf)
  7983. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  7984. else
  7985. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  7986. }
  7987. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  7988. UnaryExprOrTypeTrait ExprKind) {
  7989. E = E->IgnoreParens();
  7990. // The kinds of expressions that we have special-case logic here for
  7991. // should be kept up to date with the special checks for those
  7992. // expressions in Sema.
  7993. // alignof decl is always accepted, even if it doesn't make sense: we default
  7994. // to 1 in those cases.
  7995. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  7996. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  7997. /*RefAsPointee*/true);
  7998. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  7999. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  8000. /*RefAsPointee*/true);
  8001. return GetAlignOfType(Info, E->getType(), ExprKind);
  8002. }
  8003. static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
  8004. if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
  8005. return Info.Ctx.getDeclAlign(VD);
  8006. if (const auto *E = Value.Base.dyn_cast<const Expr *>())
  8007. return GetAlignOfExpr(Info, E, UETT_AlignOf);
  8008. return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
  8009. }
  8010. /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
  8011. /// __builtin_is_aligned and __builtin_assume_aligned.
  8012. static bool getAlignmentArgument(const Expr *E, QualType ForType,
  8013. EvalInfo &Info, APSInt &Alignment) {
  8014. if (!EvaluateInteger(E, Alignment, Info))
  8015. return false;
  8016. if (Alignment < 0 || !Alignment.isPowerOf2()) {
  8017. Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
  8018. return false;
  8019. }
  8020. unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
  8021. APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
  8022. if (APSInt::compareValues(Alignment, MaxValue) > 0) {
  8023. Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
  8024. << MaxValue << ForType << Alignment;
  8025. return false;
  8026. }
  8027. // Ensure both alignment and source value have the same bit width so that we
  8028. // don't assert when computing the resulting value.
  8029. APSInt ExtAlignment =
  8030. APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
  8031. assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
  8032. "Alignment should not be changed by ext/trunc");
  8033. Alignment = ExtAlignment;
  8034. assert(Alignment.getBitWidth() == SrcWidth);
  8035. return true;
  8036. }
  8037. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  8038. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  8039. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  8040. return true;
  8041. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  8042. return false;
  8043. Result.setInvalid(E);
  8044. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  8045. Result.addUnsizedArray(Info, E, PointeeTy);
  8046. return true;
  8047. }
  8048. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8049. if (!IsConstantEvaluatedBuiltinCall(E))
  8050. return visitNonBuiltinCallExpr(E);
  8051. return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
  8052. }
  8053. // Determine if T is a character type for which we guarantee that
  8054. // sizeof(T) == 1.
  8055. static bool isOneByteCharacterType(QualType T) {
  8056. return T->isCharType() || T->isChar8Type();
  8057. }
  8058. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  8059. unsigned BuiltinOp) {
  8060. if (IsNoOpCall(E))
  8061. return Success(E);
  8062. switch (BuiltinOp) {
  8063. case Builtin::BIaddressof:
  8064. case Builtin::BI__addressof:
  8065. case Builtin::BI__builtin_addressof:
  8066. return evaluateLValue(E->getArg(0), Result);
  8067. case Builtin::BI__builtin_assume_aligned: {
  8068. // We need to be very careful here because: if the pointer does not have the
  8069. // asserted alignment, then the behavior is undefined, and undefined
  8070. // behavior is non-constant.
  8071. if (!evaluatePointer(E->getArg(0), Result))
  8072. return false;
  8073. LValue OffsetResult(Result);
  8074. APSInt Alignment;
  8075. if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
  8076. Alignment))
  8077. return false;
  8078. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  8079. if (E->getNumArgs() > 2) {
  8080. APSInt Offset;
  8081. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  8082. return false;
  8083. int64_t AdditionalOffset = -Offset.getZExtValue();
  8084. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  8085. }
  8086. // If there is a base object, then it must have the correct alignment.
  8087. if (OffsetResult.Base) {
  8088. CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
  8089. if (BaseAlignment < Align) {
  8090. Result.Designator.setInvalid();
  8091. // FIXME: Add support to Diagnostic for long / long long.
  8092. CCEDiag(E->getArg(0),
  8093. diag::note_constexpr_baa_insufficient_alignment) << 0
  8094. << (unsigned)BaseAlignment.getQuantity()
  8095. << (unsigned)Align.getQuantity();
  8096. return false;
  8097. }
  8098. }
  8099. // The offset must also have the correct alignment.
  8100. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  8101. Result.Designator.setInvalid();
  8102. (OffsetResult.Base
  8103. ? CCEDiag(E->getArg(0),
  8104. diag::note_constexpr_baa_insufficient_alignment) << 1
  8105. : CCEDiag(E->getArg(0),
  8106. diag::note_constexpr_baa_value_insufficient_alignment))
  8107. << (int)OffsetResult.Offset.getQuantity()
  8108. << (unsigned)Align.getQuantity();
  8109. return false;
  8110. }
  8111. return true;
  8112. }
  8113. case Builtin::BI__builtin_align_up:
  8114. case Builtin::BI__builtin_align_down: {
  8115. if (!evaluatePointer(E->getArg(0), Result))
  8116. return false;
  8117. APSInt Alignment;
  8118. if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
  8119. Alignment))
  8120. return false;
  8121. CharUnits BaseAlignment = getBaseAlignment(Info, Result);
  8122. CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
  8123. // For align_up/align_down, we can return the same value if the alignment
  8124. // is known to be greater or equal to the requested value.
  8125. if (PtrAlign.getQuantity() >= Alignment)
  8126. return true;
  8127. // The alignment could be greater than the minimum at run-time, so we cannot
  8128. // infer much about the resulting pointer value. One case is possible:
  8129. // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
  8130. // can infer the correct index if the requested alignment is smaller than
  8131. // the base alignment so we can perform the computation on the offset.
  8132. if (BaseAlignment.getQuantity() >= Alignment) {
  8133. assert(Alignment.getBitWidth() <= 64 &&
  8134. "Cannot handle > 64-bit address-space");
  8135. uint64_t Alignment64 = Alignment.getZExtValue();
  8136. CharUnits NewOffset = CharUnits::fromQuantity(
  8137. BuiltinOp == Builtin::BI__builtin_align_down
  8138. ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
  8139. : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
  8140. Result.adjustOffset(NewOffset - Result.Offset);
  8141. // TODO: diagnose out-of-bounds values/only allow for arrays?
  8142. return true;
  8143. }
  8144. // Otherwise, we cannot constant-evaluate the result.
  8145. Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
  8146. << Alignment;
  8147. return false;
  8148. }
  8149. case Builtin::BI__builtin_operator_new:
  8150. return HandleOperatorNewCall(Info, E, Result);
  8151. case Builtin::BI__builtin_launder:
  8152. return evaluatePointer(E->getArg(0), Result);
  8153. case Builtin::BIstrchr:
  8154. case Builtin::BIwcschr:
  8155. case Builtin::BImemchr:
  8156. case Builtin::BIwmemchr:
  8157. if (Info.getLangOpts().CPlusPlus11)
  8158. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8159. << /*isConstexpr*/ 0 << /*isConstructor*/ 0
  8160. << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
  8161. else
  8162. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8163. [[fallthrough]];
  8164. case Builtin::BI__builtin_strchr:
  8165. case Builtin::BI__builtin_wcschr:
  8166. case Builtin::BI__builtin_memchr:
  8167. case Builtin::BI__builtin_char_memchr:
  8168. case Builtin::BI__builtin_wmemchr: {
  8169. if (!Visit(E->getArg(0)))
  8170. return false;
  8171. APSInt Desired;
  8172. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  8173. return false;
  8174. uint64_t MaxLength = uint64_t(-1);
  8175. if (BuiltinOp != Builtin::BIstrchr &&
  8176. BuiltinOp != Builtin::BIwcschr &&
  8177. BuiltinOp != Builtin::BI__builtin_strchr &&
  8178. BuiltinOp != Builtin::BI__builtin_wcschr) {
  8179. APSInt N;
  8180. if (!EvaluateInteger(E->getArg(2), N, Info))
  8181. return false;
  8182. MaxLength = N.getExtValue();
  8183. }
  8184. // We cannot find the value if there are no candidates to match against.
  8185. if (MaxLength == 0u)
  8186. return ZeroInitialization(E);
  8187. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  8188. Result.Designator.Invalid)
  8189. return false;
  8190. QualType CharTy = Result.Designator.getType(Info.Ctx);
  8191. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  8192. BuiltinOp == Builtin::BI__builtin_memchr;
  8193. assert(IsRawByte ||
  8194. Info.Ctx.hasSameUnqualifiedType(
  8195. CharTy, E->getArg(0)->getType()->getPointeeType()));
  8196. // Pointers to const void may point to objects of incomplete type.
  8197. if (IsRawByte && CharTy->isIncompleteType()) {
  8198. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  8199. return false;
  8200. }
  8201. // Give up on byte-oriented matching against multibyte elements.
  8202. // FIXME: We can compare the bytes in the correct order.
  8203. if (IsRawByte && !isOneByteCharacterType(CharTy)) {
  8204. Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
  8205. << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
  8206. << CharTy;
  8207. return false;
  8208. }
  8209. // Figure out what value we're actually looking for (after converting to
  8210. // the corresponding unsigned type if necessary).
  8211. uint64_t DesiredVal;
  8212. bool StopAtNull = false;
  8213. switch (BuiltinOp) {
  8214. case Builtin::BIstrchr:
  8215. case Builtin::BI__builtin_strchr:
  8216. // strchr compares directly to the passed integer, and therefore
  8217. // always fails if given an int that is not a char.
  8218. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  8219. E->getArg(1)->getType(),
  8220. Desired),
  8221. Desired))
  8222. return ZeroInitialization(E);
  8223. StopAtNull = true;
  8224. [[fallthrough]];
  8225. case Builtin::BImemchr:
  8226. case Builtin::BI__builtin_memchr:
  8227. case Builtin::BI__builtin_char_memchr:
  8228. // memchr compares by converting both sides to unsigned char. That's also
  8229. // correct for strchr if we get this far (to cope with plain char being
  8230. // unsigned in the strchr case).
  8231. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  8232. break;
  8233. case Builtin::BIwcschr:
  8234. case Builtin::BI__builtin_wcschr:
  8235. StopAtNull = true;
  8236. [[fallthrough]];
  8237. case Builtin::BIwmemchr:
  8238. case Builtin::BI__builtin_wmemchr:
  8239. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  8240. DesiredVal = Desired.getZExtValue();
  8241. break;
  8242. }
  8243. for (; MaxLength; --MaxLength) {
  8244. APValue Char;
  8245. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  8246. !Char.isInt())
  8247. return false;
  8248. if (Char.getInt().getZExtValue() == DesiredVal)
  8249. return true;
  8250. if (StopAtNull && !Char.getInt())
  8251. break;
  8252. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  8253. return false;
  8254. }
  8255. // Not found: return nullptr.
  8256. return ZeroInitialization(E);
  8257. }
  8258. case Builtin::BImemcpy:
  8259. case Builtin::BImemmove:
  8260. case Builtin::BIwmemcpy:
  8261. case Builtin::BIwmemmove:
  8262. if (Info.getLangOpts().CPlusPlus11)
  8263. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8264. << /*isConstexpr*/ 0 << /*isConstructor*/ 0
  8265. << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
  8266. else
  8267. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8268. [[fallthrough]];
  8269. case Builtin::BI__builtin_memcpy:
  8270. case Builtin::BI__builtin_memmove:
  8271. case Builtin::BI__builtin_wmemcpy:
  8272. case Builtin::BI__builtin_wmemmove: {
  8273. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  8274. BuiltinOp == Builtin::BIwmemmove ||
  8275. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  8276. BuiltinOp == Builtin::BI__builtin_wmemmove;
  8277. bool Move = BuiltinOp == Builtin::BImemmove ||
  8278. BuiltinOp == Builtin::BIwmemmove ||
  8279. BuiltinOp == Builtin::BI__builtin_memmove ||
  8280. BuiltinOp == Builtin::BI__builtin_wmemmove;
  8281. // The result of mem* is the first argument.
  8282. if (!Visit(E->getArg(0)))
  8283. return false;
  8284. LValue Dest = Result;
  8285. LValue Src;
  8286. if (!EvaluatePointer(E->getArg(1), Src, Info))
  8287. return false;
  8288. APSInt N;
  8289. if (!EvaluateInteger(E->getArg(2), N, Info))
  8290. return false;
  8291. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  8292. // If the size is zero, we treat this as always being a valid no-op.
  8293. // (Even if one of the src and dest pointers is null.)
  8294. if (!N)
  8295. return true;
  8296. // Otherwise, if either of the operands is null, we can't proceed. Don't
  8297. // try to determine the type of the copied objects, because there aren't
  8298. // any.
  8299. if (!Src.Base || !Dest.Base) {
  8300. APValue Val;
  8301. (!Src.Base ? Src : Dest).moveInto(Val);
  8302. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  8303. << Move << WChar << !!Src.Base
  8304. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  8305. return false;
  8306. }
  8307. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  8308. return false;
  8309. // We require that Src and Dest are both pointers to arrays of
  8310. // trivially-copyable type. (For the wide version, the designator will be
  8311. // invalid if the designated object is not a wchar_t.)
  8312. QualType T = Dest.Designator.getType(Info.Ctx);
  8313. QualType SrcT = Src.Designator.getType(Info.Ctx);
  8314. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  8315. // FIXME: Consider using our bit_cast implementation to support this.
  8316. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  8317. return false;
  8318. }
  8319. if (T->isIncompleteType()) {
  8320. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  8321. return false;
  8322. }
  8323. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  8324. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  8325. return false;
  8326. }
  8327. // Figure out how many T's we're copying.
  8328. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  8329. if (!WChar) {
  8330. uint64_t Remainder;
  8331. llvm::APInt OrigN = N;
  8332. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  8333. if (Remainder) {
  8334. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  8335. << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
  8336. << (unsigned)TSize;
  8337. return false;
  8338. }
  8339. }
  8340. // Check that the copying will remain within the arrays, just so that we
  8341. // can give a more meaningful diagnostic. This implicitly also checks that
  8342. // N fits into 64 bits.
  8343. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  8344. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  8345. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  8346. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  8347. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  8348. << toString(N, 10, /*Signed*/false);
  8349. return false;
  8350. }
  8351. uint64_t NElems = N.getZExtValue();
  8352. uint64_t NBytes = NElems * TSize;
  8353. // Check for overlap.
  8354. int Direction = 1;
  8355. if (HasSameBase(Src, Dest)) {
  8356. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  8357. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  8358. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  8359. // Dest is inside the source region.
  8360. if (!Move) {
  8361. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  8362. return false;
  8363. }
  8364. // For memmove and friends, copy backwards.
  8365. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  8366. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  8367. return false;
  8368. Direction = -1;
  8369. } else if (!Move && SrcOffset >= DestOffset &&
  8370. SrcOffset - DestOffset < NBytes) {
  8371. // Src is inside the destination region for memcpy: invalid.
  8372. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  8373. return false;
  8374. }
  8375. }
  8376. while (true) {
  8377. APValue Val;
  8378. // FIXME: Set WantObjectRepresentation to true if we're copying a
  8379. // char-like type?
  8380. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  8381. !handleAssignment(Info, E, Dest, T, Val))
  8382. return false;
  8383. // Do not iterate past the last element; if we're copying backwards, that
  8384. // might take us off the start of the array.
  8385. if (--NElems == 0)
  8386. return true;
  8387. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  8388. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  8389. return false;
  8390. }
  8391. }
  8392. default:
  8393. return false;
  8394. }
  8395. }
  8396. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  8397. APValue &Result, const InitListExpr *ILE,
  8398. QualType AllocType);
  8399. static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
  8400. APValue &Result,
  8401. const CXXConstructExpr *CCE,
  8402. QualType AllocType);
  8403. bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
  8404. if (!Info.getLangOpts().CPlusPlus20)
  8405. Info.CCEDiag(E, diag::note_constexpr_new);
  8406. // We cannot speculatively evaluate a delete expression.
  8407. if (Info.SpeculativeEvaluationDepth)
  8408. return false;
  8409. FunctionDecl *OperatorNew = E->getOperatorNew();
  8410. bool IsNothrow = false;
  8411. bool IsPlacement = false;
  8412. if (OperatorNew->isReservedGlobalPlacementOperator() &&
  8413. Info.CurrentCall->isStdFunction() && !E->isArray()) {
  8414. // FIXME Support array placement new.
  8415. assert(E->getNumPlacementArgs() == 1);
  8416. if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
  8417. return false;
  8418. if (Result.Designator.Invalid)
  8419. return false;
  8420. IsPlacement = true;
  8421. } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
  8422. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  8423. << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
  8424. return false;
  8425. } else if (E->getNumPlacementArgs()) {
  8426. // The only new-placement list we support is of the form (std::nothrow).
  8427. //
  8428. // FIXME: There is no restriction on this, but it's not clear that any
  8429. // other form makes any sense. We get here for cases such as:
  8430. //
  8431. // new (std::align_val_t{N}) X(int)
  8432. //
  8433. // (which should presumably be valid only if N is a multiple of
  8434. // alignof(int), and in any case can't be deallocated unless N is
  8435. // alignof(X) and X has new-extended alignment).
  8436. if (E->getNumPlacementArgs() != 1 ||
  8437. !E->getPlacementArg(0)->getType()->isNothrowT())
  8438. return Error(E, diag::note_constexpr_new_placement);
  8439. LValue Nothrow;
  8440. if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
  8441. return false;
  8442. IsNothrow = true;
  8443. }
  8444. const Expr *Init = E->getInitializer();
  8445. const InitListExpr *ResizedArrayILE = nullptr;
  8446. const CXXConstructExpr *ResizedArrayCCE = nullptr;
  8447. bool ValueInit = false;
  8448. QualType AllocType = E->getAllocatedType();
  8449. if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
  8450. const Expr *Stripped = *ArraySize;
  8451. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
  8452. Stripped = ICE->getSubExpr())
  8453. if (ICE->getCastKind() != CK_NoOp &&
  8454. ICE->getCastKind() != CK_IntegralCast)
  8455. break;
  8456. llvm::APSInt ArrayBound;
  8457. if (!EvaluateInteger(Stripped, ArrayBound, Info))
  8458. return false;
  8459. // C++ [expr.new]p9:
  8460. // The expression is erroneous if:
  8461. // -- [...] its value before converting to size_t [or] applying the
  8462. // second standard conversion sequence is less than zero
  8463. if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
  8464. if (IsNothrow)
  8465. return ZeroInitialization(E);
  8466. Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
  8467. << ArrayBound << (*ArraySize)->getSourceRange();
  8468. return false;
  8469. }
  8470. // -- its value is such that the size of the allocated object would
  8471. // exceed the implementation-defined limit
  8472. if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
  8473. ArrayBound) >
  8474. ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  8475. if (IsNothrow)
  8476. return ZeroInitialization(E);
  8477. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
  8478. << ArrayBound << (*ArraySize)->getSourceRange();
  8479. return false;
  8480. }
  8481. // -- the new-initializer is a braced-init-list and the number of
  8482. // array elements for which initializers are provided [...]
  8483. // exceeds the number of elements to initialize
  8484. if (!Init) {
  8485. // No initialization is performed.
  8486. } else if (isa<CXXScalarValueInitExpr>(Init) ||
  8487. isa<ImplicitValueInitExpr>(Init)) {
  8488. ValueInit = true;
  8489. } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
  8490. ResizedArrayCCE = CCE;
  8491. } else {
  8492. auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
  8493. assert(CAT && "unexpected type for array initializer");
  8494. unsigned Bits =
  8495. std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
  8496. llvm::APInt InitBound = CAT->getSize().zext(Bits);
  8497. llvm::APInt AllocBound = ArrayBound.zext(Bits);
  8498. if (InitBound.ugt(AllocBound)) {
  8499. if (IsNothrow)
  8500. return ZeroInitialization(E);
  8501. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
  8502. << toString(AllocBound, 10, /*Signed=*/false)
  8503. << toString(InitBound, 10, /*Signed=*/false)
  8504. << (*ArraySize)->getSourceRange();
  8505. return false;
  8506. }
  8507. // If the sizes differ, we must have an initializer list, and we need
  8508. // special handling for this case when we initialize.
  8509. if (InitBound != AllocBound)
  8510. ResizedArrayILE = cast<InitListExpr>(Init);
  8511. }
  8512. AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
  8513. ArrayType::Normal, 0);
  8514. } else {
  8515. assert(!AllocType->isArrayType() &&
  8516. "array allocation with non-array new");
  8517. }
  8518. APValue *Val;
  8519. if (IsPlacement) {
  8520. AccessKinds AK = AK_Construct;
  8521. struct FindObjectHandler {
  8522. EvalInfo &Info;
  8523. const Expr *E;
  8524. QualType AllocType;
  8525. const AccessKinds AccessKind;
  8526. APValue *Value;
  8527. typedef bool result_type;
  8528. bool failed() { return false; }
  8529. bool found(APValue &Subobj, QualType SubobjType) {
  8530. // FIXME: Reject the cases where [basic.life]p8 would not permit the
  8531. // old name of the object to be used to name the new object.
  8532. if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
  8533. Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
  8534. SubobjType << AllocType;
  8535. return false;
  8536. }
  8537. Value = &Subobj;
  8538. return true;
  8539. }
  8540. bool found(APSInt &Value, QualType SubobjType) {
  8541. Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
  8542. return false;
  8543. }
  8544. bool found(APFloat &Value, QualType SubobjType) {
  8545. Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
  8546. return false;
  8547. }
  8548. } Handler = {Info, E, AllocType, AK, nullptr};
  8549. CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
  8550. if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
  8551. return false;
  8552. Val = Handler.Value;
  8553. // [basic.life]p1:
  8554. // The lifetime of an object o of type T ends when [...] the storage
  8555. // which the object occupies is [...] reused by an object that is not
  8556. // nested within o (6.6.2).
  8557. *Val = APValue();
  8558. } else {
  8559. // Perform the allocation and obtain a pointer to the resulting object.
  8560. Val = Info.createHeapAlloc(E, AllocType, Result);
  8561. if (!Val)
  8562. return false;
  8563. }
  8564. if (ValueInit) {
  8565. ImplicitValueInitExpr VIE(AllocType);
  8566. if (!EvaluateInPlace(*Val, Info, Result, &VIE))
  8567. return false;
  8568. } else if (ResizedArrayILE) {
  8569. if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
  8570. AllocType))
  8571. return false;
  8572. } else if (ResizedArrayCCE) {
  8573. if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
  8574. AllocType))
  8575. return false;
  8576. } else if (Init) {
  8577. if (!EvaluateInPlace(*Val, Info, Result, Init))
  8578. return false;
  8579. } else if (!getDefaultInitValue(AllocType, *Val)) {
  8580. return false;
  8581. }
  8582. // Array new returns a pointer to the first element, not a pointer to the
  8583. // array.
  8584. if (auto *AT = AllocType->getAsArrayTypeUnsafe())
  8585. Result.addArray(Info, E, cast<ConstantArrayType>(AT));
  8586. return true;
  8587. }
  8588. //===----------------------------------------------------------------------===//
  8589. // Member Pointer Evaluation
  8590. //===----------------------------------------------------------------------===//
  8591. namespace {
  8592. class MemberPointerExprEvaluator
  8593. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  8594. MemberPtr &Result;
  8595. bool Success(const ValueDecl *D) {
  8596. Result = MemberPtr(D);
  8597. return true;
  8598. }
  8599. public:
  8600. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  8601. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  8602. bool Success(const APValue &V, const Expr *E) {
  8603. Result.setFrom(V);
  8604. return true;
  8605. }
  8606. bool ZeroInitialization(const Expr *E) {
  8607. return Success((const ValueDecl*)nullptr);
  8608. }
  8609. bool VisitCastExpr(const CastExpr *E);
  8610. bool VisitUnaryAddrOf(const UnaryOperator *E);
  8611. };
  8612. } // end anonymous namespace
  8613. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  8614. EvalInfo &Info) {
  8615. assert(!E->isValueDependent());
  8616. assert(E->isPRValue() && E->getType()->isMemberPointerType());
  8617. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  8618. }
  8619. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8620. switch (E->getCastKind()) {
  8621. default:
  8622. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8623. case CK_NullToMemberPointer:
  8624. VisitIgnoredValue(E->getSubExpr());
  8625. return ZeroInitialization(E);
  8626. case CK_BaseToDerivedMemberPointer: {
  8627. if (!Visit(E->getSubExpr()))
  8628. return false;
  8629. if (E->path_empty())
  8630. return true;
  8631. // Base-to-derived member pointer casts store the path in derived-to-base
  8632. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  8633. // the wrong end of the derived->base arc, so stagger the path by one class.
  8634. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  8635. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  8636. PathI != PathE; ++PathI) {
  8637. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  8638. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  8639. if (!Result.castToDerived(Derived))
  8640. return Error(E);
  8641. }
  8642. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  8643. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  8644. return Error(E);
  8645. return true;
  8646. }
  8647. case CK_DerivedToBaseMemberPointer:
  8648. if (!Visit(E->getSubExpr()))
  8649. return false;
  8650. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  8651. PathE = E->path_end(); PathI != PathE; ++PathI) {
  8652. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  8653. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  8654. if (!Result.castToBase(Base))
  8655. return Error(E);
  8656. }
  8657. return true;
  8658. }
  8659. }
  8660. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  8661. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  8662. // member can be formed.
  8663. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  8664. }
  8665. //===----------------------------------------------------------------------===//
  8666. // Record Evaluation
  8667. //===----------------------------------------------------------------------===//
  8668. namespace {
  8669. class RecordExprEvaluator
  8670. : public ExprEvaluatorBase<RecordExprEvaluator> {
  8671. const LValue &This;
  8672. APValue &Result;
  8673. public:
  8674. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  8675. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  8676. bool Success(const APValue &V, const Expr *E) {
  8677. Result = V;
  8678. return true;
  8679. }
  8680. bool ZeroInitialization(const Expr *E) {
  8681. return ZeroInitialization(E, E->getType());
  8682. }
  8683. bool ZeroInitialization(const Expr *E, QualType T);
  8684. bool VisitCallExpr(const CallExpr *E) {
  8685. return handleCallExpr(E, Result, &This);
  8686. }
  8687. bool VisitCastExpr(const CastExpr *E);
  8688. bool VisitInitListExpr(const InitListExpr *E);
  8689. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8690. return VisitCXXConstructExpr(E, E->getType());
  8691. }
  8692. bool VisitLambdaExpr(const LambdaExpr *E);
  8693. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  8694. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  8695. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  8696. bool VisitBinCmp(const BinaryOperator *E);
  8697. bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
  8698. bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
  8699. ArrayRef<Expr *> Args);
  8700. };
  8701. }
  8702. /// Perform zero-initialization on an object of non-union class type.
  8703. /// C++11 [dcl.init]p5:
  8704. /// To zero-initialize an object or reference of type T means:
  8705. /// [...]
  8706. /// -- if T is a (possibly cv-qualified) non-union class type,
  8707. /// each non-static data member and each base-class subobject is
  8708. /// zero-initialized
  8709. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  8710. const RecordDecl *RD,
  8711. const LValue &This, APValue &Result) {
  8712. assert(!RD->isUnion() && "Expected non-union class type");
  8713. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  8714. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  8715. std::distance(RD->field_begin(), RD->field_end()));
  8716. if (RD->isInvalidDecl()) return false;
  8717. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  8718. if (CD) {
  8719. unsigned Index = 0;
  8720. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  8721. End = CD->bases_end(); I != End; ++I, ++Index) {
  8722. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  8723. LValue Subobject = This;
  8724. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  8725. return false;
  8726. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  8727. Result.getStructBase(Index)))
  8728. return false;
  8729. }
  8730. }
  8731. for (const auto *I : RD->fields()) {
  8732. // -- if T is a reference type, no initialization is performed.
  8733. if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
  8734. continue;
  8735. LValue Subobject = This;
  8736. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  8737. return false;
  8738. ImplicitValueInitExpr VIE(I->getType());
  8739. if (!EvaluateInPlace(
  8740. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  8741. return false;
  8742. }
  8743. return true;
  8744. }
  8745. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  8746. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  8747. if (RD->isInvalidDecl()) return false;
  8748. if (RD->isUnion()) {
  8749. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  8750. // object's first non-static named data member is zero-initialized
  8751. RecordDecl::field_iterator I = RD->field_begin();
  8752. while (I != RD->field_end() && (*I)->isUnnamedBitfield())
  8753. ++I;
  8754. if (I == RD->field_end()) {
  8755. Result = APValue((const FieldDecl*)nullptr);
  8756. return true;
  8757. }
  8758. LValue Subobject = This;
  8759. if (!HandleLValueMember(Info, E, Subobject, *I))
  8760. return false;
  8761. Result = APValue(*I);
  8762. ImplicitValueInitExpr VIE(I->getType());
  8763. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  8764. }
  8765. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  8766. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  8767. return false;
  8768. }
  8769. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  8770. }
  8771. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8772. switch (E->getCastKind()) {
  8773. default:
  8774. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8775. case CK_ConstructorConversion:
  8776. return Visit(E->getSubExpr());
  8777. case CK_DerivedToBase:
  8778. case CK_UncheckedDerivedToBase: {
  8779. APValue DerivedObject;
  8780. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  8781. return false;
  8782. if (!DerivedObject.isStruct())
  8783. return Error(E->getSubExpr());
  8784. // Derived-to-base rvalue conversion: just slice off the derived part.
  8785. APValue *Value = &DerivedObject;
  8786. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  8787. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  8788. PathE = E->path_end(); PathI != PathE; ++PathI) {
  8789. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  8790. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  8791. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  8792. RD = Base;
  8793. }
  8794. Result = *Value;
  8795. return true;
  8796. }
  8797. }
  8798. }
  8799. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  8800. if (E->isTransparent())
  8801. return Visit(E->getInit(0));
  8802. return VisitCXXParenListOrInitListExpr(E, E->inits());
  8803. }
  8804. bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
  8805. const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
  8806. const RecordDecl *RD =
  8807. ExprToVisit->getType()->castAs<RecordType>()->getDecl();
  8808. if (RD->isInvalidDecl()) return false;
  8809. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  8810. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  8811. EvalInfo::EvaluatingConstructorRAII EvalObj(
  8812. Info,
  8813. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  8814. CXXRD && CXXRD->getNumBases());
  8815. if (RD->isUnion()) {
  8816. const FieldDecl *Field;
  8817. if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
  8818. Field = ILE->getInitializedFieldInUnion();
  8819. } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
  8820. Field = PLIE->getInitializedFieldInUnion();
  8821. } else {
  8822. llvm_unreachable(
  8823. "Expression is neither an init list nor a C++ paren list");
  8824. }
  8825. Result = APValue(Field);
  8826. if (!Field)
  8827. return true;
  8828. // If the initializer list for a union does not contain any elements, the
  8829. // first element of the union is value-initialized.
  8830. // FIXME: The element should be initialized from an initializer list.
  8831. // Is this difference ever observable for initializer lists which
  8832. // we don't build?
  8833. ImplicitValueInitExpr VIE(Field->getType());
  8834. const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
  8835. LValue Subobject = This;
  8836. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  8837. return false;
  8838. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  8839. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  8840. isa<CXXDefaultInitExpr>(InitExpr));
  8841. if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
  8842. if (Field->isBitField())
  8843. return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
  8844. Field);
  8845. return true;
  8846. }
  8847. return false;
  8848. }
  8849. if (!Result.hasValue())
  8850. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  8851. std::distance(RD->field_begin(), RD->field_end()));
  8852. unsigned ElementNo = 0;
  8853. bool Success = true;
  8854. // Initialize base classes.
  8855. if (CXXRD && CXXRD->getNumBases()) {
  8856. for (const auto &Base : CXXRD->bases()) {
  8857. assert(ElementNo < Args.size() && "missing init for base class");
  8858. const Expr *Init = Args[ElementNo];
  8859. LValue Subobject = This;
  8860. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  8861. return false;
  8862. APValue &FieldVal = Result.getStructBase(ElementNo);
  8863. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  8864. if (!Info.noteFailure())
  8865. return false;
  8866. Success = false;
  8867. }
  8868. ++ElementNo;
  8869. }
  8870. EvalObj.finishedConstructingBases();
  8871. }
  8872. // Initialize members.
  8873. for (const auto *Field : RD->fields()) {
  8874. // Anonymous bit-fields are not considered members of the class for
  8875. // purposes of aggregate initialization.
  8876. if (Field->isUnnamedBitfield())
  8877. continue;
  8878. LValue Subobject = This;
  8879. bool HaveInit = ElementNo < Args.size();
  8880. // FIXME: Diagnostics here should point to the end of the initializer
  8881. // list, not the start.
  8882. if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
  8883. Subobject, Field, &Layout))
  8884. return false;
  8885. // Perform an implicit value-initialization for members beyond the end of
  8886. // the initializer list.
  8887. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  8888. const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
  8889. if (Field->getType()->isIncompleteArrayType()) {
  8890. if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
  8891. if (!CAT->getSize().isZero()) {
  8892. // Bail out for now. This might sort of "work", but the rest of the
  8893. // code isn't really prepared to handle it.
  8894. Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
  8895. return false;
  8896. }
  8897. }
  8898. }
  8899. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  8900. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  8901. isa<CXXDefaultInitExpr>(Init));
  8902. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  8903. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  8904. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  8905. FieldVal, Field))) {
  8906. if (!Info.noteFailure())
  8907. return false;
  8908. Success = false;
  8909. }
  8910. }
  8911. EvalObj.finishedConstructingFields();
  8912. return Success;
  8913. }
  8914. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  8915. QualType T) {
  8916. // Note that E's type is not necessarily the type of our class here; we might
  8917. // be initializing an array element instead.
  8918. const CXXConstructorDecl *FD = E->getConstructor();
  8919. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  8920. bool ZeroInit = E->requiresZeroInitialization();
  8921. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  8922. // If we've already performed zero-initialization, we're already done.
  8923. if (Result.hasValue())
  8924. return true;
  8925. if (ZeroInit)
  8926. return ZeroInitialization(E, T);
  8927. return getDefaultInitValue(T, Result);
  8928. }
  8929. const FunctionDecl *Definition = nullptr;
  8930. auto Body = FD->getBody(Definition);
  8931. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  8932. return false;
  8933. // Avoid materializing a temporary for an elidable copy/move constructor.
  8934. if (E->isElidable() && !ZeroInit) {
  8935. // FIXME: This only handles the simplest case, where the source object
  8936. // is passed directly as the first argument to the constructor.
  8937. // This should also handle stepping though implicit casts and
  8938. // and conversion sequences which involve two steps, with a
  8939. // conversion operator followed by a converting constructor.
  8940. const Expr *SrcObj = E->getArg(0);
  8941. assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
  8942. assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
  8943. if (const MaterializeTemporaryExpr *ME =
  8944. dyn_cast<MaterializeTemporaryExpr>(SrcObj))
  8945. return Visit(ME->getSubExpr());
  8946. }
  8947. if (ZeroInit && !ZeroInitialization(E, T))
  8948. return false;
  8949. auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
  8950. return HandleConstructorCall(E, This, Args,
  8951. cast<CXXConstructorDecl>(Definition), Info,
  8952. Result);
  8953. }
  8954. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  8955. const CXXInheritedCtorInitExpr *E) {
  8956. if (!Info.CurrentCall) {
  8957. assert(Info.checkingPotentialConstantExpression());
  8958. return false;
  8959. }
  8960. const CXXConstructorDecl *FD = E->getConstructor();
  8961. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  8962. return false;
  8963. const FunctionDecl *Definition = nullptr;
  8964. auto Body = FD->getBody(Definition);
  8965. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  8966. return false;
  8967. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  8968. cast<CXXConstructorDecl>(Definition), Info,
  8969. Result);
  8970. }
  8971. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  8972. const CXXStdInitializerListExpr *E) {
  8973. const ConstantArrayType *ArrayType =
  8974. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  8975. LValue Array;
  8976. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  8977. return false;
  8978. // Get a pointer to the first element of the array.
  8979. Array.addArray(Info, E, ArrayType);
  8980. auto InvalidType = [&] {
  8981. Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
  8982. << E->getType();
  8983. return false;
  8984. };
  8985. // FIXME: Perform the checks on the field types in SemaInit.
  8986. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  8987. RecordDecl::field_iterator Field = Record->field_begin();
  8988. if (Field == Record->field_end())
  8989. return InvalidType();
  8990. // Start pointer.
  8991. if (!Field->getType()->isPointerType() ||
  8992. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  8993. ArrayType->getElementType()))
  8994. return InvalidType();
  8995. // FIXME: What if the initializer_list type has base classes, etc?
  8996. Result = APValue(APValue::UninitStruct(), 0, 2);
  8997. Array.moveInto(Result.getStructField(0));
  8998. if (++Field == Record->field_end())
  8999. return InvalidType();
  9000. if (Field->getType()->isPointerType() &&
  9001. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  9002. ArrayType->getElementType())) {
  9003. // End pointer.
  9004. if (!HandleLValueArrayAdjustment(Info, E, Array,
  9005. ArrayType->getElementType(),
  9006. ArrayType->getSize().getZExtValue()))
  9007. return false;
  9008. Array.moveInto(Result.getStructField(1));
  9009. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  9010. // Length.
  9011. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  9012. else
  9013. return InvalidType();
  9014. if (++Field != Record->field_end())
  9015. return InvalidType();
  9016. return true;
  9017. }
  9018. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  9019. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  9020. if (ClosureClass->isInvalidDecl())
  9021. return false;
  9022. const size_t NumFields =
  9023. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  9024. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  9025. E->capture_init_end()) &&
  9026. "The number of lambda capture initializers should equal the number of "
  9027. "fields within the closure type");
  9028. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  9029. // Iterate through all the lambda's closure object's fields and initialize
  9030. // them.
  9031. auto *CaptureInitIt = E->capture_init_begin();
  9032. bool Success = true;
  9033. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
  9034. for (const auto *Field : ClosureClass->fields()) {
  9035. assert(CaptureInitIt != E->capture_init_end());
  9036. // Get the initializer for this field
  9037. Expr *const CurFieldInit = *CaptureInitIt++;
  9038. // If there is no initializer, either this is a VLA or an error has
  9039. // occurred.
  9040. if (!CurFieldInit)
  9041. return Error(E);
  9042. LValue Subobject = This;
  9043. if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
  9044. return false;
  9045. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  9046. if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
  9047. if (!Info.keepEvaluatingAfterFailure())
  9048. return false;
  9049. Success = false;
  9050. }
  9051. }
  9052. return Success;
  9053. }
  9054. static bool EvaluateRecord(const Expr *E, const LValue &This,
  9055. APValue &Result, EvalInfo &Info) {
  9056. assert(!E->isValueDependent());
  9057. assert(E->isPRValue() && E->getType()->isRecordType() &&
  9058. "can't evaluate expression as a record rvalue");
  9059. return RecordExprEvaluator(Info, This, Result).Visit(E);
  9060. }
  9061. //===----------------------------------------------------------------------===//
  9062. // Temporary Evaluation
  9063. //
  9064. // Temporaries are represented in the AST as rvalues, but generally behave like
  9065. // lvalues. The full-object of which the temporary is a subobject is implicitly
  9066. // materialized so that a reference can bind to it.
  9067. //===----------------------------------------------------------------------===//
  9068. namespace {
  9069. class TemporaryExprEvaluator
  9070. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  9071. public:
  9072. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  9073. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  9074. /// Visit an expression which constructs the value of this temporary.
  9075. bool VisitConstructExpr(const Expr *E) {
  9076. APValue &Value = Info.CurrentCall->createTemporary(
  9077. E, E->getType(), ScopeKind::FullExpression, Result);
  9078. return EvaluateInPlace(Value, Info, Result, E);
  9079. }
  9080. bool VisitCastExpr(const CastExpr *E) {
  9081. switch (E->getCastKind()) {
  9082. default:
  9083. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  9084. case CK_ConstructorConversion:
  9085. return VisitConstructExpr(E->getSubExpr());
  9086. }
  9087. }
  9088. bool VisitInitListExpr(const InitListExpr *E) {
  9089. return VisitConstructExpr(E);
  9090. }
  9091. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  9092. return VisitConstructExpr(E);
  9093. }
  9094. bool VisitCallExpr(const CallExpr *E) {
  9095. return VisitConstructExpr(E);
  9096. }
  9097. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  9098. return VisitConstructExpr(E);
  9099. }
  9100. bool VisitLambdaExpr(const LambdaExpr *E) {
  9101. return VisitConstructExpr(E);
  9102. }
  9103. };
  9104. } // end anonymous namespace
  9105. /// Evaluate an expression of record type as a temporary.
  9106. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  9107. assert(!E->isValueDependent());
  9108. assert(E->isPRValue() && E->getType()->isRecordType());
  9109. return TemporaryExprEvaluator(Info, Result).Visit(E);
  9110. }
  9111. //===----------------------------------------------------------------------===//
  9112. // Vector Evaluation
  9113. //===----------------------------------------------------------------------===//
  9114. namespace {
  9115. class VectorExprEvaluator
  9116. : public ExprEvaluatorBase<VectorExprEvaluator> {
  9117. APValue &Result;
  9118. public:
  9119. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  9120. : ExprEvaluatorBaseTy(info), Result(Result) {}
  9121. bool Success(ArrayRef<APValue> V, const Expr *E) {
  9122. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  9123. // FIXME: remove this APValue copy.
  9124. Result = APValue(V.data(), V.size());
  9125. return true;
  9126. }
  9127. bool Success(const APValue &V, const Expr *E) {
  9128. assert(V.isVector());
  9129. Result = V;
  9130. return true;
  9131. }
  9132. bool ZeroInitialization(const Expr *E);
  9133. bool VisitUnaryReal(const UnaryOperator *E)
  9134. { return Visit(E->getSubExpr()); }
  9135. bool VisitCastExpr(const CastExpr* E);
  9136. bool VisitInitListExpr(const InitListExpr *E);
  9137. bool VisitUnaryImag(const UnaryOperator *E);
  9138. bool VisitBinaryOperator(const BinaryOperator *E);
  9139. bool VisitUnaryOperator(const UnaryOperator *E);
  9140. // FIXME: Missing: conditional operator (for GNU
  9141. // conditional select), shufflevector, ExtVectorElementExpr
  9142. };
  9143. } // end anonymous namespace
  9144. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  9145. assert(E->isPRValue() && E->getType()->isVectorType() &&
  9146. "not a vector prvalue");
  9147. return VectorExprEvaluator(Info, Result).Visit(E);
  9148. }
  9149. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9150. const VectorType *VTy = E->getType()->castAs<VectorType>();
  9151. unsigned NElts = VTy->getNumElements();
  9152. const Expr *SE = E->getSubExpr();
  9153. QualType SETy = SE->getType();
  9154. switch (E->getCastKind()) {
  9155. case CK_VectorSplat: {
  9156. APValue Val = APValue();
  9157. if (SETy->isIntegerType()) {
  9158. APSInt IntResult;
  9159. if (!EvaluateInteger(SE, IntResult, Info))
  9160. return false;
  9161. Val = APValue(std::move(IntResult));
  9162. } else if (SETy->isRealFloatingType()) {
  9163. APFloat FloatResult(0.0);
  9164. if (!EvaluateFloat(SE, FloatResult, Info))
  9165. return false;
  9166. Val = APValue(std::move(FloatResult));
  9167. } else {
  9168. return Error(E);
  9169. }
  9170. // Splat and create vector APValue.
  9171. SmallVector<APValue, 4> Elts(NElts, Val);
  9172. return Success(Elts, E);
  9173. }
  9174. case CK_BitCast: {
  9175. // Evaluate the operand into an APInt we can extract from.
  9176. llvm::APInt SValInt;
  9177. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  9178. return false;
  9179. // Extract the elements
  9180. QualType EltTy = VTy->getElementType();
  9181. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  9182. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  9183. SmallVector<APValue, 4> Elts;
  9184. if (EltTy->isRealFloatingType()) {
  9185. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  9186. unsigned FloatEltSize = EltSize;
  9187. if (&Sem == &APFloat::x87DoubleExtended())
  9188. FloatEltSize = 80;
  9189. for (unsigned i = 0; i < NElts; i++) {
  9190. llvm::APInt Elt;
  9191. if (BigEndian)
  9192. Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
  9193. else
  9194. Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
  9195. Elts.push_back(APValue(APFloat(Sem, Elt)));
  9196. }
  9197. } else if (EltTy->isIntegerType()) {
  9198. for (unsigned i = 0; i < NElts; i++) {
  9199. llvm::APInt Elt;
  9200. if (BigEndian)
  9201. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  9202. else
  9203. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  9204. Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
  9205. }
  9206. } else {
  9207. return Error(E);
  9208. }
  9209. return Success(Elts, E);
  9210. }
  9211. default:
  9212. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9213. }
  9214. }
  9215. bool
  9216. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  9217. const VectorType *VT = E->getType()->castAs<VectorType>();
  9218. unsigned NumInits = E->getNumInits();
  9219. unsigned NumElements = VT->getNumElements();
  9220. QualType EltTy = VT->getElementType();
  9221. SmallVector<APValue, 4> Elements;
  9222. // The number of initializers can be less than the number of
  9223. // vector elements. For OpenCL, this can be due to nested vector
  9224. // initialization. For GCC compatibility, missing trailing elements
  9225. // should be initialized with zeroes.
  9226. unsigned CountInits = 0, CountElts = 0;
  9227. while (CountElts < NumElements) {
  9228. // Handle nested vector initialization.
  9229. if (CountInits < NumInits
  9230. && E->getInit(CountInits)->getType()->isVectorType()) {
  9231. APValue v;
  9232. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  9233. return Error(E);
  9234. unsigned vlen = v.getVectorLength();
  9235. for (unsigned j = 0; j < vlen; j++)
  9236. Elements.push_back(v.getVectorElt(j));
  9237. CountElts += vlen;
  9238. } else if (EltTy->isIntegerType()) {
  9239. llvm::APSInt sInt(32);
  9240. if (CountInits < NumInits) {
  9241. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  9242. return false;
  9243. } else // trailing integer zero.
  9244. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  9245. Elements.push_back(APValue(sInt));
  9246. CountElts++;
  9247. } else {
  9248. llvm::APFloat f(0.0);
  9249. if (CountInits < NumInits) {
  9250. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  9251. return false;
  9252. } else // trailing float zero.
  9253. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  9254. Elements.push_back(APValue(f));
  9255. CountElts++;
  9256. }
  9257. CountInits++;
  9258. }
  9259. return Success(Elements, E);
  9260. }
  9261. bool
  9262. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  9263. const auto *VT = E->getType()->castAs<VectorType>();
  9264. QualType EltTy = VT->getElementType();
  9265. APValue ZeroElement;
  9266. if (EltTy->isIntegerType())
  9267. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  9268. else
  9269. ZeroElement =
  9270. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  9271. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  9272. return Success(Elements, E);
  9273. }
  9274. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9275. VisitIgnoredValue(E->getSubExpr());
  9276. return ZeroInitialization(E);
  9277. }
  9278. bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9279. BinaryOperatorKind Op = E->getOpcode();
  9280. assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
  9281. "Operation not supported on vector types");
  9282. if (Op == BO_Comma)
  9283. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9284. Expr *LHS = E->getLHS();
  9285. Expr *RHS = E->getRHS();
  9286. assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
  9287. "Must both be vector types");
  9288. // Checking JUST the types are the same would be fine, except shifts don't
  9289. // need to have their types be the same (since you always shift by an int).
  9290. assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
  9291. E->getType()->castAs<VectorType>()->getNumElements() &&
  9292. RHS->getType()->castAs<VectorType>()->getNumElements() ==
  9293. E->getType()->castAs<VectorType>()->getNumElements() &&
  9294. "All operands must be the same size.");
  9295. APValue LHSValue;
  9296. APValue RHSValue;
  9297. bool LHSOK = Evaluate(LHSValue, Info, LHS);
  9298. if (!LHSOK && !Info.noteFailure())
  9299. return false;
  9300. if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
  9301. return false;
  9302. if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
  9303. return false;
  9304. return Success(LHSValue, E);
  9305. }
  9306. static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
  9307. QualType ResultTy,
  9308. UnaryOperatorKind Op,
  9309. APValue Elt) {
  9310. switch (Op) {
  9311. case UO_Plus:
  9312. // Nothing to do here.
  9313. return Elt;
  9314. case UO_Minus:
  9315. if (Elt.getKind() == APValue::Int) {
  9316. Elt.getInt().negate();
  9317. } else {
  9318. assert(Elt.getKind() == APValue::Float &&
  9319. "Vector can only be int or float type");
  9320. Elt.getFloat().changeSign();
  9321. }
  9322. return Elt;
  9323. case UO_Not:
  9324. // This is only valid for integral types anyway, so we don't have to handle
  9325. // float here.
  9326. assert(Elt.getKind() == APValue::Int &&
  9327. "Vector operator ~ can only be int");
  9328. Elt.getInt().flipAllBits();
  9329. return Elt;
  9330. case UO_LNot: {
  9331. if (Elt.getKind() == APValue::Int) {
  9332. Elt.getInt() = !Elt.getInt();
  9333. // operator ! on vectors returns -1 for 'truth', so negate it.
  9334. Elt.getInt().negate();
  9335. return Elt;
  9336. }
  9337. assert(Elt.getKind() == APValue::Float &&
  9338. "Vector can only be int or float type");
  9339. // Float types result in an int of the same size, but -1 for true, or 0 for
  9340. // false.
  9341. APSInt EltResult{Ctx.getIntWidth(ResultTy),
  9342. ResultTy->isUnsignedIntegerType()};
  9343. if (Elt.getFloat().isZero())
  9344. EltResult.setAllBits();
  9345. else
  9346. EltResult.clearAllBits();
  9347. return APValue{EltResult};
  9348. }
  9349. default:
  9350. // FIXME: Implement the rest of the unary operators.
  9351. return std::nullopt;
  9352. }
  9353. }
  9354. bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9355. Expr *SubExpr = E->getSubExpr();
  9356. const auto *VD = SubExpr->getType()->castAs<VectorType>();
  9357. // This result element type differs in the case of negating a floating point
  9358. // vector, since the result type is the a vector of the equivilant sized
  9359. // integer.
  9360. const QualType ResultEltTy = VD->getElementType();
  9361. UnaryOperatorKind Op = E->getOpcode();
  9362. APValue SubExprValue;
  9363. if (!Evaluate(SubExprValue, Info, SubExpr))
  9364. return false;
  9365. // FIXME: This vector evaluator someday needs to be changed to be LValue
  9366. // aware/keep LValue information around, rather than dealing with just vector
  9367. // types directly. Until then, we cannot handle cases where the operand to
  9368. // these unary operators is an LValue. The only case I've been able to see
  9369. // cause this is operator++ assigning to a member expression (only valid in
  9370. // altivec compilations) in C mode, so this shouldn't limit us too much.
  9371. if (SubExprValue.isLValue())
  9372. return false;
  9373. assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
  9374. "Vector length doesn't match type?");
  9375. SmallVector<APValue, 4> ResultElements;
  9376. for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
  9377. std::optional<APValue> Elt = handleVectorUnaryOperator(
  9378. Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
  9379. if (!Elt)
  9380. return false;
  9381. ResultElements.push_back(*Elt);
  9382. }
  9383. return Success(APValue(ResultElements.data(), ResultElements.size()), E);
  9384. }
  9385. //===----------------------------------------------------------------------===//
  9386. // Array Evaluation
  9387. //===----------------------------------------------------------------------===//
  9388. namespace {
  9389. class ArrayExprEvaluator
  9390. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  9391. const LValue &This;
  9392. APValue &Result;
  9393. public:
  9394. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  9395. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  9396. bool Success(const APValue &V, const Expr *E) {
  9397. assert(V.isArray() && "expected array");
  9398. Result = V;
  9399. return true;
  9400. }
  9401. bool ZeroInitialization(const Expr *E) {
  9402. const ConstantArrayType *CAT =
  9403. Info.Ctx.getAsConstantArrayType(E->getType());
  9404. if (!CAT) {
  9405. if (E->getType()->isIncompleteArrayType()) {
  9406. // We can be asked to zero-initialize a flexible array member; this
  9407. // is represented as an ImplicitValueInitExpr of incomplete array
  9408. // type. In this case, the array has zero elements.
  9409. Result = APValue(APValue::UninitArray(), 0, 0);
  9410. return true;
  9411. }
  9412. // FIXME: We could handle VLAs here.
  9413. return Error(E);
  9414. }
  9415. Result = APValue(APValue::UninitArray(), 0,
  9416. CAT->getSize().getZExtValue());
  9417. if (!Result.hasArrayFiller())
  9418. return true;
  9419. // Zero-initialize all elements.
  9420. LValue Subobject = This;
  9421. Subobject.addArray(Info, E, CAT);
  9422. ImplicitValueInitExpr VIE(CAT->getElementType());
  9423. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  9424. }
  9425. bool VisitCallExpr(const CallExpr *E) {
  9426. return handleCallExpr(E, Result, &This);
  9427. }
  9428. bool VisitInitListExpr(const InitListExpr *E,
  9429. QualType AllocType = QualType());
  9430. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  9431. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  9432. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  9433. const LValue &Subobject,
  9434. APValue *Value, QualType Type);
  9435. bool VisitStringLiteral(const StringLiteral *E,
  9436. QualType AllocType = QualType()) {
  9437. expandStringLiteral(Info, E, Result, AllocType);
  9438. return true;
  9439. }
  9440. bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
  9441. bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
  9442. ArrayRef<Expr *> Args,
  9443. const Expr *ArrayFiller,
  9444. QualType AllocType = QualType());
  9445. };
  9446. } // end anonymous namespace
  9447. static bool EvaluateArray(const Expr *E, const LValue &This,
  9448. APValue &Result, EvalInfo &Info) {
  9449. assert(!E->isValueDependent());
  9450. assert(E->isPRValue() && E->getType()->isArrayType() &&
  9451. "not an array prvalue");
  9452. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  9453. }
  9454. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  9455. APValue &Result, const InitListExpr *ILE,
  9456. QualType AllocType) {
  9457. assert(!ILE->isValueDependent());
  9458. assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
  9459. "not an array prvalue");
  9460. return ArrayExprEvaluator(Info, This, Result)
  9461. .VisitInitListExpr(ILE, AllocType);
  9462. }
  9463. static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
  9464. APValue &Result,
  9465. const CXXConstructExpr *CCE,
  9466. QualType AllocType) {
  9467. assert(!CCE->isValueDependent());
  9468. assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
  9469. "not an array prvalue");
  9470. return ArrayExprEvaluator(Info, This, Result)
  9471. .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
  9472. }
  9473. // Return true iff the given array filler may depend on the element index.
  9474. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  9475. // For now, just allow non-class value-initialization and initialization
  9476. // lists comprised of them.
  9477. if (isa<ImplicitValueInitExpr>(FillerExpr))
  9478. return false;
  9479. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  9480. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  9481. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  9482. return true;
  9483. }
  9484. if (ILE->hasArrayFiller() &&
  9485. MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
  9486. return true;
  9487. return false;
  9488. }
  9489. return true;
  9490. }
  9491. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
  9492. QualType AllocType) {
  9493. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  9494. AllocType.isNull() ? E->getType() : AllocType);
  9495. if (!CAT)
  9496. return Error(E);
  9497. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  9498. // an appropriately-typed string literal enclosed in braces.
  9499. if (E->isStringLiteralInit()) {
  9500. auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
  9501. // FIXME: Support ObjCEncodeExpr here once we support it in
  9502. // ArrayExprEvaluator generally.
  9503. if (!SL)
  9504. return Error(E);
  9505. return VisitStringLiteral(SL, AllocType);
  9506. }
  9507. // Any other transparent list init will need proper handling of the
  9508. // AllocType; we can't just recurse to the inner initializer.
  9509. assert(!E->isTransparent() &&
  9510. "transparent array list initialization is not string literal init?");
  9511. return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
  9512. AllocType);
  9513. }
  9514. bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
  9515. const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
  9516. QualType AllocType) {
  9517. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  9518. AllocType.isNull() ? ExprToVisit->getType() : AllocType);
  9519. bool Success = true;
  9520. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  9521. "zero-initialized array shouldn't have any initialized elts");
  9522. APValue Filler;
  9523. if (Result.isArray() && Result.hasArrayFiller())
  9524. Filler = Result.getArrayFiller();
  9525. unsigned NumEltsToInit = Args.size();
  9526. unsigned NumElts = CAT->getSize().getZExtValue();
  9527. // If the initializer might depend on the array index, run it for each
  9528. // array element.
  9529. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
  9530. NumEltsToInit = NumElts;
  9531. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  9532. << NumEltsToInit << ".\n");
  9533. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  9534. // If the array was previously zero-initialized, preserve the
  9535. // zero-initialized values.
  9536. if (Filler.hasValue()) {
  9537. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  9538. Result.getArrayInitializedElt(I) = Filler;
  9539. if (Result.hasArrayFiller())
  9540. Result.getArrayFiller() = Filler;
  9541. }
  9542. LValue Subobject = This;
  9543. Subobject.addArray(Info, ExprToVisit, CAT);
  9544. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  9545. const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
  9546. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  9547. Info, Subobject, Init) ||
  9548. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  9549. CAT->getElementType(), 1)) {
  9550. if (!Info.noteFailure())
  9551. return false;
  9552. Success = false;
  9553. }
  9554. }
  9555. if (!Result.hasArrayFiller())
  9556. return Success;
  9557. // If we get here, we have a trivial filler, which we can just evaluate
  9558. // once and splat over the rest of the array elements.
  9559. assert(ArrayFiller && "no array filler for incomplete init list");
  9560. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  9561. ArrayFiller) &&
  9562. Success;
  9563. }
  9564. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  9565. LValue CommonLV;
  9566. if (E->getCommonExpr() &&
  9567. !Evaluate(Info.CurrentCall->createTemporary(
  9568. E->getCommonExpr(),
  9569. getStorageType(Info.Ctx, E->getCommonExpr()),
  9570. ScopeKind::FullExpression, CommonLV),
  9571. Info, E->getCommonExpr()->getSourceExpr()))
  9572. return false;
  9573. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  9574. uint64_t Elements = CAT->getSize().getZExtValue();
  9575. Result = APValue(APValue::UninitArray(), Elements, Elements);
  9576. LValue Subobject = This;
  9577. Subobject.addArray(Info, E, CAT);
  9578. bool Success = true;
  9579. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  9580. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  9581. Info, Subobject, E->getSubExpr()) ||
  9582. !HandleLValueArrayAdjustment(Info, E, Subobject,
  9583. CAT->getElementType(), 1)) {
  9584. if (!Info.noteFailure())
  9585. return false;
  9586. Success = false;
  9587. }
  9588. }
  9589. return Success;
  9590. }
  9591. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  9592. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  9593. }
  9594. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  9595. const LValue &Subobject,
  9596. APValue *Value,
  9597. QualType Type) {
  9598. bool HadZeroInit = Value->hasValue();
  9599. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  9600. unsigned FinalSize = CAT->getSize().getZExtValue();
  9601. // Preserve the array filler if we had prior zero-initialization.
  9602. APValue Filler =
  9603. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  9604. : APValue();
  9605. *Value = APValue(APValue::UninitArray(), 0, FinalSize);
  9606. if (FinalSize == 0)
  9607. return true;
  9608. bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
  9609. Info, E->getExprLoc(), E->getConstructor(),
  9610. E->requiresZeroInitialization());
  9611. LValue ArrayElt = Subobject;
  9612. ArrayElt.addArray(Info, E, CAT);
  9613. // We do the whole initialization in two passes, first for just one element,
  9614. // then for the whole array. It's possible we may find out we can't do const
  9615. // init in the first pass, in which case we avoid allocating a potentially
  9616. // large array. We don't do more passes because expanding array requires
  9617. // copying the data, which is wasteful.
  9618. for (const unsigned N : {1u, FinalSize}) {
  9619. unsigned OldElts = Value->getArrayInitializedElts();
  9620. if (OldElts == N)
  9621. break;
  9622. // Expand the array to appropriate size.
  9623. APValue NewValue(APValue::UninitArray(), N, FinalSize);
  9624. for (unsigned I = 0; I < OldElts; ++I)
  9625. NewValue.getArrayInitializedElt(I).swap(
  9626. Value->getArrayInitializedElt(I));
  9627. Value->swap(NewValue);
  9628. if (HadZeroInit)
  9629. for (unsigned I = OldElts; I < N; ++I)
  9630. Value->getArrayInitializedElt(I) = Filler;
  9631. if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
  9632. // If we have a trivial constructor, only evaluate it once and copy
  9633. // the result into all the array elements.
  9634. APValue &FirstResult = Value->getArrayInitializedElt(0);
  9635. for (unsigned I = OldElts; I < FinalSize; ++I)
  9636. Value->getArrayInitializedElt(I) = FirstResult;
  9637. } else {
  9638. for (unsigned I = OldElts; I < N; ++I) {
  9639. if (!VisitCXXConstructExpr(E, ArrayElt,
  9640. &Value->getArrayInitializedElt(I),
  9641. CAT->getElementType()) ||
  9642. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  9643. CAT->getElementType(), 1))
  9644. return false;
  9645. // When checking for const initilization any diagnostic is considered
  9646. // an error.
  9647. if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
  9648. !Info.keepEvaluatingAfterFailure())
  9649. return false;
  9650. }
  9651. }
  9652. }
  9653. return true;
  9654. }
  9655. if (!Type->isRecordType())
  9656. return Error(E);
  9657. return RecordExprEvaluator(Info, Subobject, *Value)
  9658. .VisitCXXConstructExpr(E, Type);
  9659. }
  9660. bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
  9661. const CXXParenListInitExpr *E) {
  9662. assert(dyn_cast<ConstantArrayType>(E->getType()) &&
  9663. "Expression result is not a constant array type");
  9664. return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
  9665. E->getArrayFiller());
  9666. }
  9667. //===----------------------------------------------------------------------===//
  9668. // Integer Evaluation
  9669. //
  9670. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  9671. // types and back in constant folding. Integer values are thus represented
  9672. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  9673. //===----------------------------------------------------------------------===//
  9674. namespace {
  9675. class IntExprEvaluator
  9676. : public ExprEvaluatorBase<IntExprEvaluator> {
  9677. APValue &Result;
  9678. public:
  9679. IntExprEvaluator(EvalInfo &info, APValue &result)
  9680. : ExprEvaluatorBaseTy(info), Result(result) {}
  9681. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  9682. assert(E->getType()->isIntegralOrEnumerationType() &&
  9683. "Invalid evaluation result.");
  9684. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  9685. "Invalid evaluation result.");
  9686. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  9687. "Invalid evaluation result.");
  9688. Result = APValue(SI);
  9689. return true;
  9690. }
  9691. bool Success(const llvm::APSInt &SI, const Expr *E) {
  9692. return Success(SI, E, Result);
  9693. }
  9694. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  9695. assert(E->getType()->isIntegralOrEnumerationType() &&
  9696. "Invalid evaluation result.");
  9697. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  9698. "Invalid evaluation result.");
  9699. Result = APValue(APSInt(I));
  9700. Result.getInt().setIsUnsigned(
  9701. E->getType()->isUnsignedIntegerOrEnumerationType());
  9702. return true;
  9703. }
  9704. bool Success(const llvm::APInt &I, const Expr *E) {
  9705. return Success(I, E, Result);
  9706. }
  9707. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  9708. assert(E->getType()->isIntegralOrEnumerationType() &&
  9709. "Invalid evaluation result.");
  9710. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  9711. return true;
  9712. }
  9713. bool Success(uint64_t Value, const Expr *E) {
  9714. return Success(Value, E, Result);
  9715. }
  9716. bool Success(CharUnits Size, const Expr *E) {
  9717. return Success(Size.getQuantity(), E);
  9718. }
  9719. bool Success(const APValue &V, const Expr *E) {
  9720. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  9721. Result = V;
  9722. return true;
  9723. }
  9724. return Success(V.getInt(), E);
  9725. }
  9726. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  9727. //===--------------------------------------------------------------------===//
  9728. // Visitor Methods
  9729. //===--------------------------------------------------------------------===//
  9730. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  9731. return Success(E->getValue(), E);
  9732. }
  9733. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  9734. return Success(E->getValue(), E);
  9735. }
  9736. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  9737. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  9738. if (CheckReferencedDecl(E, E->getDecl()))
  9739. return true;
  9740. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  9741. }
  9742. bool VisitMemberExpr(const MemberExpr *E) {
  9743. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  9744. VisitIgnoredBaseExpression(E->getBase());
  9745. return true;
  9746. }
  9747. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  9748. }
  9749. bool VisitCallExpr(const CallExpr *E);
  9750. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  9751. bool VisitBinaryOperator(const BinaryOperator *E);
  9752. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  9753. bool VisitUnaryOperator(const UnaryOperator *E);
  9754. bool VisitCastExpr(const CastExpr* E);
  9755. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  9756. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  9757. return Success(E->getValue(), E);
  9758. }
  9759. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  9760. return Success(E->getValue(), E);
  9761. }
  9762. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  9763. if (Info.ArrayInitIndex == uint64_t(-1)) {
  9764. // We were asked to evaluate this subexpression independent of the
  9765. // enclosing ArrayInitLoopExpr. We can't do that.
  9766. Info.FFDiag(E);
  9767. return false;
  9768. }
  9769. return Success(Info.ArrayInitIndex, E);
  9770. }
  9771. // Note, GNU defines __null as an integer, not a pointer.
  9772. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  9773. return ZeroInitialization(E);
  9774. }
  9775. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  9776. return Success(E->getValue(), E);
  9777. }
  9778. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  9779. return Success(E->getValue(), E);
  9780. }
  9781. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  9782. return Success(E->getValue(), E);
  9783. }
  9784. bool VisitUnaryReal(const UnaryOperator *E);
  9785. bool VisitUnaryImag(const UnaryOperator *E);
  9786. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  9787. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  9788. bool VisitSourceLocExpr(const SourceLocExpr *E);
  9789. bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
  9790. bool VisitRequiresExpr(const RequiresExpr *E);
  9791. // FIXME: Missing: array subscript of vector, member of vector
  9792. };
  9793. class FixedPointExprEvaluator
  9794. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  9795. APValue &Result;
  9796. public:
  9797. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  9798. : ExprEvaluatorBaseTy(info), Result(result) {}
  9799. bool Success(const llvm::APInt &I, const Expr *E) {
  9800. return Success(
  9801. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  9802. }
  9803. bool Success(uint64_t Value, const Expr *E) {
  9804. return Success(
  9805. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  9806. }
  9807. bool Success(const APValue &V, const Expr *E) {
  9808. return Success(V.getFixedPoint(), E);
  9809. }
  9810. bool Success(const APFixedPoint &V, const Expr *E) {
  9811. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  9812. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  9813. "Invalid evaluation result.");
  9814. Result = APValue(V);
  9815. return true;
  9816. }
  9817. //===--------------------------------------------------------------------===//
  9818. // Visitor Methods
  9819. //===--------------------------------------------------------------------===//
  9820. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  9821. return Success(E->getValue(), E);
  9822. }
  9823. bool VisitCastExpr(const CastExpr *E);
  9824. bool VisitUnaryOperator(const UnaryOperator *E);
  9825. bool VisitBinaryOperator(const BinaryOperator *E);
  9826. };
  9827. } // end anonymous namespace
  9828. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  9829. /// produce either the integer value or a pointer.
  9830. ///
  9831. /// GCC has a heinous extension which folds casts between pointer types and
  9832. /// pointer-sized integral types. We support this by allowing the evaluation of
  9833. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  9834. /// Some simple arithmetic on such values is supported (they are treated much
  9835. /// like char*).
  9836. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  9837. EvalInfo &Info) {
  9838. assert(!E->isValueDependent());
  9839. assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
  9840. return IntExprEvaluator(Info, Result).Visit(E);
  9841. }
  9842. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  9843. assert(!E->isValueDependent());
  9844. APValue Val;
  9845. if (!EvaluateIntegerOrLValue(E, Val, Info))
  9846. return false;
  9847. if (!Val.isInt()) {
  9848. // FIXME: It would be better to produce the diagnostic for casting
  9849. // a pointer to an integer.
  9850. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9851. return false;
  9852. }
  9853. Result = Val.getInt();
  9854. return true;
  9855. }
  9856. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  9857. APValue Evaluated = E->EvaluateInContext(
  9858. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  9859. return Success(Evaluated, E);
  9860. }
  9861. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  9862. EvalInfo &Info) {
  9863. assert(!E->isValueDependent());
  9864. if (E->getType()->isFixedPointType()) {
  9865. APValue Val;
  9866. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  9867. return false;
  9868. if (!Val.isFixedPoint())
  9869. return false;
  9870. Result = Val.getFixedPoint();
  9871. return true;
  9872. }
  9873. return false;
  9874. }
  9875. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  9876. EvalInfo &Info) {
  9877. assert(!E->isValueDependent());
  9878. if (E->getType()->isIntegerType()) {
  9879. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  9880. APSInt Val;
  9881. if (!EvaluateInteger(E, Val, Info))
  9882. return false;
  9883. Result = APFixedPoint(Val, FXSema);
  9884. return true;
  9885. } else if (E->getType()->isFixedPointType()) {
  9886. return EvaluateFixedPoint(E, Result, Info);
  9887. }
  9888. return false;
  9889. }
  9890. /// Check whether the given declaration can be directly converted to an integral
  9891. /// rvalue. If not, no diagnostic is produced; there are other things we can
  9892. /// try.
  9893. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  9894. // Enums are integer constant exprs.
  9895. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  9896. // Check for signedness/width mismatches between E type and ECD value.
  9897. bool SameSign = (ECD->getInitVal().isSigned()
  9898. == E->getType()->isSignedIntegerOrEnumerationType());
  9899. bool SameWidth = (ECD->getInitVal().getBitWidth()
  9900. == Info.Ctx.getIntWidth(E->getType()));
  9901. if (SameSign && SameWidth)
  9902. return Success(ECD->getInitVal(), E);
  9903. else {
  9904. // Get rid of mismatch (otherwise Success assertions will fail)
  9905. // by computing a new value matching the type of E.
  9906. llvm::APSInt Val = ECD->getInitVal();
  9907. if (!SameSign)
  9908. Val.setIsSigned(!ECD->getInitVal().isSigned());
  9909. if (!SameWidth)
  9910. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  9911. return Success(Val, E);
  9912. }
  9913. }
  9914. return false;
  9915. }
  9916. /// Values returned by __builtin_classify_type, chosen to match the values
  9917. /// produced by GCC's builtin.
  9918. enum class GCCTypeClass {
  9919. None = -1,
  9920. Void = 0,
  9921. Integer = 1,
  9922. // GCC reserves 2 for character types, but instead classifies them as
  9923. // integers.
  9924. Enum = 3,
  9925. Bool = 4,
  9926. Pointer = 5,
  9927. // GCC reserves 6 for references, but appears to never use it (because
  9928. // expressions never have reference type, presumably).
  9929. PointerToDataMember = 7,
  9930. RealFloat = 8,
  9931. Complex = 9,
  9932. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  9933. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  9934. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  9935. // uses 12 for that purpose, same as for a class or struct. Maybe it
  9936. // internally implements a pointer to member as a struct? Who knows.
  9937. PointerToMemberFunction = 12, // Not a bug, see above.
  9938. ClassOrStruct = 12,
  9939. Union = 13,
  9940. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  9941. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  9942. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  9943. // literals.
  9944. };
  9945. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  9946. /// as GCC.
  9947. static GCCTypeClass
  9948. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  9949. assert(!T->isDependentType() && "unexpected dependent type");
  9950. QualType CanTy = T.getCanonicalType();
  9951. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  9952. switch (CanTy->getTypeClass()) {
  9953. #define TYPE(ID, BASE)
  9954. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  9955. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  9956. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  9957. #include "clang/AST/TypeNodes.inc"
  9958. case Type::Auto:
  9959. case Type::DeducedTemplateSpecialization:
  9960. llvm_unreachable("unexpected non-canonical or dependent type");
  9961. case Type::Builtin:
  9962. switch (BT->getKind()) {
  9963. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  9964. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  9965. case BuiltinType::ID: return GCCTypeClass::Integer;
  9966. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  9967. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  9968. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  9969. case BuiltinType::ID: break;
  9970. #include "clang/AST/BuiltinTypes.def"
  9971. case BuiltinType::Void:
  9972. return GCCTypeClass::Void;
  9973. case BuiltinType::Bool:
  9974. return GCCTypeClass::Bool;
  9975. case BuiltinType::Char_U:
  9976. case BuiltinType::UChar:
  9977. case BuiltinType::WChar_U:
  9978. case BuiltinType::Char8:
  9979. case BuiltinType::Char16:
  9980. case BuiltinType::Char32:
  9981. case BuiltinType::UShort:
  9982. case BuiltinType::UInt:
  9983. case BuiltinType::ULong:
  9984. case BuiltinType::ULongLong:
  9985. case BuiltinType::UInt128:
  9986. return GCCTypeClass::Integer;
  9987. case BuiltinType::UShortAccum:
  9988. case BuiltinType::UAccum:
  9989. case BuiltinType::ULongAccum:
  9990. case BuiltinType::UShortFract:
  9991. case BuiltinType::UFract:
  9992. case BuiltinType::ULongFract:
  9993. case BuiltinType::SatUShortAccum:
  9994. case BuiltinType::SatUAccum:
  9995. case BuiltinType::SatULongAccum:
  9996. case BuiltinType::SatUShortFract:
  9997. case BuiltinType::SatUFract:
  9998. case BuiltinType::SatULongFract:
  9999. return GCCTypeClass::None;
  10000. case BuiltinType::NullPtr:
  10001. case BuiltinType::ObjCId:
  10002. case BuiltinType::ObjCClass:
  10003. case BuiltinType::ObjCSel:
  10004. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  10005. case BuiltinType::Id:
  10006. #include "clang/Basic/OpenCLImageTypes.def"
  10007. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  10008. case BuiltinType::Id:
  10009. #include "clang/Basic/OpenCLExtensionTypes.def"
  10010. case BuiltinType::OCLSampler:
  10011. case BuiltinType::OCLEvent:
  10012. case BuiltinType::OCLClkEvent:
  10013. case BuiltinType::OCLQueue:
  10014. case BuiltinType::OCLReserveID:
  10015. #define SVE_TYPE(Name, Id, SingletonId) \
  10016. case BuiltinType::Id:
  10017. #include "clang/Basic/AArch64SVEACLETypes.def"
  10018. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  10019. case BuiltinType::Id:
  10020. #include "clang/Basic/PPCTypes.def"
  10021. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  10022. #include "clang/Basic/RISCVVTypes.def"
  10023. return GCCTypeClass::None;
  10024. case BuiltinType::Dependent:
  10025. llvm_unreachable("unexpected dependent type");
  10026. };
  10027. llvm_unreachable("unexpected placeholder type");
  10028. case Type::Enum:
  10029. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  10030. case Type::Pointer:
  10031. case Type::ConstantArray:
  10032. case Type::VariableArray:
  10033. case Type::IncompleteArray:
  10034. case Type::FunctionNoProto:
  10035. case Type::FunctionProto:
  10036. return GCCTypeClass::Pointer;
  10037. case Type::MemberPointer:
  10038. return CanTy->isMemberDataPointerType()
  10039. ? GCCTypeClass::PointerToDataMember
  10040. : GCCTypeClass::PointerToMemberFunction;
  10041. case Type::Complex:
  10042. return GCCTypeClass::Complex;
  10043. case Type::Record:
  10044. return CanTy->isUnionType() ? GCCTypeClass::Union
  10045. : GCCTypeClass::ClassOrStruct;
  10046. case Type::Atomic:
  10047. // GCC classifies _Atomic T the same as T.
  10048. return EvaluateBuiltinClassifyType(
  10049. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  10050. case Type::BlockPointer:
  10051. case Type::Vector:
  10052. case Type::ExtVector:
  10053. case Type::ConstantMatrix:
  10054. case Type::ObjCObject:
  10055. case Type::ObjCInterface:
  10056. case Type::ObjCObjectPointer:
  10057. case Type::Pipe:
  10058. case Type::BitInt:
  10059. // GCC classifies vectors as None. We follow its lead and classify all
  10060. // other types that don't fit into the regular classification the same way.
  10061. return GCCTypeClass::None;
  10062. case Type::LValueReference:
  10063. case Type::RValueReference:
  10064. llvm_unreachable("invalid type for expression");
  10065. }
  10066. llvm_unreachable("unexpected type class");
  10067. }
  10068. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  10069. /// as GCC.
  10070. static GCCTypeClass
  10071. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  10072. // If no argument was supplied, default to None. This isn't
  10073. // ideal, however it is what gcc does.
  10074. if (E->getNumArgs() == 0)
  10075. return GCCTypeClass::None;
  10076. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  10077. // being an ICE, but still folds it to a constant using the type of the first
  10078. // argument.
  10079. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  10080. }
  10081. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  10082. /// __builtin_constant_p when applied to the given pointer.
  10083. ///
  10084. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  10085. /// or it points to the first character of a string literal.
  10086. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  10087. APValue::LValueBase Base = LV.getLValueBase();
  10088. if (Base.isNull()) {
  10089. // A null base is acceptable.
  10090. return true;
  10091. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  10092. if (!isa<StringLiteral>(E))
  10093. return false;
  10094. return LV.getLValueOffset().isZero();
  10095. } else if (Base.is<TypeInfoLValue>()) {
  10096. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  10097. // evaluate to true.
  10098. return true;
  10099. } else {
  10100. // Any other base is not constant enough for GCC.
  10101. return false;
  10102. }
  10103. }
  10104. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  10105. /// GCC as we can manage.
  10106. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  10107. // This evaluation is not permitted to have side-effects, so evaluate it in
  10108. // a speculative evaluation context.
  10109. SpeculativeEvaluationRAII SpeculativeEval(Info);
  10110. // Constant-folding is always enabled for the operand of __builtin_constant_p
  10111. // (even when the enclosing evaluation context otherwise requires a strict
  10112. // language-specific constant expression).
  10113. FoldConstant Fold(Info, true);
  10114. QualType ArgType = Arg->getType();
  10115. // __builtin_constant_p always has one operand. The rules which gcc follows
  10116. // are not precisely documented, but are as follows:
  10117. //
  10118. // - If the operand is of integral, floating, complex or enumeration type,
  10119. // and can be folded to a known value of that type, it returns 1.
  10120. // - If the operand can be folded to a pointer to the first character
  10121. // of a string literal (or such a pointer cast to an integral type)
  10122. // or to a null pointer or an integer cast to a pointer, it returns 1.
  10123. //
  10124. // Otherwise, it returns 0.
  10125. //
  10126. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  10127. // its support for this did not work prior to GCC 9 and is not yet well
  10128. // understood.
  10129. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  10130. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  10131. ArgType->isNullPtrType()) {
  10132. APValue V;
  10133. if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
  10134. Fold.keepDiagnostics();
  10135. return false;
  10136. }
  10137. // For a pointer (possibly cast to integer), there are special rules.
  10138. if (V.getKind() == APValue::LValue)
  10139. return EvaluateBuiltinConstantPForLValue(V);
  10140. // Otherwise, any constant value is good enough.
  10141. return V.hasValue();
  10142. }
  10143. // Anything else isn't considered to be sufficiently constant.
  10144. return false;
  10145. }
  10146. /// Retrieves the "underlying object type" of the given expression,
  10147. /// as used by __builtin_object_size.
  10148. static QualType getObjectType(APValue::LValueBase B) {
  10149. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  10150. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  10151. return VD->getType();
  10152. } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
  10153. if (isa<CompoundLiteralExpr>(E))
  10154. return E->getType();
  10155. } else if (B.is<TypeInfoLValue>()) {
  10156. return B.getTypeInfoType();
  10157. } else if (B.is<DynamicAllocLValue>()) {
  10158. return B.getDynamicAllocType();
  10159. }
  10160. return QualType();
  10161. }
  10162. /// A more selective version of E->IgnoreParenCasts for
  10163. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  10164. /// to change the type of E.
  10165. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  10166. ///
  10167. /// Always returns an RValue with a pointer representation.
  10168. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  10169. assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
  10170. auto *NoParens = E->IgnoreParens();
  10171. auto *Cast = dyn_cast<CastExpr>(NoParens);
  10172. if (Cast == nullptr)
  10173. return NoParens;
  10174. // We only conservatively allow a few kinds of casts, because this code is
  10175. // inherently a simple solution that seeks to support the common case.
  10176. auto CastKind = Cast->getCastKind();
  10177. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  10178. CastKind != CK_AddressSpaceConversion)
  10179. return NoParens;
  10180. auto *SubExpr = Cast->getSubExpr();
  10181. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
  10182. return NoParens;
  10183. return ignorePointerCastsAndParens(SubExpr);
  10184. }
  10185. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  10186. /// record layout. e.g.
  10187. /// struct { struct { int a, b; } fst, snd; } obj;
  10188. /// obj.fst // no
  10189. /// obj.snd // yes
  10190. /// obj.fst.a // no
  10191. /// obj.fst.b // no
  10192. /// obj.snd.a // no
  10193. /// obj.snd.b // yes
  10194. ///
  10195. /// Please note: this function is specialized for how __builtin_object_size
  10196. /// views "objects".
  10197. ///
  10198. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  10199. /// correct result, it will always return true.
  10200. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  10201. assert(!LVal.Designator.Invalid);
  10202. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  10203. const RecordDecl *Parent = FD->getParent();
  10204. Invalid = Parent->isInvalidDecl();
  10205. if (Invalid || Parent->isUnion())
  10206. return true;
  10207. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  10208. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  10209. };
  10210. auto &Base = LVal.getLValueBase();
  10211. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  10212. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  10213. bool Invalid;
  10214. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  10215. return Invalid;
  10216. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  10217. for (auto *FD : IFD->chain()) {
  10218. bool Invalid;
  10219. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  10220. return Invalid;
  10221. }
  10222. }
  10223. }
  10224. unsigned I = 0;
  10225. QualType BaseType = getType(Base);
  10226. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  10227. // If we don't know the array bound, conservatively assume we're looking at
  10228. // the final array element.
  10229. ++I;
  10230. if (BaseType->isIncompleteArrayType())
  10231. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  10232. else
  10233. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  10234. }
  10235. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  10236. const auto &Entry = LVal.Designator.Entries[I];
  10237. if (BaseType->isArrayType()) {
  10238. // Because __builtin_object_size treats arrays as objects, we can ignore
  10239. // the index iff this is the last array in the Designator.
  10240. if (I + 1 == E)
  10241. return true;
  10242. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  10243. uint64_t Index = Entry.getAsArrayIndex();
  10244. if (Index + 1 != CAT->getSize())
  10245. return false;
  10246. BaseType = CAT->getElementType();
  10247. } else if (BaseType->isAnyComplexType()) {
  10248. const auto *CT = BaseType->castAs<ComplexType>();
  10249. uint64_t Index = Entry.getAsArrayIndex();
  10250. if (Index != 1)
  10251. return false;
  10252. BaseType = CT->getElementType();
  10253. } else if (auto *FD = getAsField(Entry)) {
  10254. bool Invalid;
  10255. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  10256. return Invalid;
  10257. BaseType = FD->getType();
  10258. } else {
  10259. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  10260. return false;
  10261. }
  10262. }
  10263. return true;
  10264. }
  10265. /// Tests to see if the LValue has a user-specified designator (that isn't
  10266. /// necessarily valid). Note that this always returns 'true' if the LValue has
  10267. /// an unsized array as its first designator entry, because there's currently no
  10268. /// way to tell if the user typed *foo or foo[0].
  10269. static bool refersToCompleteObject(const LValue &LVal) {
  10270. if (LVal.Designator.Invalid)
  10271. return false;
  10272. if (!LVal.Designator.Entries.empty())
  10273. return LVal.Designator.isMostDerivedAnUnsizedArray();
  10274. if (!LVal.InvalidBase)
  10275. return true;
  10276. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  10277. // the LValueBase.
  10278. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  10279. return !E || !isa<MemberExpr>(E);
  10280. }
  10281. /// Attempts to detect a user writing into a piece of memory that's impossible
  10282. /// to figure out the size of by just using types.
  10283. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  10284. const SubobjectDesignator &Designator = LVal.Designator;
  10285. // Notes:
  10286. // - Users can only write off of the end when we have an invalid base. Invalid
  10287. // bases imply we don't know where the memory came from.
  10288. // - We used to be a bit more aggressive here; we'd only be conservative if
  10289. // the array at the end was flexible, or if it had 0 or 1 elements. This
  10290. // broke some common standard library extensions (PR30346), but was
  10291. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  10292. // with some sort of list. OTOH, it seems that GCC is always
  10293. // conservative with the last element in structs (if it's an array), so our
  10294. // current behavior is more compatible than an explicit list approach would
  10295. // be.
  10296. auto isFlexibleArrayMember = [&] {
  10297. using FAMKind = LangOptions::StrictFlexArraysLevelKind;
  10298. FAMKind StrictFlexArraysLevel =
  10299. Ctx.getLangOpts().getStrictFlexArraysLevel();
  10300. if (Designator.isMostDerivedAnUnsizedArray())
  10301. return true;
  10302. if (StrictFlexArraysLevel == FAMKind::Default)
  10303. return true;
  10304. if (Designator.getMostDerivedArraySize() == 0 &&
  10305. StrictFlexArraysLevel != FAMKind::IncompleteOnly)
  10306. return true;
  10307. if (Designator.getMostDerivedArraySize() == 1 &&
  10308. StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
  10309. return true;
  10310. return false;
  10311. };
  10312. return LVal.InvalidBase &&
  10313. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  10314. Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
  10315. isDesignatorAtObjectEnd(Ctx, LVal);
  10316. }
  10317. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  10318. /// Fails if the conversion would cause loss of precision.
  10319. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  10320. CharUnits &Result) {
  10321. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  10322. if (Int.ugt(CharUnitsMax))
  10323. return false;
  10324. Result = CharUnits::fromQuantity(Int.getZExtValue());
  10325. return true;
  10326. }
  10327. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  10328. /// determine how many bytes exist from the beginning of the object to either
  10329. /// the end of the current subobject, or the end of the object itself, depending
  10330. /// on what the LValue looks like + the value of Type.
  10331. ///
  10332. /// If this returns false, the value of Result is undefined.
  10333. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  10334. unsigned Type, const LValue &LVal,
  10335. CharUnits &EndOffset) {
  10336. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  10337. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  10338. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  10339. return false;
  10340. return HandleSizeof(Info, ExprLoc, Ty, Result);
  10341. };
  10342. // We want to evaluate the size of the entire object. This is a valid fallback
  10343. // for when Type=1 and the designator is invalid, because we're asked for an
  10344. // upper-bound.
  10345. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  10346. // Type=3 wants a lower bound, so we can't fall back to this.
  10347. if (Type == 3 && !DetermineForCompleteObject)
  10348. return false;
  10349. llvm::APInt APEndOffset;
  10350. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  10351. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  10352. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  10353. if (LVal.InvalidBase)
  10354. return false;
  10355. QualType BaseTy = getObjectType(LVal.getLValueBase());
  10356. return CheckedHandleSizeof(BaseTy, EndOffset);
  10357. }
  10358. // We want to evaluate the size of a subobject.
  10359. const SubobjectDesignator &Designator = LVal.Designator;
  10360. // The following is a moderately common idiom in C:
  10361. //
  10362. // struct Foo { int a; char c[1]; };
  10363. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  10364. // strcpy(&F->c[0], Bar);
  10365. //
  10366. // In order to not break too much legacy code, we need to support it.
  10367. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  10368. // If we can resolve this to an alloc_size call, we can hand that back,
  10369. // because we know for certain how many bytes there are to write to.
  10370. llvm::APInt APEndOffset;
  10371. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  10372. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  10373. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  10374. // If we cannot determine the size of the initial allocation, then we can't
  10375. // given an accurate upper-bound. However, we are still able to give
  10376. // conservative lower-bounds for Type=3.
  10377. if (Type == 1)
  10378. return false;
  10379. }
  10380. CharUnits BytesPerElem;
  10381. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  10382. return false;
  10383. // According to the GCC documentation, we want the size of the subobject
  10384. // denoted by the pointer. But that's not quite right -- what we actually
  10385. // want is the size of the immediately-enclosing array, if there is one.
  10386. int64_t ElemsRemaining;
  10387. if (Designator.MostDerivedIsArrayElement &&
  10388. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  10389. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  10390. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  10391. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  10392. } else {
  10393. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  10394. }
  10395. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  10396. return true;
  10397. }
  10398. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  10399. /// returns true and stores the result in @p Size.
  10400. ///
  10401. /// If @p WasError is non-null, this will report whether the failure to evaluate
  10402. /// is to be treated as an Error in IntExprEvaluator.
  10403. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  10404. EvalInfo &Info, uint64_t &Size) {
  10405. // Determine the denoted object.
  10406. LValue LVal;
  10407. {
  10408. // The operand of __builtin_object_size is never evaluated for side-effects.
  10409. // If there are any, but we can determine the pointed-to object anyway, then
  10410. // ignore the side-effects.
  10411. SpeculativeEvaluationRAII SpeculativeEval(Info);
  10412. IgnoreSideEffectsRAII Fold(Info);
  10413. if (E->isGLValue()) {
  10414. // It's possible for us to be given GLValues if we're called via
  10415. // Expr::tryEvaluateObjectSize.
  10416. APValue RVal;
  10417. if (!EvaluateAsRValue(Info, E, RVal))
  10418. return false;
  10419. LVal.setFrom(Info.Ctx, RVal);
  10420. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  10421. /*InvalidBaseOK=*/true))
  10422. return false;
  10423. }
  10424. // If we point to before the start of the object, there are no accessible
  10425. // bytes.
  10426. if (LVal.getLValueOffset().isNegative()) {
  10427. Size = 0;
  10428. return true;
  10429. }
  10430. CharUnits EndOffset;
  10431. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  10432. return false;
  10433. // If we've fallen outside of the end offset, just pretend there's nothing to
  10434. // write to/read from.
  10435. if (EndOffset <= LVal.getLValueOffset())
  10436. Size = 0;
  10437. else
  10438. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  10439. return true;
  10440. }
  10441. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  10442. if (!IsConstantEvaluatedBuiltinCall(E))
  10443. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10444. return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
  10445. }
  10446. static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
  10447. APValue &Val, APSInt &Alignment) {
  10448. QualType SrcTy = E->getArg(0)->getType();
  10449. if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
  10450. return false;
  10451. // Even though we are evaluating integer expressions we could get a pointer
  10452. // argument for the __builtin_is_aligned() case.
  10453. if (SrcTy->isPointerType()) {
  10454. LValue Ptr;
  10455. if (!EvaluatePointer(E->getArg(0), Ptr, Info))
  10456. return false;
  10457. Ptr.moveInto(Val);
  10458. } else if (!SrcTy->isIntegralOrEnumerationType()) {
  10459. Info.FFDiag(E->getArg(0));
  10460. return false;
  10461. } else {
  10462. APSInt SrcInt;
  10463. if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
  10464. return false;
  10465. assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
  10466. "Bit widths must be the same");
  10467. Val = APValue(SrcInt);
  10468. }
  10469. assert(Val.hasValue());
  10470. return true;
  10471. }
  10472. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  10473. unsigned BuiltinOp) {
  10474. switch (BuiltinOp) {
  10475. default:
  10476. return false;
  10477. case Builtin::BI__builtin_dynamic_object_size:
  10478. case Builtin::BI__builtin_object_size: {
  10479. // The type was checked when we built the expression.
  10480. unsigned Type =
  10481. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  10482. assert(Type <= 3 && "unexpected type");
  10483. uint64_t Size;
  10484. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  10485. return Success(Size, E);
  10486. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  10487. return Success((Type & 2) ? 0 : -1, E);
  10488. // Expression had no side effects, but we couldn't statically determine the
  10489. // size of the referenced object.
  10490. switch (Info.EvalMode) {
  10491. case EvalInfo::EM_ConstantExpression:
  10492. case EvalInfo::EM_ConstantFold:
  10493. case EvalInfo::EM_IgnoreSideEffects:
  10494. // Leave it to IR generation.
  10495. return Error(E);
  10496. case EvalInfo::EM_ConstantExpressionUnevaluated:
  10497. // Reduce it to a constant now.
  10498. return Success((Type & 2) ? 0 : -1, E);
  10499. }
  10500. llvm_unreachable("unexpected EvalMode");
  10501. }
  10502. case Builtin::BI__builtin_os_log_format_buffer_size: {
  10503. analyze_os_log::OSLogBufferLayout Layout;
  10504. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  10505. return Success(Layout.size().getQuantity(), E);
  10506. }
  10507. case Builtin::BI__builtin_is_aligned: {
  10508. APValue Src;
  10509. APSInt Alignment;
  10510. if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
  10511. return false;
  10512. if (Src.isLValue()) {
  10513. // If we evaluated a pointer, check the minimum known alignment.
  10514. LValue Ptr;
  10515. Ptr.setFrom(Info.Ctx, Src);
  10516. CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
  10517. CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
  10518. // We can return true if the known alignment at the computed offset is
  10519. // greater than the requested alignment.
  10520. assert(PtrAlign.isPowerOfTwo());
  10521. assert(Alignment.isPowerOf2());
  10522. if (PtrAlign.getQuantity() >= Alignment)
  10523. return Success(1, E);
  10524. // If the alignment is not known to be sufficient, some cases could still
  10525. // be aligned at run time. However, if the requested alignment is less or
  10526. // equal to the base alignment and the offset is not aligned, we know that
  10527. // the run-time value can never be aligned.
  10528. if (BaseAlignment.getQuantity() >= Alignment &&
  10529. PtrAlign.getQuantity() < Alignment)
  10530. return Success(0, E);
  10531. // Otherwise we can't infer whether the value is sufficiently aligned.
  10532. // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
  10533. // in cases where we can't fully evaluate the pointer.
  10534. Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
  10535. << Alignment;
  10536. return false;
  10537. }
  10538. assert(Src.isInt());
  10539. return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
  10540. }
  10541. case Builtin::BI__builtin_align_up: {
  10542. APValue Src;
  10543. APSInt Alignment;
  10544. if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
  10545. return false;
  10546. if (!Src.isInt())
  10547. return Error(E);
  10548. APSInt AlignedVal =
  10549. APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
  10550. Src.getInt().isUnsigned());
  10551. assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
  10552. return Success(AlignedVal, E);
  10553. }
  10554. case Builtin::BI__builtin_align_down: {
  10555. APValue Src;
  10556. APSInt Alignment;
  10557. if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
  10558. return false;
  10559. if (!Src.isInt())
  10560. return Error(E);
  10561. APSInt AlignedVal =
  10562. APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
  10563. assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
  10564. return Success(AlignedVal, E);
  10565. }
  10566. case Builtin::BI__builtin_bitreverse8:
  10567. case Builtin::BI__builtin_bitreverse16:
  10568. case Builtin::BI__builtin_bitreverse32:
  10569. case Builtin::BI__builtin_bitreverse64: {
  10570. APSInt Val;
  10571. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10572. return false;
  10573. return Success(Val.reverseBits(), E);
  10574. }
  10575. case Builtin::BI__builtin_bswap16:
  10576. case Builtin::BI__builtin_bswap32:
  10577. case Builtin::BI__builtin_bswap64: {
  10578. APSInt Val;
  10579. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10580. return false;
  10581. return Success(Val.byteSwap(), E);
  10582. }
  10583. case Builtin::BI__builtin_classify_type:
  10584. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  10585. case Builtin::BI__builtin_clrsb:
  10586. case Builtin::BI__builtin_clrsbl:
  10587. case Builtin::BI__builtin_clrsbll: {
  10588. APSInt Val;
  10589. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10590. return false;
  10591. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  10592. }
  10593. case Builtin::BI__builtin_clz:
  10594. case Builtin::BI__builtin_clzl:
  10595. case Builtin::BI__builtin_clzll:
  10596. case Builtin::BI__builtin_clzs: {
  10597. APSInt Val;
  10598. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10599. return false;
  10600. if (!Val)
  10601. return Error(E);
  10602. return Success(Val.countLeadingZeros(), E);
  10603. }
  10604. case Builtin::BI__builtin_constant_p: {
  10605. const Expr *Arg = E->getArg(0);
  10606. if (EvaluateBuiltinConstantP(Info, Arg))
  10607. return Success(true, E);
  10608. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  10609. // Outside a constant context, eagerly evaluate to false in the presence
  10610. // of side-effects in order to avoid -Wunsequenced false-positives in
  10611. // a branch on __builtin_constant_p(expr).
  10612. return Success(false, E);
  10613. }
  10614. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10615. return false;
  10616. }
  10617. case Builtin::BI__builtin_is_constant_evaluated: {
  10618. const auto *Callee = Info.CurrentCall->getCallee();
  10619. if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
  10620. (Info.CallStackDepth == 1 ||
  10621. (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
  10622. Callee->getIdentifier() &&
  10623. Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
  10624. // FIXME: Find a better way to avoid duplicated diagnostics.
  10625. if (Info.EvalStatus.Diag)
  10626. Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
  10627. : Info.CurrentCall->CallLoc,
  10628. diag::warn_is_constant_evaluated_always_true_constexpr)
  10629. << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
  10630. : "std::is_constant_evaluated");
  10631. }
  10632. return Success(Info.InConstantContext, E);
  10633. }
  10634. case Builtin::BI__builtin_ctz:
  10635. case Builtin::BI__builtin_ctzl:
  10636. case Builtin::BI__builtin_ctzll:
  10637. case Builtin::BI__builtin_ctzs: {
  10638. APSInt Val;
  10639. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10640. return false;
  10641. if (!Val)
  10642. return Error(E);
  10643. return Success(Val.countTrailingZeros(), E);
  10644. }
  10645. case Builtin::BI__builtin_eh_return_data_regno: {
  10646. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  10647. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  10648. return Success(Operand, E);
  10649. }
  10650. case Builtin::BI__builtin_expect:
  10651. case Builtin::BI__builtin_expect_with_probability:
  10652. return Visit(E->getArg(0));
  10653. case Builtin::BI__builtin_ffs:
  10654. case Builtin::BI__builtin_ffsl:
  10655. case Builtin::BI__builtin_ffsll: {
  10656. APSInt Val;
  10657. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10658. return false;
  10659. unsigned N = Val.countTrailingZeros();
  10660. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  10661. }
  10662. case Builtin::BI__builtin_fpclassify: {
  10663. APFloat Val(0.0);
  10664. if (!EvaluateFloat(E->getArg(5), Val, Info))
  10665. return false;
  10666. unsigned Arg;
  10667. switch (Val.getCategory()) {
  10668. case APFloat::fcNaN: Arg = 0; break;
  10669. case APFloat::fcInfinity: Arg = 1; break;
  10670. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  10671. case APFloat::fcZero: Arg = 4; break;
  10672. }
  10673. return Visit(E->getArg(Arg));
  10674. }
  10675. case Builtin::BI__builtin_isinf_sign: {
  10676. APFloat Val(0.0);
  10677. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10678. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  10679. }
  10680. case Builtin::BI__builtin_isinf: {
  10681. APFloat Val(0.0);
  10682. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10683. Success(Val.isInfinity() ? 1 : 0, E);
  10684. }
  10685. case Builtin::BI__builtin_isfinite: {
  10686. APFloat Val(0.0);
  10687. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10688. Success(Val.isFinite() ? 1 : 0, E);
  10689. }
  10690. case Builtin::BI__builtin_isnan: {
  10691. APFloat Val(0.0);
  10692. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10693. Success(Val.isNaN() ? 1 : 0, E);
  10694. }
  10695. case Builtin::BI__builtin_isnormal: {
  10696. APFloat Val(0.0);
  10697. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10698. Success(Val.isNormal() ? 1 : 0, E);
  10699. }
  10700. case Builtin::BI__builtin_parity:
  10701. case Builtin::BI__builtin_parityl:
  10702. case Builtin::BI__builtin_parityll: {
  10703. APSInt Val;
  10704. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10705. return false;
  10706. return Success(Val.countPopulation() % 2, E);
  10707. }
  10708. case Builtin::BI__builtin_popcount:
  10709. case Builtin::BI__builtin_popcountl:
  10710. case Builtin::BI__builtin_popcountll: {
  10711. APSInt Val;
  10712. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10713. return false;
  10714. return Success(Val.countPopulation(), E);
  10715. }
  10716. case Builtin::BI__builtin_rotateleft8:
  10717. case Builtin::BI__builtin_rotateleft16:
  10718. case Builtin::BI__builtin_rotateleft32:
  10719. case Builtin::BI__builtin_rotateleft64:
  10720. case Builtin::BI_rotl8: // Microsoft variants of rotate right
  10721. case Builtin::BI_rotl16:
  10722. case Builtin::BI_rotl:
  10723. case Builtin::BI_lrotl:
  10724. case Builtin::BI_rotl64: {
  10725. APSInt Val, Amt;
  10726. if (!EvaluateInteger(E->getArg(0), Val, Info) ||
  10727. !EvaluateInteger(E->getArg(1), Amt, Info))
  10728. return false;
  10729. return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
  10730. }
  10731. case Builtin::BI__builtin_rotateright8:
  10732. case Builtin::BI__builtin_rotateright16:
  10733. case Builtin::BI__builtin_rotateright32:
  10734. case Builtin::BI__builtin_rotateright64:
  10735. case Builtin::BI_rotr8: // Microsoft variants of rotate right
  10736. case Builtin::BI_rotr16:
  10737. case Builtin::BI_rotr:
  10738. case Builtin::BI_lrotr:
  10739. case Builtin::BI_rotr64: {
  10740. APSInt Val, Amt;
  10741. if (!EvaluateInteger(E->getArg(0), Val, Info) ||
  10742. !EvaluateInteger(E->getArg(1), Amt, Info))
  10743. return false;
  10744. return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
  10745. }
  10746. case Builtin::BIstrlen:
  10747. case Builtin::BIwcslen:
  10748. // A call to strlen is not a constant expression.
  10749. if (Info.getLangOpts().CPlusPlus11)
  10750. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  10751. << /*isConstexpr*/ 0 << /*isConstructor*/ 0
  10752. << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
  10753. else
  10754. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10755. [[fallthrough]];
  10756. case Builtin::BI__builtin_strlen:
  10757. case Builtin::BI__builtin_wcslen: {
  10758. // As an extension, we support __builtin_strlen() as a constant expression,
  10759. // and support folding strlen() to a constant.
  10760. uint64_t StrLen;
  10761. if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
  10762. return Success(StrLen, E);
  10763. return false;
  10764. }
  10765. case Builtin::BIstrcmp:
  10766. case Builtin::BIwcscmp:
  10767. case Builtin::BIstrncmp:
  10768. case Builtin::BIwcsncmp:
  10769. case Builtin::BImemcmp:
  10770. case Builtin::BIbcmp:
  10771. case Builtin::BIwmemcmp:
  10772. // A call to strlen is not a constant expression.
  10773. if (Info.getLangOpts().CPlusPlus11)
  10774. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  10775. << /*isConstexpr*/ 0 << /*isConstructor*/ 0
  10776. << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
  10777. else
  10778. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10779. [[fallthrough]];
  10780. case Builtin::BI__builtin_strcmp:
  10781. case Builtin::BI__builtin_wcscmp:
  10782. case Builtin::BI__builtin_strncmp:
  10783. case Builtin::BI__builtin_wcsncmp:
  10784. case Builtin::BI__builtin_memcmp:
  10785. case Builtin::BI__builtin_bcmp:
  10786. case Builtin::BI__builtin_wmemcmp: {
  10787. LValue String1, String2;
  10788. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  10789. !EvaluatePointer(E->getArg(1), String2, Info))
  10790. return false;
  10791. uint64_t MaxLength = uint64_t(-1);
  10792. if (BuiltinOp != Builtin::BIstrcmp &&
  10793. BuiltinOp != Builtin::BIwcscmp &&
  10794. BuiltinOp != Builtin::BI__builtin_strcmp &&
  10795. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  10796. APSInt N;
  10797. if (!EvaluateInteger(E->getArg(2), N, Info))
  10798. return false;
  10799. MaxLength = N.getExtValue();
  10800. }
  10801. // Empty substrings compare equal by definition.
  10802. if (MaxLength == 0u)
  10803. return Success(0, E);
  10804. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  10805. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  10806. String1.Designator.Invalid || String2.Designator.Invalid)
  10807. return false;
  10808. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  10809. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  10810. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  10811. BuiltinOp == Builtin::BIbcmp ||
  10812. BuiltinOp == Builtin::BI__builtin_memcmp ||
  10813. BuiltinOp == Builtin::BI__builtin_bcmp;
  10814. assert(IsRawByte ||
  10815. (Info.Ctx.hasSameUnqualifiedType(
  10816. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  10817. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  10818. // For memcmp, allow comparing any arrays of '[[un]signed] char' or
  10819. // 'char8_t', but no other types.
  10820. if (IsRawByte &&
  10821. !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
  10822. // FIXME: Consider using our bit_cast implementation to support this.
  10823. Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
  10824. << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
  10825. << CharTy1 << CharTy2;
  10826. return false;
  10827. }
  10828. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  10829. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  10830. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  10831. Char1.isInt() && Char2.isInt();
  10832. };
  10833. const auto &AdvanceElems = [&] {
  10834. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  10835. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  10836. };
  10837. bool StopAtNull =
  10838. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  10839. BuiltinOp != Builtin::BIwmemcmp &&
  10840. BuiltinOp != Builtin::BI__builtin_memcmp &&
  10841. BuiltinOp != Builtin::BI__builtin_bcmp &&
  10842. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  10843. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  10844. BuiltinOp == Builtin::BIwcsncmp ||
  10845. BuiltinOp == Builtin::BIwmemcmp ||
  10846. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  10847. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  10848. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  10849. for (; MaxLength; --MaxLength) {
  10850. APValue Char1, Char2;
  10851. if (!ReadCurElems(Char1, Char2))
  10852. return false;
  10853. if (Char1.getInt().ne(Char2.getInt())) {
  10854. if (IsWide) // wmemcmp compares with wchar_t signedness.
  10855. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  10856. // memcmp always compares unsigned chars.
  10857. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  10858. }
  10859. if (StopAtNull && !Char1.getInt())
  10860. return Success(0, E);
  10861. assert(!(StopAtNull && !Char2.getInt()));
  10862. if (!AdvanceElems())
  10863. return false;
  10864. }
  10865. // We hit the strncmp / memcmp limit.
  10866. return Success(0, E);
  10867. }
  10868. case Builtin::BI__atomic_always_lock_free:
  10869. case Builtin::BI__atomic_is_lock_free:
  10870. case Builtin::BI__c11_atomic_is_lock_free: {
  10871. APSInt SizeVal;
  10872. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  10873. return false;
  10874. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  10875. // of two less than or equal to the maximum inline atomic width, we know it
  10876. // is lock-free. If the size isn't a power of two, or greater than the
  10877. // maximum alignment where we promote atomics, we know it is not lock-free
  10878. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  10879. // the answer can only be determined at runtime; for example, 16-byte
  10880. // atomics have lock-free implementations on some, but not all,
  10881. // x86-64 processors.
  10882. // Check power-of-two.
  10883. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  10884. if (Size.isPowerOfTwo()) {
  10885. // Check against inlining width.
  10886. unsigned InlineWidthBits =
  10887. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  10888. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  10889. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  10890. Size == CharUnits::One() ||
  10891. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  10892. Expr::NPC_NeverValueDependent))
  10893. // OK, we will inline appropriately-aligned operations of this size,
  10894. // and _Atomic(T) is appropriately-aligned.
  10895. return Success(1, E);
  10896. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  10897. castAs<PointerType>()->getPointeeType();
  10898. if (!PointeeType->isIncompleteType() &&
  10899. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  10900. // OK, we will inline operations on this object.
  10901. return Success(1, E);
  10902. }
  10903. }
  10904. }
  10905. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  10906. Success(0, E) : Error(E);
  10907. }
  10908. case Builtin::BI__builtin_add_overflow:
  10909. case Builtin::BI__builtin_sub_overflow:
  10910. case Builtin::BI__builtin_mul_overflow:
  10911. case Builtin::BI__builtin_sadd_overflow:
  10912. case Builtin::BI__builtin_uadd_overflow:
  10913. case Builtin::BI__builtin_uaddl_overflow:
  10914. case Builtin::BI__builtin_uaddll_overflow:
  10915. case Builtin::BI__builtin_usub_overflow:
  10916. case Builtin::BI__builtin_usubl_overflow:
  10917. case Builtin::BI__builtin_usubll_overflow:
  10918. case Builtin::BI__builtin_umul_overflow:
  10919. case Builtin::BI__builtin_umull_overflow:
  10920. case Builtin::BI__builtin_umulll_overflow:
  10921. case Builtin::BI__builtin_saddl_overflow:
  10922. case Builtin::BI__builtin_saddll_overflow:
  10923. case Builtin::BI__builtin_ssub_overflow:
  10924. case Builtin::BI__builtin_ssubl_overflow:
  10925. case Builtin::BI__builtin_ssubll_overflow:
  10926. case Builtin::BI__builtin_smul_overflow:
  10927. case Builtin::BI__builtin_smull_overflow:
  10928. case Builtin::BI__builtin_smulll_overflow: {
  10929. LValue ResultLValue;
  10930. APSInt LHS, RHS;
  10931. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  10932. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  10933. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  10934. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  10935. return false;
  10936. APSInt Result;
  10937. bool DidOverflow = false;
  10938. // If the types don't have to match, enlarge all 3 to the largest of them.
  10939. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  10940. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  10941. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  10942. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  10943. ResultType->isSignedIntegerOrEnumerationType();
  10944. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  10945. ResultType->isSignedIntegerOrEnumerationType();
  10946. uint64_t LHSSize = LHS.getBitWidth();
  10947. uint64_t RHSSize = RHS.getBitWidth();
  10948. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  10949. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  10950. // Add an additional bit if the signedness isn't uniformly agreed to. We
  10951. // could do this ONLY if there is a signed and an unsigned that both have
  10952. // MaxBits, but the code to check that is pretty nasty. The issue will be
  10953. // caught in the shrink-to-result later anyway.
  10954. if (IsSigned && !AllSigned)
  10955. ++MaxBits;
  10956. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  10957. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  10958. Result = APSInt(MaxBits, !IsSigned);
  10959. }
  10960. // Find largest int.
  10961. switch (BuiltinOp) {
  10962. default:
  10963. llvm_unreachable("Invalid value for BuiltinOp");
  10964. case Builtin::BI__builtin_add_overflow:
  10965. case Builtin::BI__builtin_sadd_overflow:
  10966. case Builtin::BI__builtin_saddl_overflow:
  10967. case Builtin::BI__builtin_saddll_overflow:
  10968. case Builtin::BI__builtin_uadd_overflow:
  10969. case Builtin::BI__builtin_uaddl_overflow:
  10970. case Builtin::BI__builtin_uaddll_overflow:
  10971. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  10972. : LHS.uadd_ov(RHS, DidOverflow);
  10973. break;
  10974. case Builtin::BI__builtin_sub_overflow:
  10975. case Builtin::BI__builtin_ssub_overflow:
  10976. case Builtin::BI__builtin_ssubl_overflow:
  10977. case Builtin::BI__builtin_ssubll_overflow:
  10978. case Builtin::BI__builtin_usub_overflow:
  10979. case Builtin::BI__builtin_usubl_overflow:
  10980. case Builtin::BI__builtin_usubll_overflow:
  10981. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  10982. : LHS.usub_ov(RHS, DidOverflow);
  10983. break;
  10984. case Builtin::BI__builtin_mul_overflow:
  10985. case Builtin::BI__builtin_smul_overflow:
  10986. case Builtin::BI__builtin_smull_overflow:
  10987. case Builtin::BI__builtin_smulll_overflow:
  10988. case Builtin::BI__builtin_umul_overflow:
  10989. case Builtin::BI__builtin_umull_overflow:
  10990. case Builtin::BI__builtin_umulll_overflow:
  10991. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  10992. : LHS.umul_ov(RHS, DidOverflow);
  10993. break;
  10994. }
  10995. // In the case where multiple sizes are allowed, truncate and see if
  10996. // the values are the same.
  10997. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  10998. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  10999. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  11000. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  11001. // since it will give us the behavior of a TruncOrSelf in the case where
  11002. // its parameter <= its size. We previously set Result to be at least the
  11003. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  11004. // will work exactly like TruncOrSelf.
  11005. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  11006. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  11007. if (!APSInt::isSameValue(Temp, Result))
  11008. DidOverflow = true;
  11009. Result = Temp;
  11010. }
  11011. APValue APV{Result};
  11012. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  11013. return false;
  11014. return Success(DidOverflow, E);
  11015. }
  11016. }
  11017. }
  11018. /// Determine whether this is a pointer past the end of the complete
  11019. /// object referred to by the lvalue.
  11020. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  11021. const LValue &LV) {
  11022. // A null pointer can be viewed as being "past the end" but we don't
  11023. // choose to look at it that way here.
  11024. if (!LV.getLValueBase())
  11025. return false;
  11026. // If the designator is valid and refers to a subobject, we're not pointing
  11027. // past the end.
  11028. if (!LV.getLValueDesignator().Invalid &&
  11029. !LV.getLValueDesignator().isOnePastTheEnd())
  11030. return false;
  11031. // A pointer to an incomplete type might be past-the-end if the type's size is
  11032. // zero. We cannot tell because the type is incomplete.
  11033. QualType Ty = getType(LV.getLValueBase());
  11034. if (Ty->isIncompleteType())
  11035. return true;
  11036. // We're a past-the-end pointer if we point to the byte after the object,
  11037. // no matter what our type or path is.
  11038. auto Size = Ctx.getTypeSizeInChars(Ty);
  11039. return LV.getLValueOffset() == Size;
  11040. }
  11041. namespace {
  11042. /// Data recursive integer evaluator of certain binary operators.
  11043. ///
  11044. /// We use a data recursive algorithm for binary operators so that we are able
  11045. /// to handle extreme cases of chained binary operators without causing stack
  11046. /// overflow.
  11047. class DataRecursiveIntBinOpEvaluator {
  11048. struct EvalResult {
  11049. APValue Val;
  11050. bool Failed;
  11051. EvalResult() : Failed(false) { }
  11052. void swap(EvalResult &RHS) {
  11053. Val.swap(RHS.Val);
  11054. Failed = RHS.Failed;
  11055. RHS.Failed = false;
  11056. }
  11057. };
  11058. struct Job {
  11059. const Expr *E;
  11060. EvalResult LHSResult; // meaningful only for binary operator expression.
  11061. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  11062. Job() = default;
  11063. Job(Job &&) = default;
  11064. void startSpeculativeEval(EvalInfo &Info) {
  11065. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  11066. }
  11067. private:
  11068. SpeculativeEvaluationRAII SpecEvalRAII;
  11069. };
  11070. SmallVector<Job, 16> Queue;
  11071. IntExprEvaluator &IntEval;
  11072. EvalInfo &Info;
  11073. APValue &FinalResult;
  11074. public:
  11075. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  11076. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  11077. /// True if \param E is a binary operator that we are going to handle
  11078. /// data recursively.
  11079. /// We handle binary operators that are comma, logical, or that have operands
  11080. /// with integral or enumeration type.
  11081. static bool shouldEnqueue(const BinaryOperator *E) {
  11082. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  11083. (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
  11084. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  11085. E->getRHS()->getType()->isIntegralOrEnumerationType());
  11086. }
  11087. bool Traverse(const BinaryOperator *E) {
  11088. enqueue(E);
  11089. EvalResult PrevResult;
  11090. while (!Queue.empty())
  11091. process(PrevResult);
  11092. if (PrevResult.Failed) return false;
  11093. FinalResult.swap(PrevResult.Val);
  11094. return true;
  11095. }
  11096. private:
  11097. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  11098. return IntEval.Success(Value, E, Result);
  11099. }
  11100. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  11101. return IntEval.Success(Value, E, Result);
  11102. }
  11103. bool Error(const Expr *E) {
  11104. return IntEval.Error(E);
  11105. }
  11106. bool Error(const Expr *E, diag::kind D) {
  11107. return IntEval.Error(E, D);
  11108. }
  11109. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  11110. return Info.CCEDiag(E, D);
  11111. }
  11112. // Returns true if visiting the RHS is necessary, false otherwise.
  11113. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  11114. bool &SuppressRHSDiags);
  11115. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  11116. const BinaryOperator *E, APValue &Result);
  11117. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  11118. Result.Failed = !Evaluate(Result.Val, Info, E);
  11119. if (Result.Failed)
  11120. Result.Val = APValue();
  11121. }
  11122. void process(EvalResult &Result);
  11123. void enqueue(const Expr *E) {
  11124. E = E->IgnoreParens();
  11125. Queue.resize(Queue.size()+1);
  11126. Queue.back().E = E;
  11127. Queue.back().Kind = Job::AnyExprKind;
  11128. }
  11129. };
  11130. }
  11131. bool DataRecursiveIntBinOpEvaluator::
  11132. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  11133. bool &SuppressRHSDiags) {
  11134. if (E->getOpcode() == BO_Comma) {
  11135. // Ignore LHS but note if we could not evaluate it.
  11136. if (LHSResult.Failed)
  11137. return Info.noteSideEffect();
  11138. return true;
  11139. }
  11140. if (E->isLogicalOp()) {
  11141. bool LHSAsBool;
  11142. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  11143. // We were able to evaluate the LHS, see if we can get away with not
  11144. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  11145. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  11146. Success(LHSAsBool, E, LHSResult.Val);
  11147. return false; // Ignore RHS
  11148. }
  11149. } else {
  11150. LHSResult.Failed = true;
  11151. // Since we weren't able to evaluate the left hand side, it
  11152. // might have had side effects.
  11153. if (!Info.noteSideEffect())
  11154. return false;
  11155. // We can't evaluate the LHS; however, sometimes the result
  11156. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  11157. // Don't ignore RHS and suppress diagnostics from this arm.
  11158. SuppressRHSDiags = true;
  11159. }
  11160. return true;
  11161. }
  11162. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  11163. E->getRHS()->getType()->isIntegralOrEnumerationType());
  11164. if (LHSResult.Failed && !Info.noteFailure())
  11165. return false; // Ignore RHS;
  11166. return true;
  11167. }
  11168. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  11169. bool IsSub) {
  11170. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  11171. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  11172. // offsets.
  11173. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  11174. CharUnits &Offset = LVal.getLValueOffset();
  11175. uint64_t Offset64 = Offset.getQuantity();
  11176. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  11177. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  11178. : Offset64 + Index64);
  11179. }
  11180. bool DataRecursiveIntBinOpEvaluator::
  11181. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  11182. const BinaryOperator *E, APValue &Result) {
  11183. if (E->getOpcode() == BO_Comma) {
  11184. if (RHSResult.Failed)
  11185. return false;
  11186. Result = RHSResult.Val;
  11187. return true;
  11188. }
  11189. if (E->isLogicalOp()) {
  11190. bool lhsResult, rhsResult;
  11191. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  11192. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  11193. if (LHSIsOK) {
  11194. if (RHSIsOK) {
  11195. if (E->getOpcode() == BO_LOr)
  11196. return Success(lhsResult || rhsResult, E, Result);
  11197. else
  11198. return Success(lhsResult && rhsResult, E, Result);
  11199. }
  11200. } else {
  11201. if (RHSIsOK) {
  11202. // We can't evaluate the LHS; however, sometimes the result
  11203. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  11204. if (rhsResult == (E->getOpcode() == BO_LOr))
  11205. return Success(rhsResult, E, Result);
  11206. }
  11207. }
  11208. return false;
  11209. }
  11210. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  11211. E->getRHS()->getType()->isIntegralOrEnumerationType());
  11212. if (LHSResult.Failed || RHSResult.Failed)
  11213. return false;
  11214. const APValue &LHSVal = LHSResult.Val;
  11215. const APValue &RHSVal = RHSResult.Val;
  11216. // Handle cases like (unsigned long)&a + 4.
  11217. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  11218. Result = LHSVal;
  11219. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  11220. return true;
  11221. }
  11222. // Handle cases like 4 + (unsigned long)&a
  11223. if (E->getOpcode() == BO_Add &&
  11224. RHSVal.isLValue() && LHSVal.isInt()) {
  11225. Result = RHSVal;
  11226. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  11227. return true;
  11228. }
  11229. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  11230. // Handle (intptr_t)&&A - (intptr_t)&&B.
  11231. if (!LHSVal.getLValueOffset().isZero() ||
  11232. !RHSVal.getLValueOffset().isZero())
  11233. return false;
  11234. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  11235. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  11236. if (!LHSExpr || !RHSExpr)
  11237. return false;
  11238. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  11239. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  11240. if (!LHSAddrExpr || !RHSAddrExpr)
  11241. return false;
  11242. // Make sure both labels come from the same function.
  11243. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  11244. RHSAddrExpr->getLabel()->getDeclContext())
  11245. return false;
  11246. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  11247. return true;
  11248. }
  11249. // All the remaining cases expect both operands to be an integer
  11250. if (!LHSVal.isInt() || !RHSVal.isInt())
  11251. return Error(E);
  11252. // Set up the width and signedness manually, in case it can't be deduced
  11253. // from the operation we're performing.
  11254. // FIXME: Don't do this in the cases where we can deduce it.
  11255. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  11256. E->getType()->isUnsignedIntegerOrEnumerationType());
  11257. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  11258. RHSVal.getInt(), Value))
  11259. return false;
  11260. return Success(Value, E, Result);
  11261. }
  11262. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  11263. Job &job = Queue.back();
  11264. switch (job.Kind) {
  11265. case Job::AnyExprKind: {
  11266. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  11267. if (shouldEnqueue(Bop)) {
  11268. job.Kind = Job::BinOpKind;
  11269. enqueue(Bop->getLHS());
  11270. return;
  11271. }
  11272. }
  11273. EvaluateExpr(job.E, Result);
  11274. Queue.pop_back();
  11275. return;
  11276. }
  11277. case Job::BinOpKind: {
  11278. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  11279. bool SuppressRHSDiags = false;
  11280. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  11281. Queue.pop_back();
  11282. return;
  11283. }
  11284. if (SuppressRHSDiags)
  11285. job.startSpeculativeEval(Info);
  11286. job.LHSResult.swap(Result);
  11287. job.Kind = Job::BinOpVisitedLHSKind;
  11288. enqueue(Bop->getRHS());
  11289. return;
  11290. }
  11291. case Job::BinOpVisitedLHSKind: {
  11292. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  11293. EvalResult RHS;
  11294. RHS.swap(Result);
  11295. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  11296. Queue.pop_back();
  11297. return;
  11298. }
  11299. }
  11300. llvm_unreachable("Invalid Job::Kind!");
  11301. }
  11302. namespace {
  11303. enum class CmpResult {
  11304. Unequal,
  11305. Less,
  11306. Equal,
  11307. Greater,
  11308. Unordered,
  11309. };
  11310. }
  11311. template <class SuccessCB, class AfterCB>
  11312. static bool
  11313. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  11314. SuccessCB &&Success, AfterCB &&DoAfter) {
  11315. assert(!E->isValueDependent());
  11316. assert(E->isComparisonOp() && "expected comparison operator");
  11317. assert((E->getOpcode() == BO_Cmp ||
  11318. E->getType()->isIntegralOrEnumerationType()) &&
  11319. "unsupported binary expression evaluation");
  11320. auto Error = [&](const Expr *E) {
  11321. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  11322. return false;
  11323. };
  11324. bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
  11325. bool IsEquality = E->isEqualityOp();
  11326. QualType LHSTy = E->getLHS()->getType();
  11327. QualType RHSTy = E->getRHS()->getType();
  11328. if (LHSTy->isIntegralOrEnumerationType() &&
  11329. RHSTy->isIntegralOrEnumerationType()) {
  11330. APSInt LHS, RHS;
  11331. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  11332. if (!LHSOK && !Info.noteFailure())
  11333. return false;
  11334. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  11335. return false;
  11336. if (LHS < RHS)
  11337. return Success(CmpResult::Less, E);
  11338. if (LHS > RHS)
  11339. return Success(CmpResult::Greater, E);
  11340. return Success(CmpResult::Equal, E);
  11341. }
  11342. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  11343. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  11344. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  11345. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  11346. if (!LHSOK && !Info.noteFailure())
  11347. return false;
  11348. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  11349. return false;
  11350. if (LHSFX < RHSFX)
  11351. return Success(CmpResult::Less, E);
  11352. if (LHSFX > RHSFX)
  11353. return Success(CmpResult::Greater, E);
  11354. return Success(CmpResult::Equal, E);
  11355. }
  11356. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  11357. ComplexValue LHS, RHS;
  11358. bool LHSOK;
  11359. if (E->isAssignmentOp()) {
  11360. LValue LV;
  11361. EvaluateLValue(E->getLHS(), LV, Info);
  11362. LHSOK = false;
  11363. } else if (LHSTy->isRealFloatingType()) {
  11364. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  11365. if (LHSOK) {
  11366. LHS.makeComplexFloat();
  11367. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  11368. }
  11369. } else {
  11370. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  11371. }
  11372. if (!LHSOK && !Info.noteFailure())
  11373. return false;
  11374. if (E->getRHS()->getType()->isRealFloatingType()) {
  11375. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  11376. return false;
  11377. RHS.makeComplexFloat();
  11378. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  11379. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  11380. return false;
  11381. if (LHS.isComplexFloat()) {
  11382. APFloat::cmpResult CR_r =
  11383. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  11384. APFloat::cmpResult CR_i =
  11385. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  11386. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  11387. return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
  11388. } else {
  11389. assert(IsEquality && "invalid complex comparison");
  11390. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  11391. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  11392. return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
  11393. }
  11394. }
  11395. if (LHSTy->isRealFloatingType() &&
  11396. RHSTy->isRealFloatingType()) {
  11397. APFloat RHS(0.0), LHS(0.0);
  11398. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  11399. if (!LHSOK && !Info.noteFailure())
  11400. return false;
  11401. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  11402. return false;
  11403. assert(E->isComparisonOp() && "Invalid binary operator!");
  11404. llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
  11405. if (!Info.InConstantContext &&
  11406. APFloatCmpResult == APFloat::cmpUnordered &&
  11407. E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
  11408. // Note: Compares may raise invalid in some cases involving NaN or sNaN.
  11409. Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
  11410. return false;
  11411. }
  11412. auto GetCmpRes = [&]() {
  11413. switch (APFloatCmpResult) {
  11414. case APFloat::cmpEqual:
  11415. return CmpResult::Equal;
  11416. case APFloat::cmpLessThan:
  11417. return CmpResult::Less;
  11418. case APFloat::cmpGreaterThan:
  11419. return CmpResult::Greater;
  11420. case APFloat::cmpUnordered:
  11421. return CmpResult::Unordered;
  11422. }
  11423. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  11424. };
  11425. return Success(GetCmpRes(), E);
  11426. }
  11427. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  11428. LValue LHSValue, RHSValue;
  11429. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  11430. if (!LHSOK && !Info.noteFailure())
  11431. return false;
  11432. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  11433. return false;
  11434. // Reject differing bases from the normal codepath; we special-case
  11435. // comparisons to null.
  11436. if (!HasSameBase(LHSValue, RHSValue)) {
  11437. auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
  11438. std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
  11439. std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
  11440. Info.FFDiag(E, DiagID)
  11441. << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
  11442. return false;
  11443. };
  11444. // Inequalities and subtractions between unrelated pointers have
  11445. // unspecified or undefined behavior.
  11446. if (!IsEquality)
  11447. return DiagComparison(
  11448. diag::note_constexpr_pointer_comparison_unspecified);
  11449. // A constant address may compare equal to the address of a symbol.
  11450. // The one exception is that address of an object cannot compare equal
  11451. // to a null pointer constant.
  11452. // TODO: Should we restrict this to actual null pointers, and exclude the
  11453. // case of zero cast to pointer type?
  11454. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  11455. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  11456. return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
  11457. !RHSValue.Base);
  11458. // It's implementation-defined whether distinct literals will have
  11459. // distinct addresses. In clang, the result of such a comparison is
  11460. // unspecified, so it is not a constant expression. However, we do know
  11461. // that the address of a literal will be non-null.
  11462. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  11463. LHSValue.Base && RHSValue.Base)
  11464. return DiagComparison(diag::note_constexpr_literal_comparison);
  11465. // We can't tell whether weak symbols will end up pointing to the same
  11466. // object.
  11467. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  11468. return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
  11469. !IsWeakLValue(LHSValue));
  11470. // We can't compare the address of the start of one object with the
  11471. // past-the-end address of another object, per C++ DR1652.
  11472. if (LHSValue.Base && LHSValue.Offset.isZero() &&
  11473. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
  11474. return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
  11475. true);
  11476. if (RHSValue.Base && RHSValue.Offset.isZero() &&
  11477. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
  11478. return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
  11479. false);
  11480. // We can't tell whether an object is at the same address as another
  11481. // zero sized object.
  11482. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  11483. (LHSValue.Base && isZeroSized(RHSValue)))
  11484. return DiagComparison(
  11485. diag::note_constexpr_pointer_comparison_zero_sized);
  11486. return Success(CmpResult::Unequal, E);
  11487. }
  11488. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  11489. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  11490. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  11491. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  11492. // C++11 [expr.rel]p3:
  11493. // Pointers to void (after pointer conversions) can be compared, with a
  11494. // result defined as follows: If both pointers represent the same
  11495. // address or are both the null pointer value, the result is true if the
  11496. // operator is <= or >= and false otherwise; otherwise the result is
  11497. // unspecified.
  11498. // We interpret this as applying to pointers to *cv* void.
  11499. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  11500. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  11501. // C++11 [expr.rel]p2:
  11502. // - If two pointers point to non-static data members of the same object,
  11503. // or to subobjects or array elements fo such members, recursively, the
  11504. // pointer to the later declared member compares greater provided the
  11505. // two members have the same access control and provided their class is
  11506. // not a union.
  11507. // [...]
  11508. // - Otherwise pointer comparisons are unspecified.
  11509. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  11510. bool WasArrayIndex;
  11511. unsigned Mismatch = FindDesignatorMismatch(
  11512. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  11513. // At the point where the designators diverge, the comparison has a
  11514. // specified value if:
  11515. // - we are comparing array indices
  11516. // - we are comparing fields of a union, or fields with the same access
  11517. // Otherwise, the result is unspecified and thus the comparison is not a
  11518. // constant expression.
  11519. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  11520. Mismatch < RHSDesignator.Entries.size()) {
  11521. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  11522. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  11523. if (!LF && !RF)
  11524. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  11525. else if (!LF)
  11526. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  11527. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  11528. << RF->getParent() << RF;
  11529. else if (!RF)
  11530. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  11531. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  11532. << LF->getParent() << LF;
  11533. else if (!LF->getParent()->isUnion() &&
  11534. LF->getAccess() != RF->getAccess())
  11535. Info.CCEDiag(E,
  11536. diag::note_constexpr_pointer_comparison_differing_access)
  11537. << LF << LF->getAccess() << RF << RF->getAccess()
  11538. << LF->getParent();
  11539. }
  11540. }
  11541. // The comparison here must be unsigned, and performed with the same
  11542. // width as the pointer.
  11543. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  11544. uint64_t CompareLHS = LHSOffset.getQuantity();
  11545. uint64_t CompareRHS = RHSOffset.getQuantity();
  11546. assert(PtrSize <= 64 && "Unexpected pointer width");
  11547. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  11548. CompareLHS &= Mask;
  11549. CompareRHS &= Mask;
  11550. // If there is a base and this is a relational operator, we can only
  11551. // compare pointers within the object in question; otherwise, the result
  11552. // depends on where the object is located in memory.
  11553. if (!LHSValue.Base.isNull() && IsRelational) {
  11554. QualType BaseTy = getType(LHSValue.Base);
  11555. if (BaseTy->isIncompleteType())
  11556. return Error(E);
  11557. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  11558. uint64_t OffsetLimit = Size.getQuantity();
  11559. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  11560. return Error(E);
  11561. }
  11562. if (CompareLHS < CompareRHS)
  11563. return Success(CmpResult::Less, E);
  11564. if (CompareLHS > CompareRHS)
  11565. return Success(CmpResult::Greater, E);
  11566. return Success(CmpResult::Equal, E);
  11567. }
  11568. if (LHSTy->isMemberPointerType()) {
  11569. assert(IsEquality && "unexpected member pointer operation");
  11570. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  11571. MemberPtr LHSValue, RHSValue;
  11572. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  11573. if (!LHSOK && !Info.noteFailure())
  11574. return false;
  11575. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  11576. return false;
  11577. // If either operand is a pointer to a weak function, the comparison is not
  11578. // constant.
  11579. if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
  11580. Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
  11581. << LHSValue.getDecl();
  11582. return true;
  11583. }
  11584. if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
  11585. Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
  11586. << RHSValue.getDecl();
  11587. return true;
  11588. }
  11589. // C++11 [expr.eq]p2:
  11590. // If both operands are null, they compare equal. Otherwise if only one is
  11591. // null, they compare unequal.
  11592. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  11593. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  11594. return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
  11595. }
  11596. // Otherwise if either is a pointer to a virtual member function, the
  11597. // result is unspecified.
  11598. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  11599. if (MD->isVirtual())
  11600. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  11601. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  11602. if (MD->isVirtual())
  11603. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  11604. // Otherwise they compare equal if and only if they would refer to the
  11605. // same member of the same most derived object or the same subobject if
  11606. // they were dereferenced with a hypothetical object of the associated
  11607. // class type.
  11608. bool Equal = LHSValue == RHSValue;
  11609. return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
  11610. }
  11611. if (LHSTy->isNullPtrType()) {
  11612. assert(E->isComparisonOp() && "unexpected nullptr operation");
  11613. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  11614. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  11615. // are compared, the result is true of the operator is <=, >= or ==, and
  11616. // false otherwise.
  11617. return Success(CmpResult::Equal, E);
  11618. }
  11619. return DoAfter();
  11620. }
  11621. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  11622. if (!CheckLiteralType(Info, E))
  11623. return false;
  11624. auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
  11625. ComparisonCategoryResult CCR;
  11626. switch (CR) {
  11627. case CmpResult::Unequal:
  11628. llvm_unreachable("should never produce Unequal for three-way comparison");
  11629. case CmpResult::Less:
  11630. CCR = ComparisonCategoryResult::Less;
  11631. break;
  11632. case CmpResult::Equal:
  11633. CCR = ComparisonCategoryResult::Equal;
  11634. break;
  11635. case CmpResult::Greater:
  11636. CCR = ComparisonCategoryResult::Greater;
  11637. break;
  11638. case CmpResult::Unordered:
  11639. CCR = ComparisonCategoryResult::Unordered;
  11640. break;
  11641. }
  11642. // Evaluation succeeded. Lookup the information for the comparison category
  11643. // type and fetch the VarDecl for the result.
  11644. const ComparisonCategoryInfo &CmpInfo =
  11645. Info.Ctx.CompCategories.getInfoForType(E->getType());
  11646. const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
  11647. // Check and evaluate the result as a constant expression.
  11648. LValue LV;
  11649. LV.set(VD);
  11650. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  11651. return false;
  11652. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
  11653. ConstantExprKind::Normal);
  11654. };
  11655. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  11656. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  11657. });
  11658. }
  11659. bool RecordExprEvaluator::VisitCXXParenListInitExpr(
  11660. const CXXParenListInitExpr *E) {
  11661. return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
  11662. }
  11663. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  11664. // We don't support assignment in C. C++ assignments don't get here because
  11665. // assignment is an lvalue in C++.
  11666. if (E->isAssignmentOp()) {
  11667. Error(E);
  11668. if (!Info.noteFailure())
  11669. return false;
  11670. }
  11671. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  11672. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  11673. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  11674. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  11675. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  11676. if (E->isComparisonOp()) {
  11677. // Evaluate builtin binary comparisons by evaluating them as three-way
  11678. // comparisons and then translating the result.
  11679. auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
  11680. assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
  11681. "should only produce Unequal for equality comparisons");
  11682. bool IsEqual = CR == CmpResult::Equal,
  11683. IsLess = CR == CmpResult::Less,
  11684. IsGreater = CR == CmpResult::Greater;
  11685. auto Op = E->getOpcode();
  11686. switch (Op) {
  11687. default:
  11688. llvm_unreachable("unsupported binary operator");
  11689. case BO_EQ:
  11690. case BO_NE:
  11691. return Success(IsEqual == (Op == BO_EQ), E);
  11692. case BO_LT:
  11693. return Success(IsLess, E);
  11694. case BO_GT:
  11695. return Success(IsGreater, E);
  11696. case BO_LE:
  11697. return Success(IsEqual || IsLess, E);
  11698. case BO_GE:
  11699. return Success(IsEqual || IsGreater, E);
  11700. }
  11701. };
  11702. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  11703. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  11704. });
  11705. }
  11706. QualType LHSTy = E->getLHS()->getType();
  11707. QualType RHSTy = E->getRHS()->getType();
  11708. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  11709. E->getOpcode() == BO_Sub) {
  11710. LValue LHSValue, RHSValue;
  11711. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  11712. if (!LHSOK && !Info.noteFailure())
  11713. return false;
  11714. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  11715. return false;
  11716. // Reject differing bases from the normal codepath; we special-case
  11717. // comparisons to null.
  11718. if (!HasSameBase(LHSValue, RHSValue)) {
  11719. // Handle &&A - &&B.
  11720. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  11721. return Error(E);
  11722. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  11723. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  11724. if (!LHSExpr || !RHSExpr)
  11725. return Error(E);
  11726. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  11727. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  11728. if (!LHSAddrExpr || !RHSAddrExpr)
  11729. return Error(E);
  11730. // Make sure both labels come from the same function.
  11731. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  11732. RHSAddrExpr->getLabel()->getDeclContext())
  11733. return Error(E);
  11734. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  11735. }
  11736. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  11737. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  11738. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  11739. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  11740. // C++11 [expr.add]p6:
  11741. // Unless both pointers point to elements of the same array object, or
  11742. // one past the last element of the array object, the behavior is
  11743. // undefined.
  11744. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  11745. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  11746. RHSDesignator))
  11747. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  11748. QualType Type = E->getLHS()->getType();
  11749. QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
  11750. CharUnits ElementSize;
  11751. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  11752. return false;
  11753. // As an extension, a type may have zero size (empty struct or union in
  11754. // C, array of zero length). Pointer subtraction in such cases has
  11755. // undefined behavior, so is not constant.
  11756. if (ElementSize.isZero()) {
  11757. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  11758. << ElementType;
  11759. return false;
  11760. }
  11761. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  11762. // and produce incorrect results when it overflows. Such behavior
  11763. // appears to be non-conforming, but is common, so perhaps we should
  11764. // assume the standard intended for such cases to be undefined behavior
  11765. // and check for them.
  11766. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  11767. // overflow in the final conversion to ptrdiff_t.
  11768. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  11769. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  11770. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  11771. false);
  11772. APSInt TrueResult = (LHS - RHS) / ElemSize;
  11773. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  11774. if (Result.extend(65) != TrueResult &&
  11775. !HandleOverflow(Info, E, TrueResult, E->getType()))
  11776. return false;
  11777. return Success(Result, E);
  11778. }
  11779. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  11780. }
  11781. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  11782. /// a result as the expression's type.
  11783. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  11784. const UnaryExprOrTypeTraitExpr *E) {
  11785. switch(E->getKind()) {
  11786. case UETT_PreferredAlignOf:
  11787. case UETT_AlignOf: {
  11788. if (E->isArgumentType())
  11789. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  11790. E);
  11791. else
  11792. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  11793. E);
  11794. }
  11795. case UETT_VecStep: {
  11796. QualType Ty = E->getTypeOfArgument();
  11797. if (Ty->isVectorType()) {
  11798. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  11799. // The vec_step built-in functions that take a 3-component
  11800. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  11801. if (n == 3)
  11802. n = 4;
  11803. return Success(n, E);
  11804. } else
  11805. return Success(1, E);
  11806. }
  11807. case UETT_SizeOf: {
  11808. QualType SrcTy = E->getTypeOfArgument();
  11809. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  11810. // the result is the size of the referenced type."
  11811. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  11812. SrcTy = Ref->getPointeeType();
  11813. CharUnits Sizeof;
  11814. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  11815. return false;
  11816. return Success(Sizeof, E);
  11817. }
  11818. case UETT_OpenMPRequiredSimdAlign:
  11819. assert(E->isArgumentType());
  11820. return Success(
  11821. Info.Ctx.toCharUnitsFromBits(
  11822. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  11823. .getQuantity(),
  11824. E);
  11825. }
  11826. llvm_unreachable("unknown expr/type trait");
  11827. }
  11828. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  11829. CharUnits Result;
  11830. unsigned n = OOE->getNumComponents();
  11831. if (n == 0)
  11832. return Error(OOE);
  11833. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  11834. for (unsigned i = 0; i != n; ++i) {
  11835. OffsetOfNode ON = OOE->getComponent(i);
  11836. switch (ON.getKind()) {
  11837. case OffsetOfNode::Array: {
  11838. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  11839. APSInt IdxResult;
  11840. if (!EvaluateInteger(Idx, IdxResult, Info))
  11841. return false;
  11842. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  11843. if (!AT)
  11844. return Error(OOE);
  11845. CurrentType = AT->getElementType();
  11846. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  11847. Result += IdxResult.getSExtValue() * ElementSize;
  11848. break;
  11849. }
  11850. case OffsetOfNode::Field: {
  11851. FieldDecl *MemberDecl = ON.getField();
  11852. const RecordType *RT = CurrentType->getAs<RecordType>();
  11853. if (!RT)
  11854. return Error(OOE);
  11855. RecordDecl *RD = RT->getDecl();
  11856. if (RD->isInvalidDecl()) return false;
  11857. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  11858. unsigned i = MemberDecl->getFieldIndex();
  11859. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  11860. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  11861. CurrentType = MemberDecl->getType().getNonReferenceType();
  11862. break;
  11863. }
  11864. case OffsetOfNode::Identifier:
  11865. llvm_unreachable("dependent __builtin_offsetof");
  11866. case OffsetOfNode::Base: {
  11867. CXXBaseSpecifier *BaseSpec = ON.getBase();
  11868. if (BaseSpec->isVirtual())
  11869. return Error(OOE);
  11870. // Find the layout of the class whose base we are looking into.
  11871. const RecordType *RT = CurrentType->getAs<RecordType>();
  11872. if (!RT)
  11873. return Error(OOE);
  11874. RecordDecl *RD = RT->getDecl();
  11875. if (RD->isInvalidDecl()) return false;
  11876. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  11877. // Find the base class itself.
  11878. CurrentType = BaseSpec->getType();
  11879. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  11880. if (!BaseRT)
  11881. return Error(OOE);
  11882. // Add the offset to the base.
  11883. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  11884. break;
  11885. }
  11886. }
  11887. }
  11888. return Success(Result, OOE);
  11889. }
  11890. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11891. switch (E->getOpcode()) {
  11892. default:
  11893. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  11894. // See C99 6.6p3.
  11895. return Error(E);
  11896. case UO_Extension:
  11897. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  11898. // If so, we could clear the diagnostic ID.
  11899. return Visit(E->getSubExpr());
  11900. case UO_Plus:
  11901. // The result is just the value.
  11902. return Visit(E->getSubExpr());
  11903. case UO_Minus: {
  11904. if (!Visit(E->getSubExpr()))
  11905. return false;
  11906. if (!Result.isInt()) return Error(E);
  11907. const APSInt &Value = Result.getInt();
  11908. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  11909. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  11910. E->getType()))
  11911. return false;
  11912. return Success(-Value, E);
  11913. }
  11914. case UO_Not: {
  11915. if (!Visit(E->getSubExpr()))
  11916. return false;
  11917. if (!Result.isInt()) return Error(E);
  11918. return Success(~Result.getInt(), E);
  11919. }
  11920. case UO_LNot: {
  11921. bool bres;
  11922. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  11923. return false;
  11924. return Success(!bres, E);
  11925. }
  11926. }
  11927. }
  11928. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  11929. /// result type is integer.
  11930. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  11931. const Expr *SubExpr = E->getSubExpr();
  11932. QualType DestType = E->getType();
  11933. QualType SrcType = SubExpr->getType();
  11934. switch (E->getCastKind()) {
  11935. case CK_BaseToDerived:
  11936. case CK_DerivedToBase:
  11937. case CK_UncheckedDerivedToBase:
  11938. case CK_Dynamic:
  11939. case CK_ToUnion:
  11940. case CK_ArrayToPointerDecay:
  11941. case CK_FunctionToPointerDecay:
  11942. case CK_NullToPointer:
  11943. case CK_NullToMemberPointer:
  11944. case CK_BaseToDerivedMemberPointer:
  11945. case CK_DerivedToBaseMemberPointer:
  11946. case CK_ReinterpretMemberPointer:
  11947. case CK_ConstructorConversion:
  11948. case CK_IntegralToPointer:
  11949. case CK_ToVoid:
  11950. case CK_VectorSplat:
  11951. case CK_IntegralToFloating:
  11952. case CK_FloatingCast:
  11953. case CK_CPointerToObjCPointerCast:
  11954. case CK_BlockPointerToObjCPointerCast:
  11955. case CK_AnyPointerToBlockPointerCast:
  11956. case CK_ObjCObjectLValueCast:
  11957. case CK_FloatingRealToComplex:
  11958. case CK_FloatingComplexToReal:
  11959. case CK_FloatingComplexCast:
  11960. case CK_FloatingComplexToIntegralComplex:
  11961. case CK_IntegralRealToComplex:
  11962. case CK_IntegralComplexCast:
  11963. case CK_IntegralComplexToFloatingComplex:
  11964. case CK_BuiltinFnToFnPtr:
  11965. case CK_ZeroToOCLOpaqueType:
  11966. case CK_NonAtomicToAtomic:
  11967. case CK_AddressSpaceConversion:
  11968. case CK_IntToOCLSampler:
  11969. case CK_FloatingToFixedPoint:
  11970. case CK_FixedPointToFloating:
  11971. case CK_FixedPointCast:
  11972. case CK_IntegralToFixedPoint:
  11973. case CK_MatrixCast:
  11974. llvm_unreachable("invalid cast kind for integral value");
  11975. case CK_BitCast:
  11976. case CK_Dependent:
  11977. case CK_LValueBitCast:
  11978. case CK_ARCProduceObject:
  11979. case CK_ARCConsumeObject:
  11980. case CK_ARCReclaimReturnedObject:
  11981. case CK_ARCExtendBlockObject:
  11982. case CK_CopyAndAutoreleaseBlockObject:
  11983. return Error(E);
  11984. case CK_UserDefinedConversion:
  11985. case CK_LValueToRValue:
  11986. case CK_AtomicToNonAtomic:
  11987. case CK_NoOp:
  11988. case CK_LValueToRValueBitCast:
  11989. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11990. case CK_MemberPointerToBoolean:
  11991. case CK_PointerToBoolean:
  11992. case CK_IntegralToBoolean:
  11993. case CK_FloatingToBoolean:
  11994. case CK_BooleanToSignedIntegral:
  11995. case CK_FloatingComplexToBoolean:
  11996. case CK_IntegralComplexToBoolean: {
  11997. bool BoolResult;
  11998. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  11999. return false;
  12000. uint64_t IntResult = BoolResult;
  12001. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  12002. IntResult = (uint64_t)-1;
  12003. return Success(IntResult, E);
  12004. }
  12005. case CK_FixedPointToIntegral: {
  12006. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  12007. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  12008. return false;
  12009. bool Overflowed;
  12010. llvm::APSInt Result = Src.convertToInt(
  12011. Info.Ctx.getIntWidth(DestType),
  12012. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  12013. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  12014. return false;
  12015. return Success(Result, E);
  12016. }
  12017. case CK_FixedPointToBoolean: {
  12018. // Unsigned padding does not affect this.
  12019. APValue Val;
  12020. if (!Evaluate(Val, Info, SubExpr))
  12021. return false;
  12022. return Success(Val.getFixedPoint().getBoolValue(), E);
  12023. }
  12024. case CK_IntegralCast: {
  12025. if (!Visit(SubExpr))
  12026. return false;
  12027. if (!Result.isInt()) {
  12028. // Allow casts of address-of-label differences if they are no-ops
  12029. // or narrowing. (The narrowing case isn't actually guaranteed to
  12030. // be constant-evaluatable except in some narrow cases which are hard
  12031. // to detect here. We let it through on the assumption the user knows
  12032. // what they are doing.)
  12033. if (Result.isAddrLabelDiff())
  12034. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  12035. // Only allow casts of lvalues if they are lossless.
  12036. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  12037. }
  12038. if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
  12039. Info.EvalMode == EvalInfo::EM_ConstantExpression &&
  12040. DestType->isEnumeralType()) {
  12041. bool ConstexprVar = true;
  12042. // We know if we are here that we are in a context that we might require
  12043. // a constant expression or a context that requires a constant
  12044. // value. But if we are initializing a value we don't know if it is a
  12045. // constexpr variable or not. We can check the EvaluatingDecl to determine
  12046. // if it constexpr or not. If not then we don't want to emit a diagnostic.
  12047. if (const auto *VD = dyn_cast_or_null<VarDecl>(
  12048. Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
  12049. ConstexprVar = VD->isConstexpr();
  12050. const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
  12051. const EnumDecl *ED = ET->getDecl();
  12052. // Check that the value is within the range of the enumeration values.
  12053. //
  12054. // This corressponds to [expr.static.cast]p10 which says:
  12055. // A value of integral or enumeration type can be explicitly converted
  12056. // to a complete enumeration type ... If the enumeration type does not
  12057. // have a fixed underlying type, the value is unchanged if the original
  12058. // value is within the range of the enumeration values ([dcl.enum]), and
  12059. // otherwise, the behavior is undefined.
  12060. //
  12061. // This was resolved as part of DR2338 which has CD5 status.
  12062. if (!ED->isFixed()) {
  12063. llvm::APInt Min;
  12064. llvm::APInt Max;
  12065. ED->getValueRange(Max, Min);
  12066. --Max;
  12067. if (ED->getNumNegativeBits() && ConstexprVar &&
  12068. (Max.slt(Result.getInt().getSExtValue()) ||
  12069. Min.sgt(Result.getInt().getSExtValue())))
  12070. Info.Ctx.getDiagnostics().Report(
  12071. E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
  12072. << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
  12073. << Max.getSExtValue();
  12074. else if (!ED->getNumNegativeBits() && ConstexprVar &&
  12075. Max.ult(Result.getInt().getZExtValue()))
  12076. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  12077. diag::warn_constexpr_unscoped_enum_out_of_range)
  12078. << llvm::toString(Result.getInt(),10) << Min.getZExtValue() << Max.getZExtValue();
  12079. }
  12080. }
  12081. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  12082. Result.getInt()), E);
  12083. }
  12084. case CK_PointerToIntegral: {
  12085. CCEDiag(E, diag::note_constexpr_invalid_cast)
  12086. << 2 << Info.Ctx.getLangOpts().CPlusPlus;
  12087. LValue LV;
  12088. if (!EvaluatePointer(SubExpr, LV, Info))
  12089. return false;
  12090. if (LV.getLValueBase()) {
  12091. // Only allow based lvalue casts if they are lossless.
  12092. // FIXME: Allow a larger integer size than the pointer size, and allow
  12093. // narrowing back down to pointer width in subsequent integral casts.
  12094. // FIXME: Check integer type's active bits, not its type size.
  12095. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  12096. return Error(E);
  12097. LV.Designator.setInvalid();
  12098. LV.moveInto(Result);
  12099. return true;
  12100. }
  12101. APSInt AsInt;
  12102. APValue V;
  12103. LV.moveInto(V);
  12104. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  12105. llvm_unreachable("Can't cast this!");
  12106. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  12107. }
  12108. case CK_IntegralComplexToReal: {
  12109. ComplexValue C;
  12110. if (!EvaluateComplex(SubExpr, C, Info))
  12111. return false;
  12112. return Success(C.getComplexIntReal(), E);
  12113. }
  12114. case CK_FloatingToIntegral: {
  12115. APFloat F(0.0);
  12116. if (!EvaluateFloat(SubExpr, F, Info))
  12117. return false;
  12118. APSInt Value;
  12119. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  12120. return false;
  12121. return Success(Value, E);
  12122. }
  12123. }
  12124. llvm_unreachable("unknown cast resulting in integral value");
  12125. }
  12126. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  12127. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  12128. ComplexValue LV;
  12129. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  12130. return false;
  12131. if (!LV.isComplexInt())
  12132. return Error(E);
  12133. return Success(LV.getComplexIntReal(), E);
  12134. }
  12135. return Visit(E->getSubExpr());
  12136. }
  12137. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  12138. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  12139. ComplexValue LV;
  12140. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  12141. return false;
  12142. if (!LV.isComplexInt())
  12143. return Error(E);
  12144. return Success(LV.getComplexIntImag(), E);
  12145. }
  12146. VisitIgnoredValue(E->getSubExpr());
  12147. return Success(0, E);
  12148. }
  12149. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  12150. return Success(E->getPackLength(), E);
  12151. }
  12152. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  12153. return Success(E->getValue(), E);
  12154. }
  12155. bool IntExprEvaluator::VisitConceptSpecializationExpr(
  12156. const ConceptSpecializationExpr *E) {
  12157. return Success(E->isSatisfied(), E);
  12158. }
  12159. bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
  12160. return Success(E->isSatisfied(), E);
  12161. }
  12162. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  12163. switch (E->getOpcode()) {
  12164. default:
  12165. // Invalid unary operators
  12166. return Error(E);
  12167. case UO_Plus:
  12168. // The result is just the value.
  12169. return Visit(E->getSubExpr());
  12170. case UO_Minus: {
  12171. if (!Visit(E->getSubExpr())) return false;
  12172. if (!Result.isFixedPoint())
  12173. return Error(E);
  12174. bool Overflowed;
  12175. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  12176. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  12177. return false;
  12178. return Success(Negated, E);
  12179. }
  12180. case UO_LNot: {
  12181. bool bres;
  12182. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  12183. return false;
  12184. return Success(!bres, E);
  12185. }
  12186. }
  12187. }
  12188. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  12189. const Expr *SubExpr = E->getSubExpr();
  12190. QualType DestType = E->getType();
  12191. assert(DestType->isFixedPointType() &&
  12192. "Expected destination type to be a fixed point type");
  12193. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  12194. switch (E->getCastKind()) {
  12195. case CK_FixedPointCast: {
  12196. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  12197. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  12198. return false;
  12199. bool Overflowed;
  12200. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  12201. if (Overflowed) {
  12202. if (Info.checkingForUndefinedBehavior())
  12203. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  12204. diag::warn_fixedpoint_constant_overflow)
  12205. << Result.toString() << E->getType();
  12206. if (!HandleOverflow(Info, E, Result, E->getType()))
  12207. return false;
  12208. }
  12209. return Success(Result, E);
  12210. }
  12211. case CK_IntegralToFixedPoint: {
  12212. APSInt Src;
  12213. if (!EvaluateInteger(SubExpr, Src, Info))
  12214. return false;
  12215. bool Overflowed;
  12216. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  12217. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  12218. if (Overflowed) {
  12219. if (Info.checkingForUndefinedBehavior())
  12220. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  12221. diag::warn_fixedpoint_constant_overflow)
  12222. << IntResult.toString() << E->getType();
  12223. if (!HandleOverflow(Info, E, IntResult, E->getType()))
  12224. return false;
  12225. }
  12226. return Success(IntResult, E);
  12227. }
  12228. case CK_FloatingToFixedPoint: {
  12229. APFloat Src(0.0);
  12230. if (!EvaluateFloat(SubExpr, Src, Info))
  12231. return false;
  12232. bool Overflowed;
  12233. APFixedPoint Result = APFixedPoint::getFromFloatValue(
  12234. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  12235. if (Overflowed) {
  12236. if (Info.checkingForUndefinedBehavior())
  12237. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  12238. diag::warn_fixedpoint_constant_overflow)
  12239. << Result.toString() << E->getType();
  12240. if (!HandleOverflow(Info, E, Result, E->getType()))
  12241. return false;
  12242. }
  12243. return Success(Result, E);
  12244. }
  12245. case CK_NoOp:
  12246. case CK_LValueToRValue:
  12247. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  12248. default:
  12249. return Error(E);
  12250. }
  12251. }
  12252. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  12253. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  12254. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  12255. const Expr *LHS = E->getLHS();
  12256. const Expr *RHS = E->getRHS();
  12257. FixedPointSemantics ResultFXSema =
  12258. Info.Ctx.getFixedPointSemantics(E->getType());
  12259. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  12260. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  12261. return false;
  12262. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  12263. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  12264. return false;
  12265. bool OpOverflow = false, ConversionOverflow = false;
  12266. APFixedPoint Result(LHSFX.getSemantics());
  12267. switch (E->getOpcode()) {
  12268. case BO_Add: {
  12269. Result = LHSFX.add(RHSFX, &OpOverflow)
  12270. .convert(ResultFXSema, &ConversionOverflow);
  12271. break;
  12272. }
  12273. case BO_Sub: {
  12274. Result = LHSFX.sub(RHSFX, &OpOverflow)
  12275. .convert(ResultFXSema, &ConversionOverflow);
  12276. break;
  12277. }
  12278. case BO_Mul: {
  12279. Result = LHSFX.mul(RHSFX, &OpOverflow)
  12280. .convert(ResultFXSema, &ConversionOverflow);
  12281. break;
  12282. }
  12283. case BO_Div: {
  12284. if (RHSFX.getValue() == 0) {
  12285. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  12286. return false;
  12287. }
  12288. Result = LHSFX.div(RHSFX, &OpOverflow)
  12289. .convert(ResultFXSema, &ConversionOverflow);
  12290. break;
  12291. }
  12292. case BO_Shl:
  12293. case BO_Shr: {
  12294. FixedPointSemantics LHSSema = LHSFX.getSemantics();
  12295. llvm::APSInt RHSVal = RHSFX.getValue();
  12296. unsigned ShiftBW =
  12297. LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
  12298. unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
  12299. // Embedded-C 4.1.6.2.2:
  12300. // The right operand must be nonnegative and less than the total number
  12301. // of (nonpadding) bits of the fixed-point operand ...
  12302. if (RHSVal.isNegative())
  12303. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
  12304. else if (Amt != RHSVal)
  12305. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  12306. << RHSVal << E->getType() << ShiftBW;
  12307. if (E->getOpcode() == BO_Shl)
  12308. Result = LHSFX.shl(Amt, &OpOverflow);
  12309. else
  12310. Result = LHSFX.shr(Amt, &OpOverflow);
  12311. break;
  12312. }
  12313. default:
  12314. return false;
  12315. }
  12316. if (OpOverflow || ConversionOverflow) {
  12317. if (Info.checkingForUndefinedBehavior())
  12318. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  12319. diag::warn_fixedpoint_constant_overflow)
  12320. << Result.toString() << E->getType();
  12321. if (!HandleOverflow(Info, E, Result, E->getType()))
  12322. return false;
  12323. }
  12324. return Success(Result, E);
  12325. }
  12326. //===----------------------------------------------------------------------===//
  12327. // Float Evaluation
  12328. //===----------------------------------------------------------------------===//
  12329. namespace {
  12330. class FloatExprEvaluator
  12331. : public ExprEvaluatorBase<FloatExprEvaluator> {
  12332. APFloat &Result;
  12333. public:
  12334. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  12335. : ExprEvaluatorBaseTy(info), Result(result) {}
  12336. bool Success(const APValue &V, const Expr *e) {
  12337. Result = V.getFloat();
  12338. return true;
  12339. }
  12340. bool ZeroInitialization(const Expr *E) {
  12341. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  12342. return true;
  12343. }
  12344. bool VisitCallExpr(const CallExpr *E);
  12345. bool VisitUnaryOperator(const UnaryOperator *E);
  12346. bool VisitBinaryOperator(const BinaryOperator *E);
  12347. bool VisitFloatingLiteral(const FloatingLiteral *E);
  12348. bool VisitCastExpr(const CastExpr *E);
  12349. bool VisitUnaryReal(const UnaryOperator *E);
  12350. bool VisitUnaryImag(const UnaryOperator *E);
  12351. // FIXME: Missing: array subscript of vector, member of vector
  12352. };
  12353. } // end anonymous namespace
  12354. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  12355. assert(!E->isValueDependent());
  12356. assert(E->isPRValue() && E->getType()->isRealFloatingType());
  12357. return FloatExprEvaluator(Info, Result).Visit(E);
  12358. }
  12359. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  12360. QualType ResultTy,
  12361. const Expr *Arg,
  12362. bool SNaN,
  12363. llvm::APFloat &Result) {
  12364. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  12365. if (!S) return false;
  12366. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  12367. llvm::APInt fill;
  12368. // Treat empty strings as if they were zero.
  12369. if (S->getString().empty())
  12370. fill = llvm::APInt(32, 0);
  12371. else if (S->getString().getAsInteger(0, fill))
  12372. return false;
  12373. if (Context.getTargetInfo().isNan2008()) {
  12374. if (SNaN)
  12375. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  12376. else
  12377. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  12378. } else {
  12379. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  12380. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  12381. // a different encoding to what became a standard in 2008, and for pre-
  12382. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  12383. // sNaN. This is now known as "legacy NaN" encoding.
  12384. if (SNaN)
  12385. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  12386. else
  12387. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  12388. }
  12389. return true;
  12390. }
  12391. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  12392. if (!IsConstantEvaluatedBuiltinCall(E))
  12393. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  12394. switch (E->getBuiltinCallee()) {
  12395. default:
  12396. return false;
  12397. case Builtin::BI__builtin_huge_val:
  12398. case Builtin::BI__builtin_huge_valf:
  12399. case Builtin::BI__builtin_huge_vall:
  12400. case Builtin::BI__builtin_huge_valf16:
  12401. case Builtin::BI__builtin_huge_valf128:
  12402. case Builtin::BI__builtin_inf:
  12403. case Builtin::BI__builtin_inff:
  12404. case Builtin::BI__builtin_infl:
  12405. case Builtin::BI__builtin_inff16:
  12406. case Builtin::BI__builtin_inff128: {
  12407. const llvm::fltSemantics &Sem =
  12408. Info.Ctx.getFloatTypeSemantics(E->getType());
  12409. Result = llvm::APFloat::getInf(Sem);
  12410. return true;
  12411. }
  12412. case Builtin::BI__builtin_nans:
  12413. case Builtin::BI__builtin_nansf:
  12414. case Builtin::BI__builtin_nansl:
  12415. case Builtin::BI__builtin_nansf16:
  12416. case Builtin::BI__builtin_nansf128:
  12417. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  12418. true, Result))
  12419. return Error(E);
  12420. return true;
  12421. case Builtin::BI__builtin_nan:
  12422. case Builtin::BI__builtin_nanf:
  12423. case Builtin::BI__builtin_nanl:
  12424. case Builtin::BI__builtin_nanf16:
  12425. case Builtin::BI__builtin_nanf128:
  12426. // If this is __builtin_nan() turn this into a nan, otherwise we
  12427. // can't constant fold it.
  12428. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  12429. false, Result))
  12430. return Error(E);
  12431. return true;
  12432. case Builtin::BI__builtin_fabs:
  12433. case Builtin::BI__builtin_fabsf:
  12434. case Builtin::BI__builtin_fabsl:
  12435. case Builtin::BI__builtin_fabsf128:
  12436. // The C standard says "fabs raises no floating-point exceptions,
  12437. // even if x is a signaling NaN. The returned value is independent of
  12438. // the current rounding direction mode." Therefore constant folding can
  12439. // proceed without regard to the floating point settings.
  12440. // Reference, WG14 N2478 F.10.4.3
  12441. if (!EvaluateFloat(E->getArg(0), Result, Info))
  12442. return false;
  12443. if (Result.isNegative())
  12444. Result.changeSign();
  12445. return true;
  12446. case Builtin::BI__arithmetic_fence:
  12447. return EvaluateFloat(E->getArg(0), Result, Info);
  12448. // FIXME: Builtin::BI__builtin_powi
  12449. // FIXME: Builtin::BI__builtin_powif
  12450. // FIXME: Builtin::BI__builtin_powil
  12451. case Builtin::BI__builtin_copysign:
  12452. case Builtin::BI__builtin_copysignf:
  12453. case Builtin::BI__builtin_copysignl:
  12454. case Builtin::BI__builtin_copysignf128: {
  12455. APFloat RHS(0.);
  12456. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  12457. !EvaluateFloat(E->getArg(1), RHS, Info))
  12458. return false;
  12459. Result.copySign(RHS);
  12460. return true;
  12461. }
  12462. case Builtin::BI__builtin_fmax:
  12463. case Builtin::BI__builtin_fmaxf:
  12464. case Builtin::BI__builtin_fmaxl:
  12465. case Builtin::BI__builtin_fmaxf16:
  12466. case Builtin::BI__builtin_fmaxf128: {
  12467. // TODO: Handle sNaN.
  12468. APFloat RHS(0.);
  12469. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  12470. !EvaluateFloat(E->getArg(1), RHS, Info))
  12471. return false;
  12472. // When comparing zeroes, return +0.0 if one of the zeroes is positive.
  12473. if (Result.isZero() && RHS.isZero() && Result.isNegative())
  12474. Result = RHS;
  12475. else if (Result.isNaN() || RHS > Result)
  12476. Result = RHS;
  12477. return true;
  12478. }
  12479. case Builtin::BI__builtin_fmin:
  12480. case Builtin::BI__builtin_fminf:
  12481. case Builtin::BI__builtin_fminl:
  12482. case Builtin::BI__builtin_fminf16:
  12483. case Builtin::BI__builtin_fminf128: {
  12484. // TODO: Handle sNaN.
  12485. APFloat RHS(0.);
  12486. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  12487. !EvaluateFloat(E->getArg(1), RHS, Info))
  12488. return false;
  12489. // When comparing zeroes, return -0.0 if one of the zeroes is negative.
  12490. if (Result.isZero() && RHS.isZero() && RHS.isNegative())
  12491. Result = RHS;
  12492. else if (Result.isNaN() || RHS < Result)
  12493. Result = RHS;
  12494. return true;
  12495. }
  12496. }
  12497. }
  12498. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  12499. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  12500. ComplexValue CV;
  12501. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  12502. return false;
  12503. Result = CV.FloatReal;
  12504. return true;
  12505. }
  12506. return Visit(E->getSubExpr());
  12507. }
  12508. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  12509. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  12510. ComplexValue CV;
  12511. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  12512. return false;
  12513. Result = CV.FloatImag;
  12514. return true;
  12515. }
  12516. VisitIgnoredValue(E->getSubExpr());
  12517. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  12518. Result = llvm::APFloat::getZero(Sem);
  12519. return true;
  12520. }
  12521. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  12522. switch (E->getOpcode()) {
  12523. default: return Error(E);
  12524. case UO_Plus:
  12525. return EvaluateFloat(E->getSubExpr(), Result, Info);
  12526. case UO_Minus:
  12527. // In C standard, WG14 N2478 F.3 p4
  12528. // "the unary - raises no floating point exceptions,
  12529. // even if the operand is signalling."
  12530. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  12531. return false;
  12532. Result.changeSign();
  12533. return true;
  12534. }
  12535. }
  12536. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  12537. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  12538. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  12539. APFloat RHS(0.0);
  12540. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  12541. if (!LHSOK && !Info.noteFailure())
  12542. return false;
  12543. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  12544. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  12545. }
  12546. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  12547. Result = E->getValue();
  12548. return true;
  12549. }
  12550. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  12551. const Expr* SubExpr = E->getSubExpr();
  12552. switch (E->getCastKind()) {
  12553. default:
  12554. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  12555. case CK_IntegralToFloating: {
  12556. APSInt IntResult;
  12557. const FPOptions FPO = E->getFPFeaturesInEffect(
  12558. Info.Ctx.getLangOpts());
  12559. return EvaluateInteger(SubExpr, IntResult, Info) &&
  12560. HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
  12561. IntResult, E->getType(), Result);
  12562. }
  12563. case CK_FixedPointToFloating: {
  12564. APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  12565. if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
  12566. return false;
  12567. Result =
  12568. FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
  12569. return true;
  12570. }
  12571. case CK_FloatingCast: {
  12572. if (!Visit(SubExpr))
  12573. return false;
  12574. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  12575. Result);
  12576. }
  12577. case CK_FloatingComplexToReal: {
  12578. ComplexValue V;
  12579. if (!EvaluateComplex(SubExpr, V, Info))
  12580. return false;
  12581. Result = V.getComplexFloatReal();
  12582. return true;
  12583. }
  12584. }
  12585. }
  12586. //===----------------------------------------------------------------------===//
  12587. // Complex Evaluation (for float and integer)
  12588. //===----------------------------------------------------------------------===//
  12589. namespace {
  12590. class ComplexExprEvaluator
  12591. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  12592. ComplexValue &Result;
  12593. public:
  12594. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  12595. : ExprEvaluatorBaseTy(info), Result(Result) {}
  12596. bool Success(const APValue &V, const Expr *e) {
  12597. Result.setFrom(V);
  12598. return true;
  12599. }
  12600. bool ZeroInitialization(const Expr *E);
  12601. //===--------------------------------------------------------------------===//
  12602. // Visitor Methods
  12603. //===--------------------------------------------------------------------===//
  12604. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  12605. bool VisitCastExpr(const CastExpr *E);
  12606. bool VisitBinaryOperator(const BinaryOperator *E);
  12607. bool VisitUnaryOperator(const UnaryOperator *E);
  12608. bool VisitInitListExpr(const InitListExpr *E);
  12609. bool VisitCallExpr(const CallExpr *E);
  12610. };
  12611. } // end anonymous namespace
  12612. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  12613. EvalInfo &Info) {
  12614. assert(!E->isValueDependent());
  12615. assert(E->isPRValue() && E->getType()->isAnyComplexType());
  12616. return ComplexExprEvaluator(Info, Result).Visit(E);
  12617. }
  12618. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  12619. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  12620. if (ElemTy->isRealFloatingType()) {
  12621. Result.makeComplexFloat();
  12622. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  12623. Result.FloatReal = Zero;
  12624. Result.FloatImag = Zero;
  12625. } else {
  12626. Result.makeComplexInt();
  12627. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  12628. Result.IntReal = Zero;
  12629. Result.IntImag = Zero;
  12630. }
  12631. return true;
  12632. }
  12633. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  12634. const Expr* SubExpr = E->getSubExpr();
  12635. if (SubExpr->getType()->isRealFloatingType()) {
  12636. Result.makeComplexFloat();
  12637. APFloat &Imag = Result.FloatImag;
  12638. if (!EvaluateFloat(SubExpr, Imag, Info))
  12639. return false;
  12640. Result.FloatReal = APFloat(Imag.getSemantics());
  12641. return true;
  12642. } else {
  12643. assert(SubExpr->getType()->isIntegerType() &&
  12644. "Unexpected imaginary literal.");
  12645. Result.makeComplexInt();
  12646. APSInt &Imag = Result.IntImag;
  12647. if (!EvaluateInteger(SubExpr, Imag, Info))
  12648. return false;
  12649. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  12650. return true;
  12651. }
  12652. }
  12653. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  12654. switch (E->getCastKind()) {
  12655. case CK_BitCast:
  12656. case CK_BaseToDerived:
  12657. case CK_DerivedToBase:
  12658. case CK_UncheckedDerivedToBase:
  12659. case CK_Dynamic:
  12660. case CK_ToUnion:
  12661. case CK_ArrayToPointerDecay:
  12662. case CK_FunctionToPointerDecay:
  12663. case CK_NullToPointer:
  12664. case CK_NullToMemberPointer:
  12665. case CK_BaseToDerivedMemberPointer:
  12666. case CK_DerivedToBaseMemberPointer:
  12667. case CK_MemberPointerToBoolean:
  12668. case CK_ReinterpretMemberPointer:
  12669. case CK_ConstructorConversion:
  12670. case CK_IntegralToPointer:
  12671. case CK_PointerToIntegral:
  12672. case CK_PointerToBoolean:
  12673. case CK_ToVoid:
  12674. case CK_VectorSplat:
  12675. case CK_IntegralCast:
  12676. case CK_BooleanToSignedIntegral:
  12677. case CK_IntegralToBoolean:
  12678. case CK_IntegralToFloating:
  12679. case CK_FloatingToIntegral:
  12680. case CK_FloatingToBoolean:
  12681. case CK_FloatingCast:
  12682. case CK_CPointerToObjCPointerCast:
  12683. case CK_BlockPointerToObjCPointerCast:
  12684. case CK_AnyPointerToBlockPointerCast:
  12685. case CK_ObjCObjectLValueCast:
  12686. case CK_FloatingComplexToReal:
  12687. case CK_FloatingComplexToBoolean:
  12688. case CK_IntegralComplexToReal:
  12689. case CK_IntegralComplexToBoolean:
  12690. case CK_ARCProduceObject:
  12691. case CK_ARCConsumeObject:
  12692. case CK_ARCReclaimReturnedObject:
  12693. case CK_ARCExtendBlockObject:
  12694. case CK_CopyAndAutoreleaseBlockObject:
  12695. case CK_BuiltinFnToFnPtr:
  12696. case CK_ZeroToOCLOpaqueType:
  12697. case CK_NonAtomicToAtomic:
  12698. case CK_AddressSpaceConversion:
  12699. case CK_IntToOCLSampler:
  12700. case CK_FloatingToFixedPoint:
  12701. case CK_FixedPointToFloating:
  12702. case CK_FixedPointCast:
  12703. case CK_FixedPointToBoolean:
  12704. case CK_FixedPointToIntegral:
  12705. case CK_IntegralToFixedPoint:
  12706. case CK_MatrixCast:
  12707. llvm_unreachable("invalid cast kind for complex value");
  12708. case CK_LValueToRValue:
  12709. case CK_AtomicToNonAtomic:
  12710. case CK_NoOp:
  12711. case CK_LValueToRValueBitCast:
  12712. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  12713. case CK_Dependent:
  12714. case CK_LValueBitCast:
  12715. case CK_UserDefinedConversion:
  12716. return Error(E);
  12717. case CK_FloatingRealToComplex: {
  12718. APFloat &Real = Result.FloatReal;
  12719. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  12720. return false;
  12721. Result.makeComplexFloat();
  12722. Result.FloatImag = APFloat(Real.getSemantics());
  12723. return true;
  12724. }
  12725. case CK_FloatingComplexCast: {
  12726. if (!Visit(E->getSubExpr()))
  12727. return false;
  12728. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  12729. QualType From
  12730. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  12731. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  12732. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  12733. }
  12734. case CK_FloatingComplexToIntegralComplex: {
  12735. if (!Visit(E->getSubExpr()))
  12736. return false;
  12737. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  12738. QualType From
  12739. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  12740. Result.makeComplexInt();
  12741. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  12742. To, Result.IntReal) &&
  12743. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  12744. To, Result.IntImag);
  12745. }
  12746. case CK_IntegralRealToComplex: {
  12747. APSInt &Real = Result.IntReal;
  12748. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  12749. return false;
  12750. Result.makeComplexInt();
  12751. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  12752. return true;
  12753. }
  12754. case CK_IntegralComplexCast: {
  12755. if (!Visit(E->getSubExpr()))
  12756. return false;
  12757. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  12758. QualType From
  12759. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  12760. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  12761. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  12762. return true;
  12763. }
  12764. case CK_IntegralComplexToFloatingComplex: {
  12765. if (!Visit(E->getSubExpr()))
  12766. return false;
  12767. const FPOptions FPO = E->getFPFeaturesInEffect(
  12768. Info.Ctx.getLangOpts());
  12769. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  12770. QualType From
  12771. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  12772. Result.makeComplexFloat();
  12773. return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
  12774. To, Result.FloatReal) &&
  12775. HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
  12776. To, Result.FloatImag);
  12777. }
  12778. }
  12779. llvm_unreachable("unknown cast resulting in complex value");
  12780. }
  12781. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  12782. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  12783. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  12784. // Track whether the LHS or RHS is real at the type system level. When this is
  12785. // the case we can simplify our evaluation strategy.
  12786. bool LHSReal = false, RHSReal = false;
  12787. bool LHSOK;
  12788. if (E->getLHS()->getType()->isRealFloatingType()) {
  12789. LHSReal = true;
  12790. APFloat &Real = Result.FloatReal;
  12791. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  12792. if (LHSOK) {
  12793. Result.makeComplexFloat();
  12794. Result.FloatImag = APFloat(Real.getSemantics());
  12795. }
  12796. } else {
  12797. LHSOK = Visit(E->getLHS());
  12798. }
  12799. if (!LHSOK && !Info.noteFailure())
  12800. return false;
  12801. ComplexValue RHS;
  12802. if (E->getRHS()->getType()->isRealFloatingType()) {
  12803. RHSReal = true;
  12804. APFloat &Real = RHS.FloatReal;
  12805. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  12806. return false;
  12807. RHS.makeComplexFloat();
  12808. RHS.FloatImag = APFloat(Real.getSemantics());
  12809. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  12810. return false;
  12811. assert(!(LHSReal && RHSReal) &&
  12812. "Cannot have both operands of a complex operation be real.");
  12813. switch (E->getOpcode()) {
  12814. default: return Error(E);
  12815. case BO_Add:
  12816. if (Result.isComplexFloat()) {
  12817. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  12818. APFloat::rmNearestTiesToEven);
  12819. if (LHSReal)
  12820. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  12821. else if (!RHSReal)
  12822. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  12823. APFloat::rmNearestTiesToEven);
  12824. } else {
  12825. Result.getComplexIntReal() += RHS.getComplexIntReal();
  12826. Result.getComplexIntImag() += RHS.getComplexIntImag();
  12827. }
  12828. break;
  12829. case BO_Sub:
  12830. if (Result.isComplexFloat()) {
  12831. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  12832. APFloat::rmNearestTiesToEven);
  12833. if (LHSReal) {
  12834. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  12835. Result.getComplexFloatImag().changeSign();
  12836. } else if (!RHSReal) {
  12837. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  12838. APFloat::rmNearestTiesToEven);
  12839. }
  12840. } else {
  12841. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  12842. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  12843. }
  12844. break;
  12845. case BO_Mul:
  12846. if (Result.isComplexFloat()) {
  12847. // This is an implementation of complex multiplication according to the
  12848. // constraints laid out in C11 Annex G. The implementation uses the
  12849. // following naming scheme:
  12850. // (a + ib) * (c + id)
  12851. ComplexValue LHS = Result;
  12852. APFloat &A = LHS.getComplexFloatReal();
  12853. APFloat &B = LHS.getComplexFloatImag();
  12854. APFloat &C = RHS.getComplexFloatReal();
  12855. APFloat &D = RHS.getComplexFloatImag();
  12856. APFloat &ResR = Result.getComplexFloatReal();
  12857. APFloat &ResI = Result.getComplexFloatImag();
  12858. if (LHSReal) {
  12859. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  12860. ResR = A * C;
  12861. ResI = A * D;
  12862. } else if (RHSReal) {
  12863. ResR = C * A;
  12864. ResI = C * B;
  12865. } else {
  12866. // In the fully general case, we need to handle NaNs and infinities
  12867. // robustly.
  12868. APFloat AC = A * C;
  12869. APFloat BD = B * D;
  12870. APFloat AD = A * D;
  12871. APFloat BC = B * C;
  12872. ResR = AC - BD;
  12873. ResI = AD + BC;
  12874. if (ResR.isNaN() && ResI.isNaN()) {
  12875. bool Recalc = false;
  12876. if (A.isInfinity() || B.isInfinity()) {
  12877. A = APFloat::copySign(
  12878. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  12879. B = APFloat::copySign(
  12880. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  12881. if (C.isNaN())
  12882. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  12883. if (D.isNaN())
  12884. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  12885. Recalc = true;
  12886. }
  12887. if (C.isInfinity() || D.isInfinity()) {
  12888. C = APFloat::copySign(
  12889. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  12890. D = APFloat::copySign(
  12891. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  12892. if (A.isNaN())
  12893. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  12894. if (B.isNaN())
  12895. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  12896. Recalc = true;
  12897. }
  12898. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  12899. AD.isInfinity() || BC.isInfinity())) {
  12900. if (A.isNaN())
  12901. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  12902. if (B.isNaN())
  12903. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  12904. if (C.isNaN())
  12905. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  12906. if (D.isNaN())
  12907. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  12908. Recalc = true;
  12909. }
  12910. if (Recalc) {
  12911. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  12912. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  12913. }
  12914. }
  12915. }
  12916. } else {
  12917. ComplexValue LHS = Result;
  12918. Result.getComplexIntReal() =
  12919. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  12920. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  12921. Result.getComplexIntImag() =
  12922. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  12923. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  12924. }
  12925. break;
  12926. case BO_Div:
  12927. if (Result.isComplexFloat()) {
  12928. // This is an implementation of complex division according to the
  12929. // constraints laid out in C11 Annex G. The implementation uses the
  12930. // following naming scheme:
  12931. // (a + ib) / (c + id)
  12932. ComplexValue LHS = Result;
  12933. APFloat &A = LHS.getComplexFloatReal();
  12934. APFloat &B = LHS.getComplexFloatImag();
  12935. APFloat &C = RHS.getComplexFloatReal();
  12936. APFloat &D = RHS.getComplexFloatImag();
  12937. APFloat &ResR = Result.getComplexFloatReal();
  12938. APFloat &ResI = Result.getComplexFloatImag();
  12939. if (RHSReal) {
  12940. ResR = A / C;
  12941. ResI = B / C;
  12942. } else {
  12943. if (LHSReal) {
  12944. // No real optimizations we can do here, stub out with zero.
  12945. B = APFloat::getZero(A.getSemantics());
  12946. }
  12947. int DenomLogB = 0;
  12948. APFloat MaxCD = maxnum(abs(C), abs(D));
  12949. if (MaxCD.isFinite()) {
  12950. DenomLogB = ilogb(MaxCD);
  12951. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  12952. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  12953. }
  12954. APFloat Denom = C * C + D * D;
  12955. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  12956. APFloat::rmNearestTiesToEven);
  12957. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  12958. APFloat::rmNearestTiesToEven);
  12959. if (ResR.isNaN() && ResI.isNaN()) {
  12960. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  12961. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  12962. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  12963. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  12964. D.isFinite()) {
  12965. A = APFloat::copySign(
  12966. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  12967. B = APFloat::copySign(
  12968. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  12969. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  12970. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  12971. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  12972. C = APFloat::copySign(
  12973. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  12974. D = APFloat::copySign(
  12975. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  12976. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  12977. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  12978. }
  12979. }
  12980. }
  12981. } else {
  12982. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  12983. return Error(E, diag::note_expr_divide_by_zero);
  12984. ComplexValue LHS = Result;
  12985. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  12986. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  12987. Result.getComplexIntReal() =
  12988. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  12989. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  12990. Result.getComplexIntImag() =
  12991. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  12992. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  12993. }
  12994. break;
  12995. }
  12996. return true;
  12997. }
  12998. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  12999. // Get the operand value into 'Result'.
  13000. if (!Visit(E->getSubExpr()))
  13001. return false;
  13002. switch (E->getOpcode()) {
  13003. default:
  13004. return Error(E);
  13005. case UO_Extension:
  13006. return true;
  13007. case UO_Plus:
  13008. // The result is always just the subexpr.
  13009. return true;
  13010. case UO_Minus:
  13011. if (Result.isComplexFloat()) {
  13012. Result.getComplexFloatReal().changeSign();
  13013. Result.getComplexFloatImag().changeSign();
  13014. }
  13015. else {
  13016. Result.getComplexIntReal() = -Result.getComplexIntReal();
  13017. Result.getComplexIntImag() = -Result.getComplexIntImag();
  13018. }
  13019. return true;
  13020. case UO_Not:
  13021. if (Result.isComplexFloat())
  13022. Result.getComplexFloatImag().changeSign();
  13023. else
  13024. Result.getComplexIntImag() = -Result.getComplexIntImag();
  13025. return true;
  13026. }
  13027. }
  13028. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  13029. if (E->getNumInits() == 2) {
  13030. if (E->getType()->isComplexType()) {
  13031. Result.makeComplexFloat();
  13032. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  13033. return false;
  13034. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  13035. return false;
  13036. } else {
  13037. Result.makeComplexInt();
  13038. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  13039. return false;
  13040. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  13041. return false;
  13042. }
  13043. return true;
  13044. }
  13045. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  13046. }
  13047. bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
  13048. if (!IsConstantEvaluatedBuiltinCall(E))
  13049. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  13050. switch (E->getBuiltinCallee()) {
  13051. case Builtin::BI__builtin_complex:
  13052. Result.makeComplexFloat();
  13053. if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
  13054. return false;
  13055. if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
  13056. return false;
  13057. return true;
  13058. default:
  13059. return false;
  13060. }
  13061. }
  13062. //===----------------------------------------------------------------------===//
  13063. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  13064. // implicit conversion.
  13065. //===----------------------------------------------------------------------===//
  13066. namespace {
  13067. class AtomicExprEvaluator :
  13068. public ExprEvaluatorBase<AtomicExprEvaluator> {
  13069. const LValue *This;
  13070. APValue &Result;
  13071. public:
  13072. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  13073. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  13074. bool Success(const APValue &V, const Expr *E) {
  13075. Result = V;
  13076. return true;
  13077. }
  13078. bool ZeroInitialization(const Expr *E) {
  13079. ImplicitValueInitExpr VIE(
  13080. E->getType()->castAs<AtomicType>()->getValueType());
  13081. // For atomic-qualified class (and array) types in C++, initialize the
  13082. // _Atomic-wrapped subobject directly, in-place.
  13083. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  13084. : Evaluate(Result, Info, &VIE);
  13085. }
  13086. bool VisitCastExpr(const CastExpr *E) {
  13087. switch (E->getCastKind()) {
  13088. default:
  13089. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  13090. case CK_NonAtomicToAtomic:
  13091. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  13092. : Evaluate(Result, Info, E->getSubExpr());
  13093. }
  13094. }
  13095. };
  13096. } // end anonymous namespace
  13097. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  13098. EvalInfo &Info) {
  13099. assert(!E->isValueDependent());
  13100. assert(E->isPRValue() && E->getType()->isAtomicType());
  13101. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  13102. }
  13103. //===----------------------------------------------------------------------===//
  13104. // Void expression evaluation, primarily for a cast to void on the LHS of a
  13105. // comma operator
  13106. //===----------------------------------------------------------------------===//
  13107. namespace {
  13108. class VoidExprEvaluator
  13109. : public ExprEvaluatorBase<VoidExprEvaluator> {
  13110. public:
  13111. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  13112. bool Success(const APValue &V, const Expr *e) { return true; }
  13113. bool ZeroInitialization(const Expr *E) { return true; }
  13114. bool VisitCastExpr(const CastExpr *E) {
  13115. switch (E->getCastKind()) {
  13116. default:
  13117. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  13118. case CK_ToVoid:
  13119. VisitIgnoredValue(E->getSubExpr());
  13120. return true;
  13121. }
  13122. }
  13123. bool VisitCallExpr(const CallExpr *E) {
  13124. if (!IsConstantEvaluatedBuiltinCall(E))
  13125. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  13126. switch (E->getBuiltinCallee()) {
  13127. case Builtin::BI__assume:
  13128. case Builtin::BI__builtin_assume:
  13129. // The argument is not evaluated!
  13130. return true;
  13131. case Builtin::BI__builtin_operator_delete:
  13132. return HandleOperatorDeleteCall(Info, E);
  13133. default:
  13134. return false;
  13135. }
  13136. }
  13137. bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
  13138. };
  13139. } // end anonymous namespace
  13140. bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  13141. // We cannot speculatively evaluate a delete expression.
  13142. if (Info.SpeculativeEvaluationDepth)
  13143. return false;
  13144. FunctionDecl *OperatorDelete = E->getOperatorDelete();
  13145. if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
  13146. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  13147. << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
  13148. return false;
  13149. }
  13150. const Expr *Arg = E->getArgument();
  13151. LValue Pointer;
  13152. if (!EvaluatePointer(Arg, Pointer, Info))
  13153. return false;
  13154. if (Pointer.Designator.Invalid)
  13155. return false;
  13156. // Deleting a null pointer has no effect.
  13157. if (Pointer.isNullPointer()) {
  13158. // This is the only case where we need to produce an extension warning:
  13159. // the only other way we can succeed is if we find a dynamic allocation,
  13160. // and we will have warned when we allocated it in that case.
  13161. if (!Info.getLangOpts().CPlusPlus20)
  13162. Info.CCEDiag(E, diag::note_constexpr_new);
  13163. return true;
  13164. }
  13165. std::optional<DynAlloc *> Alloc = CheckDeleteKind(
  13166. Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
  13167. if (!Alloc)
  13168. return false;
  13169. QualType AllocType = Pointer.Base.getDynamicAllocType();
  13170. // For the non-array case, the designator must be empty if the static type
  13171. // does not have a virtual destructor.
  13172. if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
  13173. !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
  13174. Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
  13175. << Arg->getType()->getPointeeType() << AllocType;
  13176. return false;
  13177. }
  13178. // For a class type with a virtual destructor, the selected operator delete
  13179. // is the one looked up when building the destructor.
  13180. if (!E->isArrayForm() && !E->isGlobalDelete()) {
  13181. const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
  13182. if (VirtualDelete &&
  13183. !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
  13184. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  13185. << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
  13186. return false;
  13187. }
  13188. }
  13189. if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
  13190. (*Alloc)->Value, AllocType))
  13191. return false;
  13192. if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
  13193. // The element was already erased. This means the destructor call also
  13194. // deleted the object.
  13195. // FIXME: This probably results in undefined behavior before we get this
  13196. // far, and should be diagnosed elsewhere first.
  13197. Info.FFDiag(E, diag::note_constexpr_double_delete);
  13198. return false;
  13199. }
  13200. return true;
  13201. }
  13202. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  13203. assert(!E->isValueDependent());
  13204. assert(E->isPRValue() && E->getType()->isVoidType());
  13205. return VoidExprEvaluator(Info).Visit(E);
  13206. }
  13207. //===----------------------------------------------------------------------===//
  13208. // Top level Expr::EvaluateAsRValue method.
  13209. //===----------------------------------------------------------------------===//
  13210. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  13211. assert(!E->isValueDependent());
  13212. // In C, function designators are not lvalues, but we evaluate them as if they
  13213. // are.
  13214. QualType T = E->getType();
  13215. if (E->isGLValue() || T->isFunctionType()) {
  13216. LValue LV;
  13217. if (!EvaluateLValue(E, LV, Info))
  13218. return false;
  13219. LV.moveInto(Result);
  13220. } else if (T->isVectorType()) {
  13221. if (!EvaluateVector(E, Result, Info))
  13222. return false;
  13223. } else if (T->isIntegralOrEnumerationType()) {
  13224. if (!IntExprEvaluator(Info, Result).Visit(E))
  13225. return false;
  13226. } else if (T->hasPointerRepresentation()) {
  13227. LValue LV;
  13228. if (!EvaluatePointer(E, LV, Info))
  13229. return false;
  13230. LV.moveInto(Result);
  13231. } else if (T->isRealFloatingType()) {
  13232. llvm::APFloat F(0.0);
  13233. if (!EvaluateFloat(E, F, Info))
  13234. return false;
  13235. Result = APValue(F);
  13236. } else if (T->isAnyComplexType()) {
  13237. ComplexValue C;
  13238. if (!EvaluateComplex(E, C, Info))
  13239. return false;
  13240. C.moveInto(Result);
  13241. } else if (T->isFixedPointType()) {
  13242. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  13243. } else if (T->isMemberPointerType()) {
  13244. MemberPtr P;
  13245. if (!EvaluateMemberPointer(E, P, Info))
  13246. return false;
  13247. P.moveInto(Result);
  13248. return true;
  13249. } else if (T->isArrayType()) {
  13250. LValue LV;
  13251. APValue &Value =
  13252. Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
  13253. if (!EvaluateArray(E, LV, Value, Info))
  13254. return false;
  13255. Result = Value;
  13256. } else if (T->isRecordType()) {
  13257. LValue LV;
  13258. APValue &Value =
  13259. Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
  13260. if (!EvaluateRecord(E, LV, Value, Info))
  13261. return false;
  13262. Result = Value;
  13263. } else if (T->isVoidType()) {
  13264. if (!Info.getLangOpts().CPlusPlus11)
  13265. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  13266. << E->getType();
  13267. if (!EvaluateVoid(E, Info))
  13268. return false;
  13269. } else if (T->isAtomicType()) {
  13270. QualType Unqual = T.getAtomicUnqualifiedType();
  13271. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  13272. LValue LV;
  13273. APValue &Value = Info.CurrentCall->createTemporary(
  13274. E, Unqual, ScopeKind::FullExpression, LV);
  13275. if (!EvaluateAtomic(E, &LV, Value, Info))
  13276. return false;
  13277. } else {
  13278. if (!EvaluateAtomic(E, nullptr, Result, Info))
  13279. return false;
  13280. }
  13281. } else if (Info.getLangOpts().CPlusPlus11) {
  13282. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  13283. return false;
  13284. } else {
  13285. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  13286. return false;
  13287. }
  13288. return true;
  13289. }
  13290. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  13291. /// cases, the in-place evaluation is essential, since later initializers for
  13292. /// an object can indirectly refer to subobjects which were initialized earlier.
  13293. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  13294. const Expr *E, bool AllowNonLiteralTypes) {
  13295. assert(!E->isValueDependent());
  13296. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  13297. return false;
  13298. if (E->isPRValue()) {
  13299. // Evaluate arrays and record types in-place, so that later initializers can
  13300. // refer to earlier-initialized members of the object.
  13301. QualType T = E->getType();
  13302. if (T->isArrayType())
  13303. return EvaluateArray(E, This, Result, Info);
  13304. else if (T->isRecordType())
  13305. return EvaluateRecord(E, This, Result, Info);
  13306. else if (T->isAtomicType()) {
  13307. QualType Unqual = T.getAtomicUnqualifiedType();
  13308. if (Unqual->isArrayType() || Unqual->isRecordType())
  13309. return EvaluateAtomic(E, &This, Result, Info);
  13310. }
  13311. }
  13312. // For any other type, in-place evaluation is unimportant.
  13313. return Evaluate(Result, Info, E);
  13314. }
  13315. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  13316. /// lvalue-to-rvalue cast if it is an lvalue.
  13317. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  13318. assert(!E->isValueDependent());
  13319. if (E->getType().isNull())
  13320. return false;
  13321. if (!CheckLiteralType(Info, E))
  13322. return false;
  13323. if (Info.EnableNewConstInterp) {
  13324. if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
  13325. return false;
  13326. } else {
  13327. if (!::Evaluate(Result, Info, E))
  13328. return false;
  13329. }
  13330. // Implicit lvalue-to-rvalue cast.
  13331. if (E->isGLValue()) {
  13332. LValue LV;
  13333. LV.setFrom(Info.Ctx, Result);
  13334. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  13335. return false;
  13336. }
  13337. // Check this core constant expression is a constant expression.
  13338. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
  13339. ConstantExprKind::Normal) &&
  13340. CheckMemoryLeaks(Info);
  13341. }
  13342. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  13343. const ASTContext &Ctx, bool &IsConst) {
  13344. // Fast-path evaluations of integer literals, since we sometimes see files
  13345. // containing vast quantities of these.
  13346. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  13347. Result.Val = APValue(APSInt(L->getValue(),
  13348. L->getType()->isUnsignedIntegerType()));
  13349. IsConst = true;
  13350. return true;
  13351. }
  13352. if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
  13353. Result.Val = APValue(APSInt(APInt(1, L->getValue())));
  13354. IsConst = true;
  13355. return true;
  13356. }
  13357. // This case should be rare, but we need to check it before we check on
  13358. // the type below.
  13359. if (Exp->getType().isNull()) {
  13360. IsConst = false;
  13361. return true;
  13362. }
  13363. // FIXME: Evaluating values of large array and record types can cause
  13364. // performance problems. Only do so in C++11 for now.
  13365. if (Exp->isPRValue() &&
  13366. (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
  13367. !Ctx.getLangOpts().CPlusPlus11) {
  13368. IsConst = false;
  13369. return true;
  13370. }
  13371. return false;
  13372. }
  13373. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  13374. Expr::SideEffectsKind SEK) {
  13375. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  13376. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  13377. }
  13378. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  13379. const ASTContext &Ctx, EvalInfo &Info) {
  13380. assert(!E->isValueDependent());
  13381. bool IsConst;
  13382. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  13383. return IsConst;
  13384. return EvaluateAsRValue(Info, E, Result.Val);
  13385. }
  13386. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  13387. const ASTContext &Ctx,
  13388. Expr::SideEffectsKind AllowSideEffects,
  13389. EvalInfo &Info) {
  13390. assert(!E->isValueDependent());
  13391. if (!E->getType()->isIntegralOrEnumerationType())
  13392. return false;
  13393. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  13394. !ExprResult.Val.isInt() ||
  13395. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  13396. return false;
  13397. return true;
  13398. }
  13399. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  13400. const ASTContext &Ctx,
  13401. Expr::SideEffectsKind AllowSideEffects,
  13402. EvalInfo &Info) {
  13403. assert(!E->isValueDependent());
  13404. if (!E->getType()->isFixedPointType())
  13405. return false;
  13406. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  13407. return false;
  13408. if (!ExprResult.Val.isFixedPoint() ||
  13409. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  13410. return false;
  13411. return true;
  13412. }
  13413. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  13414. /// any crazy technique (that has nothing to do with language standards) that
  13415. /// we want to. If this function returns true, it returns the folded constant
  13416. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  13417. /// will be applied to the result.
  13418. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  13419. bool InConstantContext) const {
  13420. assert(!isValueDependent() &&
  13421. "Expression evaluator can't be called on a dependent expression.");
  13422. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
  13423. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  13424. Info.InConstantContext = InConstantContext;
  13425. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  13426. }
  13427. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  13428. bool InConstantContext) const {
  13429. assert(!isValueDependent() &&
  13430. "Expression evaluator can't be called on a dependent expression.");
  13431. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
  13432. EvalResult Scratch;
  13433. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  13434. HandleConversionToBool(Scratch.Val, Result);
  13435. }
  13436. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  13437. SideEffectsKind AllowSideEffects,
  13438. bool InConstantContext) const {
  13439. assert(!isValueDependent() &&
  13440. "Expression evaluator can't be called on a dependent expression.");
  13441. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
  13442. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  13443. Info.InConstantContext = InConstantContext;
  13444. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  13445. }
  13446. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  13447. SideEffectsKind AllowSideEffects,
  13448. bool InConstantContext) const {
  13449. assert(!isValueDependent() &&
  13450. "Expression evaluator can't be called on a dependent expression.");
  13451. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
  13452. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  13453. Info.InConstantContext = InConstantContext;
  13454. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  13455. }
  13456. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  13457. SideEffectsKind AllowSideEffects,
  13458. bool InConstantContext) const {
  13459. assert(!isValueDependent() &&
  13460. "Expression evaluator can't be called on a dependent expression.");
  13461. if (!getType()->isRealFloatingType())
  13462. return false;
  13463. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
  13464. EvalResult ExprResult;
  13465. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  13466. !ExprResult.Val.isFloat() ||
  13467. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  13468. return false;
  13469. Result = ExprResult.Val.getFloat();
  13470. return true;
  13471. }
  13472. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  13473. bool InConstantContext) const {
  13474. assert(!isValueDependent() &&
  13475. "Expression evaluator can't be called on a dependent expression.");
  13476. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
  13477. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  13478. Info.InConstantContext = InConstantContext;
  13479. LValue LV;
  13480. CheckedTemporaries CheckedTemps;
  13481. if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
  13482. Result.HasSideEffects ||
  13483. !CheckLValueConstantExpression(Info, getExprLoc(),
  13484. Ctx.getLValueReferenceType(getType()), LV,
  13485. ConstantExprKind::Normal, CheckedTemps))
  13486. return false;
  13487. LV.moveInto(Result.Val);
  13488. return true;
  13489. }
  13490. static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
  13491. APValue DestroyedValue, QualType Type,
  13492. SourceLocation Loc, Expr::EvalStatus &EStatus,
  13493. bool IsConstantDestruction) {
  13494. EvalInfo Info(Ctx, EStatus,
  13495. IsConstantDestruction ? EvalInfo::EM_ConstantExpression
  13496. : EvalInfo::EM_ConstantFold);
  13497. Info.setEvaluatingDecl(Base, DestroyedValue,
  13498. EvalInfo::EvaluatingDeclKind::Dtor);
  13499. Info.InConstantContext = IsConstantDestruction;
  13500. LValue LVal;
  13501. LVal.set(Base);
  13502. if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
  13503. EStatus.HasSideEffects)
  13504. return false;
  13505. if (!Info.discardCleanups())
  13506. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  13507. return true;
  13508. }
  13509. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
  13510. ConstantExprKind Kind) const {
  13511. assert(!isValueDependent() &&
  13512. "Expression evaluator can't be called on a dependent expression.");
  13513. bool IsConst;
  13514. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
  13515. return true;
  13516. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
  13517. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  13518. EvalInfo Info(Ctx, Result, EM);
  13519. Info.InConstantContext = true;
  13520. // The type of the object we're initializing is 'const T' for a class NTTP.
  13521. QualType T = getType();
  13522. if (Kind == ConstantExprKind::ClassTemplateArgument)
  13523. T.addConst();
  13524. // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
  13525. // represent the result of the evaluation. CheckConstantExpression ensures
  13526. // this doesn't escape.
  13527. MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
  13528. APValue::LValueBase Base(&BaseMTE);
  13529. Info.setEvaluatingDecl(Base, Result.Val);
  13530. LValue LVal;
  13531. LVal.set(Base);
  13532. if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
  13533. return false;
  13534. if (!Info.discardCleanups())
  13535. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  13536. if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
  13537. Result.Val, Kind))
  13538. return false;
  13539. if (!CheckMemoryLeaks(Info))
  13540. return false;
  13541. // If this is a class template argument, it's required to have constant
  13542. // destruction too.
  13543. if (Kind == ConstantExprKind::ClassTemplateArgument &&
  13544. (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
  13545. true) ||
  13546. Result.HasSideEffects)) {
  13547. // FIXME: Prefix a note to indicate that the problem is lack of constant
  13548. // destruction.
  13549. return false;
  13550. }
  13551. return true;
  13552. }
  13553. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  13554. const VarDecl *VD,
  13555. SmallVectorImpl<PartialDiagnosticAt> &Notes,
  13556. bool IsConstantInitialization) const {
  13557. assert(!isValueDependent() &&
  13558. "Expression evaluator can't be called on a dependent expression.");
  13559. llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
  13560. std::string Name;
  13561. llvm::raw_string_ostream OS(Name);
  13562. VD->printQualifiedName(OS);
  13563. return Name;
  13564. });
  13565. // FIXME: Evaluating initializers for large array and record types can cause
  13566. // performance problems. Only do so in C++11 for now.
  13567. if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  13568. !Ctx.getLangOpts().CPlusPlus11)
  13569. return false;
  13570. Expr::EvalStatus EStatus;
  13571. EStatus.Diag = &Notes;
  13572. EvalInfo Info(Ctx, EStatus,
  13573. (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
  13574. ? EvalInfo::EM_ConstantExpression
  13575. : EvalInfo::EM_ConstantFold);
  13576. Info.setEvaluatingDecl(VD, Value);
  13577. Info.InConstantContext = IsConstantInitialization;
  13578. SourceLocation DeclLoc = VD->getLocation();
  13579. QualType DeclTy = VD->getType();
  13580. if (Info.EnableNewConstInterp) {
  13581. auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
  13582. if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
  13583. return false;
  13584. } else {
  13585. LValue LVal;
  13586. LVal.set(VD);
  13587. if (!EvaluateInPlace(Value, Info, LVal, this,
  13588. /*AllowNonLiteralTypes=*/true) ||
  13589. EStatus.HasSideEffects)
  13590. return false;
  13591. // At this point, any lifetime-extended temporaries are completely
  13592. // initialized.
  13593. Info.performLifetimeExtension();
  13594. if (!Info.discardCleanups())
  13595. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  13596. }
  13597. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
  13598. ConstantExprKind::Normal) &&
  13599. CheckMemoryLeaks(Info);
  13600. }
  13601. bool VarDecl::evaluateDestruction(
  13602. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  13603. Expr::EvalStatus EStatus;
  13604. EStatus.Diag = &Notes;
  13605. // Only treat the destruction as constant destruction if we formally have
  13606. // constant initialization (or are usable in a constant expression).
  13607. bool IsConstantDestruction = hasConstantInitialization();
  13608. // Make a copy of the value for the destructor to mutate, if we know it.
  13609. // Otherwise, treat the value as default-initialized; if the destructor works
  13610. // anyway, then the destruction is constant (and must be essentially empty).
  13611. APValue DestroyedValue;
  13612. if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
  13613. DestroyedValue = *getEvaluatedValue();
  13614. else if (!getDefaultInitValue(getType(), DestroyedValue))
  13615. return false;
  13616. if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
  13617. getType(), getLocation(), EStatus,
  13618. IsConstantDestruction) ||
  13619. EStatus.HasSideEffects)
  13620. return false;
  13621. ensureEvaluatedStmt()->HasConstantDestruction = true;
  13622. return true;
  13623. }
  13624. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  13625. /// constant folded, but discard the result.
  13626. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  13627. assert(!isValueDependent() &&
  13628. "Expression evaluator can't be called on a dependent expression.");
  13629. EvalResult Result;
  13630. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  13631. !hasUnacceptableSideEffect(Result, SEK);
  13632. }
  13633. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  13634. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  13635. assert(!isValueDependent() &&
  13636. "Expression evaluator can't be called on a dependent expression.");
  13637. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
  13638. EvalResult EVResult;
  13639. EVResult.Diag = Diag;
  13640. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  13641. Info.InConstantContext = true;
  13642. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  13643. (void)Result;
  13644. assert(Result && "Could not evaluate expression");
  13645. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  13646. return EVResult.Val.getInt();
  13647. }
  13648. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  13649. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  13650. assert(!isValueDependent() &&
  13651. "Expression evaluator can't be called on a dependent expression.");
  13652. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
  13653. EvalResult EVResult;
  13654. EVResult.Diag = Diag;
  13655. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  13656. Info.InConstantContext = true;
  13657. Info.CheckingForUndefinedBehavior = true;
  13658. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  13659. (void)Result;
  13660. assert(Result && "Could not evaluate expression");
  13661. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  13662. return EVResult.Val.getInt();
  13663. }
  13664. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  13665. assert(!isValueDependent() &&
  13666. "Expression evaluator can't be called on a dependent expression.");
  13667. ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
  13668. bool IsConst;
  13669. EvalResult EVResult;
  13670. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  13671. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  13672. Info.CheckingForUndefinedBehavior = true;
  13673. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  13674. }
  13675. }
  13676. bool Expr::EvalResult::isGlobalLValue() const {
  13677. assert(Val.isLValue());
  13678. return IsGlobalLValue(Val.getLValueBase());
  13679. }
  13680. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  13681. /// an integer constant expression.
  13682. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  13683. /// comma, etc
  13684. // CheckICE - This function does the fundamental ICE checking: the returned
  13685. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  13686. // and a (possibly null) SourceLocation indicating the location of the problem.
  13687. //
  13688. // Note that to reduce code duplication, this helper does no evaluation
  13689. // itself; the caller checks whether the expression is evaluatable, and
  13690. // in the rare cases where CheckICE actually cares about the evaluated
  13691. // value, it calls into Evaluate.
  13692. namespace {
  13693. enum ICEKind {
  13694. /// This expression is an ICE.
  13695. IK_ICE,
  13696. /// This expression is not an ICE, but if it isn't evaluated, it's
  13697. /// a legal subexpression for an ICE. This return value is used to handle
  13698. /// the comma operator in C99 mode, and non-constant subexpressions.
  13699. IK_ICEIfUnevaluated,
  13700. /// This expression is not an ICE, and is not a legal subexpression for one.
  13701. IK_NotICE
  13702. };
  13703. struct ICEDiag {
  13704. ICEKind Kind;
  13705. SourceLocation Loc;
  13706. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  13707. };
  13708. }
  13709. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  13710. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  13711. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  13712. Expr::EvalResult EVResult;
  13713. Expr::EvalStatus Status;
  13714. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  13715. Info.InConstantContext = true;
  13716. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  13717. !EVResult.Val.isInt())
  13718. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13719. return NoDiag();
  13720. }
  13721. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  13722. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  13723. if (!E->getType()->isIntegralOrEnumerationType())
  13724. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13725. switch (E->getStmtClass()) {
  13726. #define ABSTRACT_STMT(Node)
  13727. #define STMT(Node, Base) case Expr::Node##Class:
  13728. #define EXPR(Node, Base)
  13729. #include "clang/AST/StmtNodes.inc"
  13730. case Expr::PredefinedExprClass:
  13731. case Expr::FloatingLiteralClass:
  13732. case Expr::ImaginaryLiteralClass:
  13733. case Expr::StringLiteralClass:
  13734. case Expr::ArraySubscriptExprClass:
  13735. case Expr::MatrixSubscriptExprClass:
  13736. case Expr::OMPArraySectionExprClass:
  13737. case Expr::OMPArrayShapingExprClass:
  13738. case Expr::OMPIteratorExprClass:
  13739. case Expr::MemberExprClass:
  13740. case Expr::CompoundAssignOperatorClass:
  13741. case Expr::CompoundLiteralExprClass:
  13742. case Expr::ExtVectorElementExprClass:
  13743. case Expr::DesignatedInitExprClass:
  13744. case Expr::ArrayInitLoopExprClass:
  13745. case Expr::ArrayInitIndexExprClass:
  13746. case Expr::NoInitExprClass:
  13747. case Expr::DesignatedInitUpdateExprClass:
  13748. case Expr::ImplicitValueInitExprClass:
  13749. case Expr::ParenListExprClass:
  13750. case Expr::VAArgExprClass:
  13751. case Expr::AddrLabelExprClass:
  13752. case Expr::StmtExprClass:
  13753. case Expr::CXXMemberCallExprClass:
  13754. case Expr::CUDAKernelCallExprClass:
  13755. case Expr::CXXAddrspaceCastExprClass:
  13756. case Expr::CXXDynamicCastExprClass:
  13757. case Expr::CXXTypeidExprClass:
  13758. case Expr::CXXUuidofExprClass:
  13759. case Expr::MSPropertyRefExprClass:
  13760. case Expr::MSPropertySubscriptExprClass:
  13761. case Expr::CXXNullPtrLiteralExprClass:
  13762. case Expr::UserDefinedLiteralClass:
  13763. case Expr::CXXThisExprClass:
  13764. case Expr::CXXThrowExprClass:
  13765. case Expr::CXXNewExprClass:
  13766. case Expr::CXXDeleteExprClass:
  13767. case Expr::CXXPseudoDestructorExprClass:
  13768. case Expr::UnresolvedLookupExprClass:
  13769. case Expr::TypoExprClass:
  13770. case Expr::RecoveryExprClass:
  13771. case Expr::DependentScopeDeclRefExprClass:
  13772. case Expr::CXXConstructExprClass:
  13773. case Expr::CXXInheritedCtorInitExprClass:
  13774. case Expr::CXXStdInitializerListExprClass:
  13775. case Expr::CXXBindTemporaryExprClass:
  13776. case Expr::ExprWithCleanupsClass:
  13777. case Expr::CXXTemporaryObjectExprClass:
  13778. case Expr::CXXUnresolvedConstructExprClass:
  13779. case Expr::CXXDependentScopeMemberExprClass:
  13780. case Expr::UnresolvedMemberExprClass:
  13781. case Expr::ObjCStringLiteralClass:
  13782. case Expr::ObjCBoxedExprClass:
  13783. case Expr::ObjCArrayLiteralClass:
  13784. case Expr::ObjCDictionaryLiteralClass:
  13785. case Expr::ObjCEncodeExprClass:
  13786. case Expr::ObjCMessageExprClass:
  13787. case Expr::ObjCSelectorExprClass:
  13788. case Expr::ObjCProtocolExprClass:
  13789. case Expr::ObjCIvarRefExprClass:
  13790. case Expr::ObjCPropertyRefExprClass:
  13791. case Expr::ObjCSubscriptRefExprClass:
  13792. case Expr::ObjCIsaExprClass:
  13793. case Expr::ObjCAvailabilityCheckExprClass:
  13794. case Expr::ShuffleVectorExprClass:
  13795. case Expr::ConvertVectorExprClass:
  13796. case Expr::BlockExprClass:
  13797. case Expr::NoStmtClass:
  13798. case Expr::OpaqueValueExprClass:
  13799. case Expr::PackExpansionExprClass:
  13800. case Expr::SubstNonTypeTemplateParmPackExprClass:
  13801. case Expr::FunctionParmPackExprClass:
  13802. case Expr::AsTypeExprClass:
  13803. case Expr::ObjCIndirectCopyRestoreExprClass:
  13804. case Expr::MaterializeTemporaryExprClass:
  13805. case Expr::PseudoObjectExprClass:
  13806. case Expr::AtomicExprClass:
  13807. case Expr::LambdaExprClass:
  13808. case Expr::CXXFoldExprClass:
  13809. case Expr::CoawaitExprClass:
  13810. case Expr::DependentCoawaitExprClass:
  13811. case Expr::CoyieldExprClass:
  13812. case Expr::SYCLUniqueStableNameExprClass:
  13813. case Expr::CXXParenListInitExprClass:
  13814. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13815. case Expr::InitListExprClass: {
  13816. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  13817. // form "T x = { a };" is equivalent to "T x = a;".
  13818. // Unless we're initializing a reference, T is a scalar as it is known to be
  13819. // of integral or enumeration type.
  13820. if (E->isPRValue())
  13821. if (cast<InitListExpr>(E)->getNumInits() == 1)
  13822. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  13823. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13824. }
  13825. case Expr::SizeOfPackExprClass:
  13826. case Expr::GNUNullExprClass:
  13827. case Expr::SourceLocExprClass:
  13828. return NoDiag();
  13829. case Expr::SubstNonTypeTemplateParmExprClass:
  13830. return
  13831. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  13832. case Expr::ConstantExprClass:
  13833. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  13834. case Expr::ParenExprClass:
  13835. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  13836. case Expr::GenericSelectionExprClass:
  13837. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  13838. case Expr::IntegerLiteralClass:
  13839. case Expr::FixedPointLiteralClass:
  13840. case Expr::CharacterLiteralClass:
  13841. case Expr::ObjCBoolLiteralExprClass:
  13842. case Expr::CXXBoolLiteralExprClass:
  13843. case Expr::CXXScalarValueInitExprClass:
  13844. case Expr::TypeTraitExprClass:
  13845. case Expr::ConceptSpecializationExprClass:
  13846. case Expr::RequiresExprClass:
  13847. case Expr::ArrayTypeTraitExprClass:
  13848. case Expr::ExpressionTraitExprClass:
  13849. case Expr::CXXNoexceptExprClass:
  13850. return NoDiag();
  13851. case Expr::CallExprClass:
  13852. case Expr::CXXOperatorCallExprClass: {
  13853. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  13854. // constant expressions, but they can never be ICEs because an ICE cannot
  13855. // contain an operand of (pointer to) function type.
  13856. const CallExpr *CE = cast<CallExpr>(E);
  13857. if (CE->getBuiltinCallee())
  13858. return CheckEvalInICE(E, Ctx);
  13859. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13860. }
  13861. case Expr::CXXRewrittenBinaryOperatorClass:
  13862. return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
  13863. Ctx);
  13864. case Expr::DeclRefExprClass: {
  13865. const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
  13866. if (isa<EnumConstantDecl>(D))
  13867. return NoDiag();
  13868. // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
  13869. // integer variables in constant expressions:
  13870. //
  13871. // C++ 7.1.5.1p2
  13872. // A variable of non-volatile const-qualified integral or enumeration
  13873. // type initialized by an ICE can be used in ICEs.
  13874. //
  13875. // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
  13876. // that mode, use of reference variables should not be allowed.
  13877. const VarDecl *VD = dyn_cast<VarDecl>(D);
  13878. if (VD && VD->isUsableInConstantExpressions(Ctx) &&
  13879. !VD->getType()->isReferenceType())
  13880. return NoDiag();
  13881. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13882. }
  13883. case Expr::UnaryOperatorClass: {
  13884. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  13885. switch (Exp->getOpcode()) {
  13886. case UO_PostInc:
  13887. case UO_PostDec:
  13888. case UO_PreInc:
  13889. case UO_PreDec:
  13890. case UO_AddrOf:
  13891. case UO_Deref:
  13892. case UO_Coawait:
  13893. // C99 6.6/3 allows increment and decrement within unevaluated
  13894. // subexpressions of constant expressions, but they can never be ICEs
  13895. // because an ICE cannot contain an lvalue operand.
  13896. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13897. case UO_Extension:
  13898. case UO_LNot:
  13899. case UO_Plus:
  13900. case UO_Minus:
  13901. case UO_Not:
  13902. case UO_Real:
  13903. case UO_Imag:
  13904. return CheckICE(Exp->getSubExpr(), Ctx);
  13905. }
  13906. llvm_unreachable("invalid unary operator class");
  13907. }
  13908. case Expr::OffsetOfExprClass: {
  13909. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  13910. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  13911. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  13912. // compliance: we should warn earlier for offsetof expressions with
  13913. // array subscripts that aren't ICEs, and if the array subscripts
  13914. // are ICEs, the value of the offsetof must be an integer constant.
  13915. return CheckEvalInICE(E, Ctx);
  13916. }
  13917. case Expr::UnaryExprOrTypeTraitExprClass: {
  13918. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  13919. if ((Exp->getKind() == UETT_SizeOf) &&
  13920. Exp->getTypeOfArgument()->isVariableArrayType())
  13921. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13922. return NoDiag();
  13923. }
  13924. case Expr::BinaryOperatorClass: {
  13925. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  13926. switch (Exp->getOpcode()) {
  13927. case BO_PtrMemD:
  13928. case BO_PtrMemI:
  13929. case BO_Assign:
  13930. case BO_MulAssign:
  13931. case BO_DivAssign:
  13932. case BO_RemAssign:
  13933. case BO_AddAssign:
  13934. case BO_SubAssign:
  13935. case BO_ShlAssign:
  13936. case BO_ShrAssign:
  13937. case BO_AndAssign:
  13938. case BO_XorAssign:
  13939. case BO_OrAssign:
  13940. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  13941. // constant expressions, but they can never be ICEs because an ICE cannot
  13942. // contain an lvalue operand.
  13943. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13944. case BO_Mul:
  13945. case BO_Div:
  13946. case BO_Rem:
  13947. case BO_Add:
  13948. case BO_Sub:
  13949. case BO_Shl:
  13950. case BO_Shr:
  13951. case BO_LT:
  13952. case BO_GT:
  13953. case BO_LE:
  13954. case BO_GE:
  13955. case BO_EQ:
  13956. case BO_NE:
  13957. case BO_And:
  13958. case BO_Xor:
  13959. case BO_Or:
  13960. case BO_Comma:
  13961. case BO_Cmp: {
  13962. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  13963. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  13964. if (Exp->getOpcode() == BO_Div ||
  13965. Exp->getOpcode() == BO_Rem) {
  13966. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  13967. // we don't evaluate one.
  13968. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  13969. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  13970. if (REval == 0)
  13971. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  13972. if (REval.isSigned() && REval.isAllOnes()) {
  13973. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  13974. if (LEval.isMinSignedValue())
  13975. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  13976. }
  13977. }
  13978. }
  13979. if (Exp->getOpcode() == BO_Comma) {
  13980. if (Ctx.getLangOpts().C99) {
  13981. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  13982. // if it isn't evaluated.
  13983. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  13984. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  13985. } else {
  13986. // In both C89 and C++, commas in ICEs are illegal.
  13987. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13988. }
  13989. }
  13990. return Worst(LHSResult, RHSResult);
  13991. }
  13992. case BO_LAnd:
  13993. case BO_LOr: {
  13994. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  13995. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  13996. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  13997. // Rare case where the RHS has a comma "side-effect"; we need
  13998. // to actually check the condition to see whether the side
  13999. // with the comma is evaluated.
  14000. if ((Exp->getOpcode() == BO_LAnd) !=
  14001. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  14002. return RHSResult;
  14003. return NoDiag();
  14004. }
  14005. return Worst(LHSResult, RHSResult);
  14006. }
  14007. }
  14008. llvm_unreachable("invalid binary operator kind");
  14009. }
  14010. case Expr::ImplicitCastExprClass:
  14011. case Expr::CStyleCastExprClass:
  14012. case Expr::CXXFunctionalCastExprClass:
  14013. case Expr::CXXStaticCastExprClass:
  14014. case Expr::CXXReinterpretCastExprClass:
  14015. case Expr::CXXConstCastExprClass:
  14016. case Expr::ObjCBridgedCastExprClass: {
  14017. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  14018. if (isa<ExplicitCastExpr>(E)) {
  14019. if (const FloatingLiteral *FL
  14020. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  14021. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  14022. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  14023. APSInt IgnoredVal(DestWidth, !DestSigned);
  14024. bool Ignored;
  14025. // If the value does not fit in the destination type, the behavior is
  14026. // undefined, so we are not required to treat it as a constant
  14027. // expression.
  14028. if (FL->getValue().convertToInteger(IgnoredVal,
  14029. llvm::APFloat::rmTowardZero,
  14030. &Ignored) & APFloat::opInvalidOp)
  14031. return ICEDiag(IK_NotICE, E->getBeginLoc());
  14032. return NoDiag();
  14033. }
  14034. }
  14035. switch (cast<CastExpr>(E)->getCastKind()) {
  14036. case CK_LValueToRValue:
  14037. case CK_AtomicToNonAtomic:
  14038. case CK_NonAtomicToAtomic:
  14039. case CK_NoOp:
  14040. case CK_IntegralToBoolean:
  14041. case CK_IntegralCast:
  14042. return CheckICE(SubExpr, Ctx);
  14043. default:
  14044. return ICEDiag(IK_NotICE, E->getBeginLoc());
  14045. }
  14046. }
  14047. case Expr::BinaryConditionalOperatorClass: {
  14048. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  14049. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  14050. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  14051. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  14052. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  14053. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  14054. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  14055. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  14056. return FalseResult;
  14057. }
  14058. case Expr::ConditionalOperatorClass: {
  14059. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  14060. // If the condition (ignoring parens) is a __builtin_constant_p call,
  14061. // then only the true side is actually considered in an integer constant
  14062. // expression, and it is fully evaluated. This is an important GNU
  14063. // extension. See GCC PR38377 for discussion.
  14064. if (const CallExpr *CallCE
  14065. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  14066. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  14067. return CheckEvalInICE(E, Ctx);
  14068. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  14069. if (CondResult.Kind == IK_NotICE)
  14070. return CondResult;
  14071. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  14072. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  14073. if (TrueResult.Kind == IK_NotICE)
  14074. return TrueResult;
  14075. if (FalseResult.Kind == IK_NotICE)
  14076. return FalseResult;
  14077. if (CondResult.Kind == IK_ICEIfUnevaluated)
  14078. return CondResult;
  14079. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  14080. return NoDiag();
  14081. // Rare case where the diagnostics depend on which side is evaluated
  14082. // Note that if we get here, CondResult is 0, and at least one of
  14083. // TrueResult and FalseResult is non-zero.
  14084. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  14085. return FalseResult;
  14086. return TrueResult;
  14087. }
  14088. case Expr::CXXDefaultArgExprClass:
  14089. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  14090. case Expr::CXXDefaultInitExprClass:
  14091. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  14092. case Expr::ChooseExprClass: {
  14093. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  14094. }
  14095. case Expr::BuiltinBitCastExprClass: {
  14096. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  14097. return ICEDiag(IK_NotICE, E->getBeginLoc());
  14098. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  14099. }
  14100. }
  14101. llvm_unreachable("Invalid StmtClass!");
  14102. }
  14103. /// Evaluate an expression as a C++11 integral constant expression.
  14104. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  14105. const Expr *E,
  14106. llvm::APSInt *Value,
  14107. SourceLocation *Loc) {
  14108. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  14109. if (Loc) *Loc = E->getExprLoc();
  14110. return false;
  14111. }
  14112. APValue Result;
  14113. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  14114. return false;
  14115. if (!Result.isInt()) {
  14116. if (Loc) *Loc = E->getExprLoc();
  14117. return false;
  14118. }
  14119. if (Value) *Value = Result.getInt();
  14120. return true;
  14121. }
  14122. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  14123. SourceLocation *Loc) const {
  14124. assert(!isValueDependent() &&
  14125. "Expression evaluator can't be called on a dependent expression.");
  14126. ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
  14127. if (Ctx.getLangOpts().CPlusPlus11)
  14128. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  14129. ICEDiag D = CheckICE(this, Ctx);
  14130. if (D.Kind != IK_ICE) {
  14131. if (Loc) *Loc = D.Loc;
  14132. return false;
  14133. }
  14134. return true;
  14135. }
  14136. std::optional<llvm::APSInt>
  14137. Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc,
  14138. bool isEvaluated) const {
  14139. if (isValueDependent()) {
  14140. // Expression evaluator can't succeed on a dependent expression.
  14141. return std::nullopt;
  14142. }
  14143. APSInt Value;
  14144. if (Ctx.getLangOpts().CPlusPlus11) {
  14145. if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
  14146. return Value;
  14147. return std::nullopt;
  14148. }
  14149. if (!isIntegerConstantExpr(Ctx, Loc))
  14150. return std::nullopt;
  14151. // The only possible side-effects here are due to UB discovered in the
  14152. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  14153. // required to treat the expression as an ICE, so we produce the folded
  14154. // value.
  14155. EvalResult ExprResult;
  14156. Expr::EvalStatus Status;
  14157. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  14158. Info.InConstantContext = true;
  14159. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  14160. llvm_unreachable("ICE cannot be evaluated!");
  14161. return ExprResult.Val.getInt();
  14162. }
  14163. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  14164. assert(!isValueDependent() &&
  14165. "Expression evaluator can't be called on a dependent expression.");
  14166. return CheckICE(this, Ctx).Kind == IK_ICE;
  14167. }
  14168. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  14169. SourceLocation *Loc) const {
  14170. assert(!isValueDependent() &&
  14171. "Expression evaluator can't be called on a dependent expression.");
  14172. // We support this checking in C++98 mode in order to diagnose compatibility
  14173. // issues.
  14174. assert(Ctx.getLangOpts().CPlusPlus);
  14175. // Build evaluation settings.
  14176. Expr::EvalStatus Status;
  14177. SmallVector<PartialDiagnosticAt, 8> Diags;
  14178. Status.Diag = &Diags;
  14179. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  14180. APValue Scratch;
  14181. bool IsConstExpr =
  14182. ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
  14183. // FIXME: We don't produce a diagnostic for this, but the callers that
  14184. // call us on arbitrary full-expressions should generally not care.
  14185. Info.discardCleanups() && !Status.HasSideEffects;
  14186. if (!Diags.empty()) {
  14187. IsConstExpr = false;
  14188. if (Loc) *Loc = Diags[0].first;
  14189. } else if (!IsConstExpr) {
  14190. // FIXME: This shouldn't happen.
  14191. if (Loc) *Loc = getExprLoc();
  14192. }
  14193. return IsConstExpr;
  14194. }
  14195. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  14196. const FunctionDecl *Callee,
  14197. ArrayRef<const Expr*> Args,
  14198. const Expr *This) const {
  14199. assert(!isValueDependent() &&
  14200. "Expression evaluator can't be called on a dependent expression.");
  14201. llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
  14202. std::string Name;
  14203. llvm::raw_string_ostream OS(Name);
  14204. Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
  14205. /*Qualified=*/true);
  14206. return Name;
  14207. });
  14208. Expr::EvalStatus Status;
  14209. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  14210. Info.InConstantContext = true;
  14211. LValue ThisVal;
  14212. const LValue *ThisPtr = nullptr;
  14213. if (This) {
  14214. #ifndef NDEBUG
  14215. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  14216. assert(MD && "Don't provide `this` for non-methods.");
  14217. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  14218. #endif
  14219. if (!This->isValueDependent() &&
  14220. EvaluateObjectArgument(Info, This, ThisVal) &&
  14221. !Info.EvalStatus.HasSideEffects)
  14222. ThisPtr = &ThisVal;
  14223. // Ignore any side-effects from a failed evaluation. This is safe because
  14224. // they can't interfere with any other argument evaluation.
  14225. Info.EvalStatus.HasSideEffects = false;
  14226. }
  14227. CallRef Call = Info.CurrentCall->createCall(Callee);
  14228. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  14229. I != E; ++I) {
  14230. unsigned Idx = I - Args.begin();
  14231. if (Idx >= Callee->getNumParams())
  14232. break;
  14233. const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
  14234. if ((*I)->isValueDependent() ||
  14235. !EvaluateCallArg(PVD, *I, Call, Info) ||
  14236. Info.EvalStatus.HasSideEffects) {
  14237. // If evaluation fails, throw away the argument entirely.
  14238. if (APValue *Slot = Info.getParamSlot(Call, PVD))
  14239. *Slot = APValue();
  14240. }
  14241. // Ignore any side-effects from a failed evaluation. This is safe because
  14242. // they can't interfere with any other argument evaluation.
  14243. Info.EvalStatus.HasSideEffects = false;
  14244. }
  14245. // Parameter cleanups happen in the caller and are not part of this
  14246. // evaluation.
  14247. Info.discardCleanups();
  14248. Info.EvalStatus.HasSideEffects = false;
  14249. // Build fake call to Callee.
  14250. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
  14251. // FIXME: Missing ExprWithCleanups in enable_if conditions?
  14252. FullExpressionRAII Scope(Info);
  14253. return Evaluate(Value, Info, this) && Scope.destroy() &&
  14254. !Info.EvalStatus.HasSideEffects;
  14255. }
  14256. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  14257. SmallVectorImpl<
  14258. PartialDiagnosticAt> &Diags) {
  14259. // FIXME: It would be useful to check constexpr function templates, but at the
  14260. // moment the constant expression evaluator cannot cope with the non-rigorous
  14261. // ASTs which we build for dependent expressions.
  14262. if (FD->isDependentContext())
  14263. return true;
  14264. llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
  14265. std::string Name;
  14266. llvm::raw_string_ostream OS(Name);
  14267. FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
  14268. /*Qualified=*/true);
  14269. return Name;
  14270. });
  14271. Expr::EvalStatus Status;
  14272. Status.Diag = &Diags;
  14273. EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
  14274. Info.InConstantContext = true;
  14275. Info.CheckingPotentialConstantExpression = true;
  14276. // The constexpr VM attempts to compile all methods to bytecode here.
  14277. if (Info.EnableNewConstInterp) {
  14278. Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
  14279. return Diags.empty();
  14280. }
  14281. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  14282. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  14283. // Fabricate an arbitrary expression on the stack and pretend that it
  14284. // is a temporary being used as the 'this' pointer.
  14285. LValue This;
  14286. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  14287. This.set({&VIE, Info.CurrentCall->Index});
  14288. ArrayRef<const Expr*> Args;
  14289. APValue Scratch;
  14290. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  14291. // Evaluate the call as a constant initializer, to allow the construction
  14292. // of objects of non-literal types.
  14293. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  14294. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  14295. } else {
  14296. SourceLocation Loc = FD->getLocation();
  14297. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  14298. Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
  14299. }
  14300. return Diags.empty();
  14301. }
  14302. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  14303. const FunctionDecl *FD,
  14304. SmallVectorImpl<
  14305. PartialDiagnosticAt> &Diags) {
  14306. assert(!E->isValueDependent() &&
  14307. "Expression evaluator can't be called on a dependent expression.");
  14308. Expr::EvalStatus Status;
  14309. Status.Diag = &Diags;
  14310. EvalInfo Info(FD->getASTContext(), Status,
  14311. EvalInfo::EM_ConstantExpressionUnevaluated);
  14312. Info.InConstantContext = true;
  14313. Info.CheckingPotentialConstantExpression = true;
  14314. // Fabricate a call stack frame to give the arguments a plausible cover story.
  14315. CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
  14316. APValue ResultScratch;
  14317. Evaluate(ResultScratch, Info, E);
  14318. return Diags.empty();
  14319. }
  14320. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  14321. unsigned Type) const {
  14322. if (!getType()->isPointerType())
  14323. return false;
  14324. Expr::EvalStatus Status;
  14325. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  14326. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  14327. }
  14328. static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
  14329. EvalInfo &Info) {
  14330. if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
  14331. return false;
  14332. LValue String;
  14333. if (!EvaluatePointer(E, String, Info))
  14334. return false;
  14335. QualType CharTy = E->getType()->getPointeeType();
  14336. // Fast path: if it's a string literal, search the string value.
  14337. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  14338. String.getLValueBase().dyn_cast<const Expr *>())) {
  14339. StringRef Str = S->getBytes();
  14340. int64_t Off = String.Offset.getQuantity();
  14341. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  14342. S->getCharByteWidth() == 1 &&
  14343. // FIXME: Add fast-path for wchar_t too.
  14344. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  14345. Str = Str.substr(Off);
  14346. StringRef::size_type Pos = Str.find(0);
  14347. if (Pos != StringRef::npos)
  14348. Str = Str.substr(0, Pos);
  14349. Result = Str.size();
  14350. return true;
  14351. }
  14352. // Fall through to slow path.
  14353. }
  14354. // Slow path: scan the bytes of the string looking for the terminating 0.
  14355. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  14356. APValue Char;
  14357. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  14358. !Char.isInt())
  14359. return false;
  14360. if (!Char.getInt()) {
  14361. Result = Strlen;
  14362. return true;
  14363. }
  14364. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  14365. return false;
  14366. }
  14367. }
  14368. bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
  14369. Expr::EvalStatus Status;
  14370. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  14371. return EvaluateBuiltinStrLen(this, Result, Info);
  14372. }