ExprConstant.cpp 400 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Expr constant evaluator.
  11. //
  12. // Constant expression evaluation produces four main results:
  13. //
  14. // * A success/failure flag indicating whether constant folding was successful.
  15. // This is the 'bool' return value used by most of the code in this file. A
  16. // 'false' return value indicates that constant folding has failed, and any
  17. // appropriate diagnostic has already been produced.
  18. //
  19. // * An evaluated result, valid only if constant folding has not failed.
  20. //
  21. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  22. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  23. // where it is possible to determine the evaluated result regardless.
  24. //
  25. // * A set of notes indicating why the evaluation was not a constant expression
  26. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  27. // too, why the expression could not be folded.
  28. //
  29. // If we are checking for a potential constant expression, failure to constant
  30. // fold a potential constant sub-expression will be indicated by a 'false'
  31. // return value (the expression could not be folded) and no diagnostic (the
  32. // expression is not necessarily non-constant).
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #include "clang/AST/APValue.h"
  36. #include "clang/AST/ASTContext.h"
  37. #include "clang/AST/ASTDiagnostic.h"
  38. #include "clang/AST/ASTLambda.h"
  39. #include "clang/AST/CharUnits.h"
  40. #include "clang/AST/Expr.h"
  41. #include "clang/AST/RecordLayout.h"
  42. #include "clang/AST/StmtVisitor.h"
  43. #include "clang/AST/TypeLoc.h"
  44. #include "clang/Basic/Builtins.h"
  45. #include "clang/Basic/TargetInfo.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <cstring>
  48. #include <functional>
  49. #define DEBUG_TYPE "exprconstant"
  50. using namespace clang;
  51. using llvm::APSInt;
  52. using llvm::APFloat;
  53. static bool IsGlobalLValue(APValue::LValueBase B);
  54. namespace {
  55. struct LValue;
  56. struct CallStackFrame;
  57. struct EvalInfo;
  58. static QualType getType(APValue::LValueBase B) {
  59. if (!B) return QualType();
  60. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  61. // FIXME: It's unclear where we're supposed to take the type from, and
  62. // this actually matters for arrays of unknown bound. Eg:
  63. //
  64. // extern int arr[]; void f() { extern int arr[3]; };
  65. // constexpr int *p = &arr[1]; // valid?
  66. //
  67. // For now, we take the array bound from the most recent declaration.
  68. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  69. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  70. QualType T = Redecl->getType();
  71. if (!T->isIncompleteArrayType())
  72. return T;
  73. }
  74. return D->getType();
  75. }
  76. const Expr *Base = B.get<const Expr*>();
  77. // For a materialized temporary, the type of the temporary we materialized
  78. // may not be the type of the expression.
  79. if (const MaterializeTemporaryExpr *MTE =
  80. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  81. SmallVector<const Expr *, 2> CommaLHSs;
  82. SmallVector<SubobjectAdjustment, 2> Adjustments;
  83. const Expr *Temp = MTE->GetTemporaryExpr();
  84. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  85. Adjustments);
  86. // Keep any cv-qualifiers from the reference if we generated a temporary
  87. // for it directly. Otherwise use the type after adjustment.
  88. if (!Adjustments.empty())
  89. return Inner->getType();
  90. }
  91. return Base->getType();
  92. }
  93. /// Get an LValue path entry, which is known to not be an array index, as a
  94. /// field or base class.
  95. static
  96. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  97. APValue::BaseOrMemberType Value;
  98. Value.setFromOpaqueValue(E.BaseOrMember);
  99. return Value;
  100. }
  101. /// Get an LValue path entry, which is known to not be an array index, as a
  102. /// field declaration.
  103. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  104. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  105. }
  106. /// Get an LValue path entry, which is known to not be an array index, as a
  107. /// base class declaration.
  108. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  109. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  110. }
  111. /// Determine whether this LValue path entry for a base class names a virtual
  112. /// base class.
  113. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  114. return getAsBaseOrMember(E).getInt();
  115. }
  116. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  117. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  118. const FunctionDecl *Callee = CE->getDirectCallee();
  119. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  120. }
  121. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  122. /// This will look through a single cast.
  123. ///
  124. /// Returns null if we couldn't unwrap a function with alloc_size.
  125. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  126. if (!E->getType()->isPointerType())
  127. return nullptr;
  128. E = E->IgnoreParens();
  129. // If we're doing a variable assignment from e.g. malloc(N), there will
  130. // probably be a cast of some kind. In exotic cases, we might also see a
  131. // top-level ExprWithCleanups. Ignore them either way.
  132. if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
  133. E = EC->getSubExpr()->IgnoreParens();
  134. if (const auto *Cast = dyn_cast<CastExpr>(E))
  135. E = Cast->getSubExpr()->IgnoreParens();
  136. if (const auto *CE = dyn_cast<CallExpr>(E))
  137. return getAllocSizeAttr(CE) ? CE : nullptr;
  138. return nullptr;
  139. }
  140. /// Determines whether or not the given Base contains a call to a function
  141. /// with the alloc_size attribute.
  142. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  143. const auto *E = Base.dyn_cast<const Expr *>();
  144. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  145. }
  146. /// The bound to claim that an array of unknown bound has.
  147. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  148. /// to an arbitrary value that's likely to loudly break things if it's used.
  149. static const uint64_t AssumedSizeForUnsizedArray =
  150. std::numeric_limits<uint64_t>::max() / 2;
  151. /// Determines if an LValue with the given LValueBase will have an unsized
  152. /// array in its designator.
  153. /// Find the path length and type of the most-derived subobject in the given
  154. /// path, and find the size of the containing array, if any.
  155. static unsigned
  156. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  157. ArrayRef<APValue::LValuePathEntry> Path,
  158. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  159. bool &FirstEntryIsUnsizedArray) {
  160. // This only accepts LValueBases from APValues, and APValues don't support
  161. // arrays that lack size info.
  162. assert(!isBaseAnAllocSizeCall(Base) &&
  163. "Unsized arrays shouldn't appear here");
  164. unsigned MostDerivedLength = 0;
  165. Type = getType(Base);
  166. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  167. if (Type->isArrayType()) {
  168. const ArrayType *AT = Ctx.getAsArrayType(Type);
  169. Type = AT->getElementType();
  170. MostDerivedLength = I + 1;
  171. IsArray = true;
  172. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  173. ArraySize = CAT->getSize().getZExtValue();
  174. } else {
  175. assert(I == 0 && "unexpected unsized array designator");
  176. FirstEntryIsUnsizedArray = true;
  177. ArraySize = AssumedSizeForUnsizedArray;
  178. }
  179. } else if (Type->isAnyComplexType()) {
  180. const ComplexType *CT = Type->castAs<ComplexType>();
  181. Type = CT->getElementType();
  182. ArraySize = 2;
  183. MostDerivedLength = I + 1;
  184. IsArray = true;
  185. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  186. Type = FD->getType();
  187. ArraySize = 0;
  188. MostDerivedLength = I + 1;
  189. IsArray = false;
  190. } else {
  191. // Path[I] describes a base class.
  192. ArraySize = 0;
  193. IsArray = false;
  194. }
  195. }
  196. return MostDerivedLength;
  197. }
  198. // The order of this enum is important for diagnostics.
  199. enum CheckSubobjectKind {
  200. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  201. CSK_This, CSK_Real, CSK_Imag
  202. };
  203. /// A path from a glvalue to a subobject of that glvalue.
  204. struct SubobjectDesignator {
  205. /// True if the subobject was named in a manner not supported by C++11. Such
  206. /// lvalues can still be folded, but they are not core constant expressions
  207. /// and we cannot perform lvalue-to-rvalue conversions on them.
  208. unsigned Invalid : 1;
  209. /// Is this a pointer one past the end of an object?
  210. unsigned IsOnePastTheEnd : 1;
  211. /// Indicator of whether the first entry is an unsized array.
  212. unsigned FirstEntryIsAnUnsizedArray : 1;
  213. /// Indicator of whether the most-derived object is an array element.
  214. unsigned MostDerivedIsArrayElement : 1;
  215. /// The length of the path to the most-derived object of which this is a
  216. /// subobject.
  217. unsigned MostDerivedPathLength : 28;
  218. /// The size of the array of which the most-derived object is an element.
  219. /// This will always be 0 if the most-derived object is not an array
  220. /// element. 0 is not an indicator of whether or not the most-derived object
  221. /// is an array, however, because 0-length arrays are allowed.
  222. ///
  223. /// If the current array is an unsized array, the value of this is
  224. /// undefined.
  225. uint64_t MostDerivedArraySize;
  226. /// The type of the most derived object referred to by this address.
  227. QualType MostDerivedType;
  228. typedef APValue::LValuePathEntry PathEntry;
  229. /// The entries on the path from the glvalue to the designated subobject.
  230. SmallVector<PathEntry, 8> Entries;
  231. SubobjectDesignator() : Invalid(true) {}
  232. explicit SubobjectDesignator(QualType T)
  233. : Invalid(false), IsOnePastTheEnd(false),
  234. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  235. MostDerivedPathLength(0), MostDerivedArraySize(0),
  236. MostDerivedType(T) {}
  237. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  238. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  239. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  240. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  241. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  242. if (!Invalid) {
  243. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  244. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  245. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  246. if (V.getLValueBase()) {
  247. bool IsArray = false;
  248. bool FirstIsUnsizedArray = false;
  249. MostDerivedPathLength = findMostDerivedSubobject(
  250. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  251. MostDerivedType, IsArray, FirstIsUnsizedArray);
  252. MostDerivedIsArrayElement = IsArray;
  253. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  254. }
  255. }
  256. }
  257. void setInvalid() {
  258. Invalid = true;
  259. Entries.clear();
  260. }
  261. /// Determine whether the most derived subobject is an array without a
  262. /// known bound.
  263. bool isMostDerivedAnUnsizedArray() const {
  264. assert(!Invalid && "Calling this makes no sense on invalid designators");
  265. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  266. }
  267. /// Determine what the most derived array's size is. Results in an assertion
  268. /// failure if the most derived array lacks a size.
  269. uint64_t getMostDerivedArraySize() const {
  270. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  271. return MostDerivedArraySize;
  272. }
  273. /// Determine whether this is a one-past-the-end pointer.
  274. bool isOnePastTheEnd() const {
  275. assert(!Invalid);
  276. if (IsOnePastTheEnd)
  277. return true;
  278. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  279. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  280. return true;
  281. return false;
  282. }
  283. /// Check that this refers to a valid subobject.
  284. bool isValidSubobject() const {
  285. if (Invalid)
  286. return false;
  287. return !isOnePastTheEnd();
  288. }
  289. /// Check that this refers to a valid subobject, and if not, produce a
  290. /// relevant diagnostic and set the designator as invalid.
  291. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  292. /// Update this designator to refer to the first element within this array.
  293. void addArrayUnchecked(const ConstantArrayType *CAT) {
  294. PathEntry Entry;
  295. Entry.ArrayIndex = 0;
  296. Entries.push_back(Entry);
  297. // This is a most-derived object.
  298. MostDerivedType = CAT->getElementType();
  299. MostDerivedIsArrayElement = true;
  300. MostDerivedArraySize = CAT->getSize().getZExtValue();
  301. MostDerivedPathLength = Entries.size();
  302. }
  303. /// Update this designator to refer to the first element within the array of
  304. /// elements of type T. This is an array of unknown size.
  305. void addUnsizedArrayUnchecked(QualType ElemTy) {
  306. PathEntry Entry;
  307. Entry.ArrayIndex = 0;
  308. Entries.push_back(Entry);
  309. MostDerivedType = ElemTy;
  310. MostDerivedIsArrayElement = true;
  311. // The value in MostDerivedArraySize is undefined in this case. So, set it
  312. // to an arbitrary value that's likely to loudly break things if it's
  313. // used.
  314. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  315. MostDerivedPathLength = Entries.size();
  316. }
  317. /// Update this designator to refer to the given base or member of this
  318. /// object.
  319. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  320. PathEntry Entry;
  321. APValue::BaseOrMemberType Value(D, Virtual);
  322. Entry.BaseOrMember = Value.getOpaqueValue();
  323. Entries.push_back(Entry);
  324. // If this isn't a base class, it's a new most-derived object.
  325. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  326. MostDerivedType = FD->getType();
  327. MostDerivedIsArrayElement = false;
  328. MostDerivedArraySize = 0;
  329. MostDerivedPathLength = Entries.size();
  330. }
  331. }
  332. /// Update this designator to refer to the given complex component.
  333. void addComplexUnchecked(QualType EltTy, bool Imag) {
  334. PathEntry Entry;
  335. Entry.ArrayIndex = Imag;
  336. Entries.push_back(Entry);
  337. // This is technically a most-derived object, though in practice this
  338. // is unlikely to matter.
  339. MostDerivedType = EltTy;
  340. MostDerivedIsArrayElement = true;
  341. MostDerivedArraySize = 2;
  342. MostDerivedPathLength = Entries.size();
  343. }
  344. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  345. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  346. const APSInt &N);
  347. /// Add N to the address of this subobject.
  348. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  349. if (Invalid || !N) return;
  350. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  351. if (isMostDerivedAnUnsizedArray()) {
  352. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  353. // Can't verify -- trust that the user is doing the right thing (or if
  354. // not, trust that the caller will catch the bad behavior).
  355. // FIXME: Should we reject if this overflows, at least?
  356. Entries.back().ArrayIndex += TruncatedN;
  357. return;
  358. }
  359. // [expr.add]p4: For the purposes of these operators, a pointer to a
  360. // nonarray object behaves the same as a pointer to the first element of
  361. // an array of length one with the type of the object as its element type.
  362. bool IsArray = MostDerivedPathLength == Entries.size() &&
  363. MostDerivedIsArrayElement;
  364. uint64_t ArrayIndex =
  365. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  366. uint64_t ArraySize =
  367. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  368. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  369. // Calculate the actual index in a wide enough type, so we can include
  370. // it in the note.
  371. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  372. (llvm::APInt&)N += ArrayIndex;
  373. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  374. diagnosePointerArithmetic(Info, E, N);
  375. setInvalid();
  376. return;
  377. }
  378. ArrayIndex += TruncatedN;
  379. assert(ArrayIndex <= ArraySize &&
  380. "bounds check succeeded for out-of-bounds index");
  381. if (IsArray)
  382. Entries.back().ArrayIndex = ArrayIndex;
  383. else
  384. IsOnePastTheEnd = (ArrayIndex != 0);
  385. }
  386. };
  387. /// A stack frame in the constexpr call stack.
  388. struct CallStackFrame {
  389. EvalInfo &Info;
  390. /// Parent - The caller of this stack frame.
  391. CallStackFrame *Caller;
  392. /// Callee - The function which was called.
  393. const FunctionDecl *Callee;
  394. /// This - The binding for the this pointer in this call, if any.
  395. const LValue *This;
  396. /// Arguments - Parameter bindings for this function call, indexed by
  397. /// parameters' function scope indices.
  398. APValue *Arguments;
  399. // Note that we intentionally use std::map here so that references to
  400. // values are stable.
  401. typedef std::pair<const void *, unsigned> MapKeyTy;
  402. typedef std::map<MapKeyTy, APValue> MapTy;
  403. /// Temporaries - Temporary lvalues materialized within this stack frame.
  404. MapTy Temporaries;
  405. /// CallLoc - The location of the call expression for this call.
  406. SourceLocation CallLoc;
  407. /// Index - The call index of this call.
  408. unsigned Index;
  409. /// The stack of integers for tracking version numbers for temporaries.
  410. SmallVector<unsigned, 2> TempVersionStack = {1};
  411. unsigned CurTempVersion = TempVersionStack.back();
  412. unsigned getTempVersion() const { return TempVersionStack.back(); }
  413. void pushTempVersion() {
  414. TempVersionStack.push_back(++CurTempVersion);
  415. }
  416. void popTempVersion() {
  417. TempVersionStack.pop_back();
  418. }
  419. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  420. // on the overall stack usage of deeply-recursing constexpr evaluataions.
  421. // (We should cache this map rather than recomputing it repeatedly.)
  422. // But let's try this and see how it goes; we can look into caching the map
  423. // as a later change.
  424. /// LambdaCaptureFields - Mapping from captured variables/this to
  425. /// corresponding data members in the closure class.
  426. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  427. FieldDecl *LambdaThisCaptureField;
  428. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  429. const FunctionDecl *Callee, const LValue *This,
  430. APValue *Arguments);
  431. ~CallStackFrame();
  432. // Return the temporary for Key whose version number is Version.
  433. APValue *getTemporary(const void *Key, unsigned Version) {
  434. MapKeyTy KV(Key, Version);
  435. auto LB = Temporaries.lower_bound(KV);
  436. if (LB != Temporaries.end() && LB->first == KV)
  437. return &LB->second;
  438. // Pair (Key,Version) wasn't found in the map. Check that no elements
  439. // in the map have 'Key' as their key.
  440. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  441. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  442. "Element with key 'Key' found in map");
  443. return nullptr;
  444. }
  445. // Return the current temporary for Key in the map.
  446. APValue *getCurrentTemporary(const void *Key) {
  447. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  448. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  449. return &std::prev(UB)->second;
  450. return nullptr;
  451. }
  452. // Return the version number of the current temporary for Key.
  453. unsigned getCurrentTemporaryVersion(const void *Key) const {
  454. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  455. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  456. return std::prev(UB)->first.second;
  457. return 0;
  458. }
  459. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  460. };
  461. /// Temporarily override 'this'.
  462. class ThisOverrideRAII {
  463. public:
  464. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  465. : Frame(Frame), OldThis(Frame.This) {
  466. if (Enable)
  467. Frame.This = NewThis;
  468. }
  469. ~ThisOverrideRAII() {
  470. Frame.This = OldThis;
  471. }
  472. private:
  473. CallStackFrame &Frame;
  474. const LValue *OldThis;
  475. };
  476. /// A partial diagnostic which we might know in advance that we are not going
  477. /// to emit.
  478. class OptionalDiagnostic {
  479. PartialDiagnostic *Diag;
  480. public:
  481. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  482. : Diag(Diag) {}
  483. template<typename T>
  484. OptionalDiagnostic &operator<<(const T &v) {
  485. if (Diag)
  486. *Diag << v;
  487. return *this;
  488. }
  489. OptionalDiagnostic &operator<<(const APSInt &I) {
  490. if (Diag) {
  491. SmallVector<char, 32> Buffer;
  492. I.toString(Buffer);
  493. *Diag << StringRef(Buffer.data(), Buffer.size());
  494. }
  495. return *this;
  496. }
  497. OptionalDiagnostic &operator<<(const APFloat &F) {
  498. if (Diag) {
  499. // FIXME: Force the precision of the source value down so we don't
  500. // print digits which are usually useless (we don't really care here if
  501. // we truncate a digit by accident in edge cases). Ideally,
  502. // APFloat::toString would automatically print the shortest
  503. // representation which rounds to the correct value, but it's a bit
  504. // tricky to implement.
  505. unsigned precision =
  506. llvm::APFloat::semanticsPrecision(F.getSemantics());
  507. precision = (precision * 59 + 195) / 196;
  508. SmallVector<char, 32> Buffer;
  509. F.toString(Buffer, precision);
  510. *Diag << StringRef(Buffer.data(), Buffer.size());
  511. }
  512. return *this;
  513. }
  514. };
  515. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  516. class Cleanup {
  517. llvm::PointerIntPair<APValue*, 1, bool> Value;
  518. public:
  519. Cleanup(APValue *Val, bool IsLifetimeExtended)
  520. : Value(Val, IsLifetimeExtended) {}
  521. bool isLifetimeExtended() const { return Value.getInt(); }
  522. void endLifetime() {
  523. *Value.getPointer() = APValue();
  524. }
  525. };
  526. /// EvalInfo - This is a private struct used by the evaluator to capture
  527. /// information about a subexpression as it is folded. It retains information
  528. /// about the AST context, but also maintains information about the folded
  529. /// expression.
  530. ///
  531. /// If an expression could be evaluated, it is still possible it is not a C
  532. /// "integer constant expression" or constant expression. If not, this struct
  533. /// captures information about how and why not.
  534. ///
  535. /// One bit of information passed *into* the request for constant folding
  536. /// indicates whether the subexpression is "evaluated" or not according to C
  537. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  538. /// evaluate the expression regardless of what the RHS is, but C only allows
  539. /// certain things in certain situations.
  540. struct EvalInfo {
  541. ASTContext &Ctx;
  542. /// EvalStatus - Contains information about the evaluation.
  543. Expr::EvalStatus &EvalStatus;
  544. /// CurrentCall - The top of the constexpr call stack.
  545. CallStackFrame *CurrentCall;
  546. /// CallStackDepth - The number of calls in the call stack right now.
  547. unsigned CallStackDepth;
  548. /// NextCallIndex - The next call index to assign.
  549. unsigned NextCallIndex;
  550. /// StepsLeft - The remaining number of evaluation steps we're permitted
  551. /// to perform. This is essentially a limit for the number of statements
  552. /// we will evaluate.
  553. unsigned StepsLeft;
  554. /// BottomFrame - The frame in which evaluation started. This must be
  555. /// initialized after CurrentCall and CallStackDepth.
  556. CallStackFrame BottomFrame;
  557. /// A stack of values whose lifetimes end at the end of some surrounding
  558. /// evaluation frame.
  559. llvm::SmallVector<Cleanup, 16> CleanupStack;
  560. /// EvaluatingDecl - This is the declaration whose initializer is being
  561. /// evaluated, if any.
  562. APValue::LValueBase EvaluatingDecl;
  563. /// EvaluatingDeclValue - This is the value being constructed for the
  564. /// declaration whose initializer is being evaluated, if any.
  565. APValue *EvaluatingDeclValue;
  566. /// EvaluatingObject - Pair of the AST node that an lvalue represents and
  567. /// the call index that that lvalue was allocated in.
  568. typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
  569. EvaluatingObject;
  570. /// EvaluatingConstructors - Set of objects that are currently being
  571. /// constructed.
  572. llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
  573. struct EvaluatingConstructorRAII {
  574. EvalInfo &EI;
  575. EvaluatingObject Object;
  576. bool DidInsert;
  577. EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
  578. : EI(EI), Object(Object) {
  579. DidInsert = EI.EvaluatingConstructors.insert(Object).second;
  580. }
  581. ~EvaluatingConstructorRAII() {
  582. if (DidInsert) EI.EvaluatingConstructors.erase(Object);
  583. }
  584. };
  585. bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
  586. unsigned Version) {
  587. return EvaluatingConstructors.count(
  588. EvaluatingObject(Decl, {CallIndex, Version}));
  589. }
  590. /// The current array initialization index, if we're performing array
  591. /// initialization.
  592. uint64_t ArrayInitIndex = -1;
  593. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  594. /// notes attached to it will also be stored, otherwise they will not be.
  595. bool HasActiveDiagnostic;
  596. /// Have we emitted a diagnostic explaining why we couldn't constant
  597. /// fold (not just why it's not strictly a constant expression)?
  598. bool HasFoldFailureDiagnostic;
  599. /// Whether or not we're currently speculatively evaluating.
  600. bool IsSpeculativelyEvaluating;
  601. enum EvaluationMode {
  602. /// Evaluate as a constant expression. Stop if we find that the expression
  603. /// is not a constant expression.
  604. EM_ConstantExpression,
  605. /// Evaluate as a potential constant expression. Keep going if we hit a
  606. /// construct that we can't evaluate yet (because we don't yet know the
  607. /// value of something) but stop if we hit something that could never be
  608. /// a constant expression.
  609. EM_PotentialConstantExpression,
  610. /// Fold the expression to a constant. Stop if we hit a side-effect that
  611. /// we can't model.
  612. EM_ConstantFold,
  613. /// Evaluate the expression looking for integer overflow and similar
  614. /// issues. Don't worry about side-effects, and try to visit all
  615. /// subexpressions.
  616. EM_EvaluateForOverflow,
  617. /// Evaluate in any way we know how. Don't worry about side-effects that
  618. /// can't be modeled.
  619. EM_IgnoreSideEffects,
  620. /// Evaluate as a constant expression. Stop if we find that the expression
  621. /// is not a constant expression. Some expressions can be retried in the
  622. /// optimizer if we don't constant fold them here, but in an unevaluated
  623. /// context we try to fold them immediately since the optimizer never
  624. /// gets a chance to look at it.
  625. EM_ConstantExpressionUnevaluated,
  626. /// Evaluate as a potential constant expression. Keep going if we hit a
  627. /// construct that we can't evaluate yet (because we don't yet know the
  628. /// value of something) but stop if we hit something that could never be
  629. /// a constant expression. Some expressions can be retried in the
  630. /// optimizer if we don't constant fold them here, but in an unevaluated
  631. /// context we try to fold them immediately since the optimizer never
  632. /// gets a chance to look at it.
  633. EM_PotentialConstantExpressionUnevaluated,
  634. /// Evaluate as a constant expression. In certain scenarios, if:
  635. /// - we find a MemberExpr with a base that can't be evaluated, or
  636. /// - we find a variable initialized with a call to a function that has
  637. /// the alloc_size attribute on it
  638. /// then we may consider evaluation to have succeeded.
  639. ///
  640. /// In either case, the LValue returned shall have an invalid base; in the
  641. /// former, the base will be the invalid MemberExpr, in the latter, the
  642. /// base will be either the alloc_size CallExpr or a CastExpr wrapping
  643. /// said CallExpr.
  644. EM_OffsetFold,
  645. } EvalMode;
  646. /// Are we checking whether the expression is a potential constant
  647. /// expression?
  648. bool checkingPotentialConstantExpression() const {
  649. return EvalMode == EM_PotentialConstantExpression ||
  650. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  651. }
  652. /// Are we checking an expression for overflow?
  653. // FIXME: We should check for any kind of undefined or suspicious behavior
  654. // in such constructs, not just overflow.
  655. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  656. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  657. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  658. CallStackDepth(0), NextCallIndex(1),
  659. StepsLeft(getLangOpts().ConstexprStepLimit),
  660. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  661. EvaluatingDecl((const ValueDecl *)nullptr),
  662. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  663. HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
  664. EvalMode(Mode) {}
  665. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  666. EvaluatingDecl = Base;
  667. EvaluatingDeclValue = &Value;
  668. EvaluatingConstructors.insert({Base, {0, 0}});
  669. }
  670. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  671. bool CheckCallLimit(SourceLocation Loc) {
  672. // Don't perform any constexpr calls (other than the call we're checking)
  673. // when checking a potential constant expression.
  674. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  675. return false;
  676. if (NextCallIndex == 0) {
  677. // NextCallIndex has wrapped around.
  678. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  679. return false;
  680. }
  681. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  682. return true;
  683. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  684. << getLangOpts().ConstexprCallDepth;
  685. return false;
  686. }
  687. CallStackFrame *getCallFrame(unsigned CallIndex) {
  688. assert(CallIndex && "no call index in getCallFrame");
  689. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  690. // be null in this loop.
  691. CallStackFrame *Frame = CurrentCall;
  692. while (Frame->Index > CallIndex)
  693. Frame = Frame->Caller;
  694. return (Frame->Index == CallIndex) ? Frame : nullptr;
  695. }
  696. bool nextStep(const Stmt *S) {
  697. if (!StepsLeft) {
  698. FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
  699. return false;
  700. }
  701. --StepsLeft;
  702. return true;
  703. }
  704. private:
  705. /// Add a diagnostic to the diagnostics list.
  706. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  707. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  708. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  709. return EvalStatus.Diag->back().second;
  710. }
  711. /// Add notes containing a call stack to the current point of evaluation.
  712. void addCallStack(unsigned Limit);
  713. private:
  714. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  715. unsigned ExtraNotes, bool IsCCEDiag) {
  716. if (EvalStatus.Diag) {
  717. // If we have a prior diagnostic, it will be noting that the expression
  718. // isn't a constant expression. This diagnostic is more important,
  719. // unless we require this evaluation to produce a constant expression.
  720. //
  721. // FIXME: We might want to show both diagnostics to the user in
  722. // EM_ConstantFold mode.
  723. if (!EvalStatus.Diag->empty()) {
  724. switch (EvalMode) {
  725. case EM_ConstantFold:
  726. case EM_IgnoreSideEffects:
  727. case EM_EvaluateForOverflow:
  728. if (!HasFoldFailureDiagnostic)
  729. break;
  730. // We've already failed to fold something. Keep that diagnostic.
  731. LLVM_FALLTHROUGH;
  732. case EM_ConstantExpression:
  733. case EM_PotentialConstantExpression:
  734. case EM_ConstantExpressionUnevaluated:
  735. case EM_PotentialConstantExpressionUnevaluated:
  736. case EM_OffsetFold:
  737. HasActiveDiagnostic = false;
  738. return OptionalDiagnostic();
  739. }
  740. }
  741. unsigned CallStackNotes = CallStackDepth - 1;
  742. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  743. if (Limit)
  744. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  745. if (checkingPotentialConstantExpression())
  746. CallStackNotes = 0;
  747. HasActiveDiagnostic = true;
  748. HasFoldFailureDiagnostic = !IsCCEDiag;
  749. EvalStatus.Diag->clear();
  750. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  751. addDiag(Loc, DiagId);
  752. if (!checkingPotentialConstantExpression())
  753. addCallStack(Limit);
  754. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  755. }
  756. HasActiveDiagnostic = false;
  757. return OptionalDiagnostic();
  758. }
  759. public:
  760. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  761. OptionalDiagnostic
  762. FFDiag(SourceLocation Loc,
  763. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  764. unsigned ExtraNotes = 0) {
  765. return Diag(Loc, DiagId, ExtraNotes, false);
  766. }
  767. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  768. = diag::note_invalid_subexpr_in_const_expr,
  769. unsigned ExtraNotes = 0) {
  770. if (EvalStatus.Diag)
  771. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  772. HasActiveDiagnostic = false;
  773. return OptionalDiagnostic();
  774. }
  775. /// Diagnose that the evaluation does not produce a C++11 core constant
  776. /// expression.
  777. ///
  778. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  779. /// EM_PotentialConstantExpression mode and we produce one of these.
  780. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  781. = diag::note_invalid_subexpr_in_const_expr,
  782. unsigned ExtraNotes = 0) {
  783. // Don't override a previous diagnostic. Don't bother collecting
  784. // diagnostics if we're evaluating for overflow.
  785. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  786. HasActiveDiagnostic = false;
  787. return OptionalDiagnostic();
  788. }
  789. return Diag(Loc, DiagId, ExtraNotes, true);
  790. }
  791. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  792. = diag::note_invalid_subexpr_in_const_expr,
  793. unsigned ExtraNotes = 0) {
  794. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  795. }
  796. /// Add a note to a prior diagnostic.
  797. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  798. if (!HasActiveDiagnostic)
  799. return OptionalDiagnostic();
  800. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  801. }
  802. /// Add a stack of notes to a prior diagnostic.
  803. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  804. if (HasActiveDiagnostic) {
  805. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  806. Diags.begin(), Diags.end());
  807. }
  808. }
  809. /// Should we continue evaluation after encountering a side-effect that we
  810. /// couldn't model?
  811. bool keepEvaluatingAfterSideEffect() {
  812. switch (EvalMode) {
  813. case EM_PotentialConstantExpression:
  814. case EM_PotentialConstantExpressionUnevaluated:
  815. case EM_EvaluateForOverflow:
  816. case EM_IgnoreSideEffects:
  817. return true;
  818. case EM_ConstantExpression:
  819. case EM_ConstantExpressionUnevaluated:
  820. case EM_ConstantFold:
  821. case EM_OffsetFold:
  822. return false;
  823. }
  824. llvm_unreachable("Missed EvalMode case");
  825. }
  826. /// Note that we have had a side-effect, and determine whether we should
  827. /// keep evaluating.
  828. bool noteSideEffect() {
  829. EvalStatus.HasSideEffects = true;
  830. return keepEvaluatingAfterSideEffect();
  831. }
  832. /// Should we continue evaluation after encountering undefined behavior?
  833. bool keepEvaluatingAfterUndefinedBehavior() {
  834. switch (EvalMode) {
  835. case EM_EvaluateForOverflow:
  836. case EM_IgnoreSideEffects:
  837. case EM_ConstantFold:
  838. case EM_OffsetFold:
  839. return true;
  840. case EM_PotentialConstantExpression:
  841. case EM_PotentialConstantExpressionUnevaluated:
  842. case EM_ConstantExpression:
  843. case EM_ConstantExpressionUnevaluated:
  844. return false;
  845. }
  846. llvm_unreachable("Missed EvalMode case");
  847. }
  848. /// Note that we hit something that was technically undefined behavior, but
  849. /// that we can evaluate past it (such as signed overflow or floating-point
  850. /// division by zero.)
  851. bool noteUndefinedBehavior() {
  852. EvalStatus.HasUndefinedBehavior = true;
  853. return keepEvaluatingAfterUndefinedBehavior();
  854. }
  855. /// Should we continue evaluation as much as possible after encountering a
  856. /// construct which can't be reduced to a value?
  857. bool keepEvaluatingAfterFailure() {
  858. if (!StepsLeft)
  859. return false;
  860. switch (EvalMode) {
  861. case EM_PotentialConstantExpression:
  862. case EM_PotentialConstantExpressionUnevaluated:
  863. case EM_EvaluateForOverflow:
  864. return true;
  865. case EM_ConstantExpression:
  866. case EM_ConstantExpressionUnevaluated:
  867. case EM_ConstantFold:
  868. case EM_IgnoreSideEffects:
  869. case EM_OffsetFold:
  870. return false;
  871. }
  872. llvm_unreachable("Missed EvalMode case");
  873. }
  874. /// Notes that we failed to evaluate an expression that other expressions
  875. /// directly depend on, and determine if we should keep evaluating. This
  876. /// should only be called if we actually intend to keep evaluating.
  877. ///
  878. /// Call noteSideEffect() instead if we may be able to ignore the value that
  879. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  880. ///
  881. /// (Foo(), 1) // use noteSideEffect
  882. /// (Foo() || true) // use noteSideEffect
  883. /// Foo() + 1 // use noteFailure
  884. LLVM_NODISCARD bool noteFailure() {
  885. // Failure when evaluating some expression often means there is some
  886. // subexpression whose evaluation was skipped. Therefore, (because we
  887. // don't track whether we skipped an expression when unwinding after an
  888. // evaluation failure) every evaluation failure that bubbles up from a
  889. // subexpression implies that a side-effect has potentially happened. We
  890. // skip setting the HasSideEffects flag to true until we decide to
  891. // continue evaluating after that point, which happens here.
  892. bool KeepGoing = keepEvaluatingAfterFailure();
  893. EvalStatus.HasSideEffects |= KeepGoing;
  894. return KeepGoing;
  895. }
  896. class ArrayInitLoopIndex {
  897. EvalInfo &Info;
  898. uint64_t OuterIndex;
  899. public:
  900. ArrayInitLoopIndex(EvalInfo &Info)
  901. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  902. Info.ArrayInitIndex = 0;
  903. }
  904. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  905. operator uint64_t&() { return Info.ArrayInitIndex; }
  906. };
  907. };
  908. /// Object used to treat all foldable expressions as constant expressions.
  909. struct FoldConstant {
  910. EvalInfo &Info;
  911. bool Enabled;
  912. bool HadNoPriorDiags;
  913. EvalInfo::EvaluationMode OldMode;
  914. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  915. : Info(Info),
  916. Enabled(Enabled),
  917. HadNoPriorDiags(Info.EvalStatus.Diag &&
  918. Info.EvalStatus.Diag->empty() &&
  919. !Info.EvalStatus.HasSideEffects),
  920. OldMode(Info.EvalMode) {
  921. if (Enabled &&
  922. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  923. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  924. Info.EvalMode = EvalInfo::EM_ConstantFold;
  925. }
  926. void keepDiagnostics() { Enabled = false; }
  927. ~FoldConstant() {
  928. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  929. !Info.EvalStatus.HasSideEffects)
  930. Info.EvalStatus.Diag->clear();
  931. Info.EvalMode = OldMode;
  932. }
  933. };
  934. /// RAII object used to treat the current evaluation as the correct pointer
  935. /// offset fold for the current EvalMode
  936. struct FoldOffsetRAII {
  937. EvalInfo &Info;
  938. EvalInfo::EvaluationMode OldMode;
  939. explicit FoldOffsetRAII(EvalInfo &Info)
  940. : Info(Info), OldMode(Info.EvalMode) {
  941. if (!Info.checkingPotentialConstantExpression())
  942. Info.EvalMode = EvalInfo::EM_OffsetFold;
  943. }
  944. ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
  945. };
  946. /// RAII object used to optionally suppress diagnostics and side-effects from
  947. /// a speculative evaluation.
  948. class SpeculativeEvaluationRAII {
  949. EvalInfo *Info = nullptr;
  950. Expr::EvalStatus OldStatus;
  951. bool OldIsSpeculativelyEvaluating;
  952. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  953. Info = Other.Info;
  954. OldStatus = Other.OldStatus;
  955. OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
  956. Other.Info = nullptr;
  957. }
  958. void maybeRestoreState() {
  959. if (!Info)
  960. return;
  961. Info->EvalStatus = OldStatus;
  962. Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
  963. }
  964. public:
  965. SpeculativeEvaluationRAII() = default;
  966. SpeculativeEvaluationRAII(
  967. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  968. : Info(&Info), OldStatus(Info.EvalStatus),
  969. OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
  970. Info.EvalStatus.Diag = NewDiag;
  971. Info.IsSpeculativelyEvaluating = true;
  972. }
  973. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  974. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  975. moveFromAndCancel(std::move(Other));
  976. }
  977. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  978. maybeRestoreState();
  979. moveFromAndCancel(std::move(Other));
  980. return *this;
  981. }
  982. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  983. };
  984. /// RAII object wrapping a full-expression or block scope, and handling
  985. /// the ending of the lifetime of temporaries created within it.
  986. template<bool IsFullExpression>
  987. class ScopeRAII {
  988. EvalInfo &Info;
  989. unsigned OldStackSize;
  990. public:
  991. ScopeRAII(EvalInfo &Info)
  992. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  993. // Push a new temporary version. This is needed to distinguish between
  994. // temporaries created in different iterations of a loop.
  995. Info.CurrentCall->pushTempVersion();
  996. }
  997. ~ScopeRAII() {
  998. // Body moved to a static method to encourage the compiler to inline away
  999. // instances of this class.
  1000. cleanup(Info, OldStackSize);
  1001. Info.CurrentCall->popTempVersion();
  1002. }
  1003. private:
  1004. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  1005. unsigned NewEnd = OldStackSize;
  1006. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  1007. I != N; ++I) {
  1008. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  1009. // Full-expression cleanup of a lifetime-extended temporary: nothing
  1010. // to do, just move this cleanup to the right place in the stack.
  1011. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  1012. ++NewEnd;
  1013. } else {
  1014. // End the lifetime of the object.
  1015. Info.CleanupStack[I].endLifetime();
  1016. }
  1017. }
  1018. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1019. Info.CleanupStack.end());
  1020. }
  1021. };
  1022. typedef ScopeRAII<false> BlockScopeRAII;
  1023. typedef ScopeRAII<true> FullExpressionRAII;
  1024. }
  1025. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1026. CheckSubobjectKind CSK) {
  1027. if (Invalid)
  1028. return false;
  1029. if (isOnePastTheEnd()) {
  1030. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1031. << CSK;
  1032. setInvalid();
  1033. return false;
  1034. }
  1035. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1036. // must actually be at least one array element; even a VLA cannot have a
  1037. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1038. return true;
  1039. }
  1040. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1041. const Expr *E) {
  1042. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1043. // Do not set the designator as invalid: we can represent this situation,
  1044. // and correct handling of __builtin_object_size requires us to do so.
  1045. }
  1046. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1047. const Expr *E,
  1048. const APSInt &N) {
  1049. // If we're complaining, we must be able to statically determine the size of
  1050. // the most derived array.
  1051. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1052. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1053. << N << /*array*/ 0
  1054. << static_cast<unsigned>(getMostDerivedArraySize());
  1055. else
  1056. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1057. << N << /*non-array*/ 1;
  1058. setInvalid();
  1059. }
  1060. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1061. const FunctionDecl *Callee, const LValue *This,
  1062. APValue *Arguments)
  1063. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1064. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1065. Info.CurrentCall = this;
  1066. ++Info.CallStackDepth;
  1067. }
  1068. CallStackFrame::~CallStackFrame() {
  1069. assert(Info.CurrentCall == this && "calls retired out of order");
  1070. --Info.CallStackDepth;
  1071. Info.CurrentCall = Caller;
  1072. }
  1073. APValue &CallStackFrame::createTemporary(const void *Key,
  1074. bool IsLifetimeExtended) {
  1075. unsigned Version = Info.CurrentCall->getTempVersion();
  1076. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1077. assert(Result.isUninit() && "temporary created multiple times");
  1078. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1079. return Result;
  1080. }
  1081. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  1082. void EvalInfo::addCallStack(unsigned Limit) {
  1083. // Determine which calls to skip, if any.
  1084. unsigned ActiveCalls = CallStackDepth - 1;
  1085. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  1086. if (Limit && Limit < ActiveCalls) {
  1087. SkipStart = Limit / 2 + Limit % 2;
  1088. SkipEnd = ActiveCalls - Limit / 2;
  1089. }
  1090. // Walk the call stack and add the diagnostics.
  1091. unsigned CallIdx = 0;
  1092. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  1093. Frame = Frame->Caller, ++CallIdx) {
  1094. // Skip this call?
  1095. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  1096. if (CallIdx == SkipStart) {
  1097. // Note that we're skipping calls.
  1098. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  1099. << unsigned(ActiveCalls - Limit);
  1100. }
  1101. continue;
  1102. }
  1103. // Use a different note for an inheriting constructor, because from the
  1104. // user's perspective it's not really a function at all.
  1105. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  1106. if (CD->isInheritingConstructor()) {
  1107. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  1108. << CD->getParent();
  1109. continue;
  1110. }
  1111. }
  1112. SmallVector<char, 128> Buffer;
  1113. llvm::raw_svector_ostream Out(Buffer);
  1114. describeCall(Frame, Out);
  1115. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  1116. }
  1117. }
  1118. namespace {
  1119. struct ComplexValue {
  1120. private:
  1121. bool IsInt;
  1122. public:
  1123. APSInt IntReal, IntImag;
  1124. APFloat FloatReal, FloatImag;
  1125. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1126. void makeComplexFloat() { IsInt = false; }
  1127. bool isComplexFloat() const { return !IsInt; }
  1128. APFloat &getComplexFloatReal() { return FloatReal; }
  1129. APFloat &getComplexFloatImag() { return FloatImag; }
  1130. void makeComplexInt() { IsInt = true; }
  1131. bool isComplexInt() const { return IsInt; }
  1132. APSInt &getComplexIntReal() { return IntReal; }
  1133. APSInt &getComplexIntImag() { return IntImag; }
  1134. void moveInto(APValue &v) const {
  1135. if (isComplexFloat())
  1136. v = APValue(FloatReal, FloatImag);
  1137. else
  1138. v = APValue(IntReal, IntImag);
  1139. }
  1140. void setFrom(const APValue &v) {
  1141. assert(v.isComplexFloat() || v.isComplexInt());
  1142. if (v.isComplexFloat()) {
  1143. makeComplexFloat();
  1144. FloatReal = v.getComplexFloatReal();
  1145. FloatImag = v.getComplexFloatImag();
  1146. } else {
  1147. makeComplexInt();
  1148. IntReal = v.getComplexIntReal();
  1149. IntImag = v.getComplexIntImag();
  1150. }
  1151. }
  1152. };
  1153. struct LValue {
  1154. APValue::LValueBase Base;
  1155. CharUnits Offset;
  1156. SubobjectDesignator Designator;
  1157. bool IsNullPtr : 1;
  1158. bool InvalidBase : 1;
  1159. const APValue::LValueBase getLValueBase() const { return Base; }
  1160. CharUnits &getLValueOffset() { return Offset; }
  1161. const CharUnits &getLValueOffset() const { return Offset; }
  1162. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1163. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1164. bool isNullPointer() const { return IsNullPtr;}
  1165. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1166. unsigned getLValueVersion() const { return Base.getVersion(); }
  1167. void moveInto(APValue &V) const {
  1168. if (Designator.Invalid)
  1169. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1170. else {
  1171. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1172. V = APValue(Base, Offset, Designator.Entries,
  1173. Designator.IsOnePastTheEnd, IsNullPtr);
  1174. }
  1175. }
  1176. void setFrom(ASTContext &Ctx, const APValue &V) {
  1177. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1178. Base = V.getLValueBase();
  1179. Offset = V.getLValueOffset();
  1180. InvalidBase = false;
  1181. Designator = SubobjectDesignator(Ctx, V);
  1182. IsNullPtr = V.isNullPointer();
  1183. }
  1184. void set(APValue::LValueBase B, bool BInvalid = false) {
  1185. #ifndef NDEBUG
  1186. // We only allow a few types of invalid bases. Enforce that here.
  1187. if (BInvalid) {
  1188. const auto *E = B.get<const Expr *>();
  1189. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1190. "Unexpected type of invalid base");
  1191. }
  1192. #endif
  1193. Base = B;
  1194. Offset = CharUnits::fromQuantity(0);
  1195. InvalidBase = BInvalid;
  1196. Designator = SubobjectDesignator(getType(B));
  1197. IsNullPtr = false;
  1198. }
  1199. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1200. Base = (Expr *)nullptr;
  1201. Offset = CharUnits::fromQuantity(TargetVal);
  1202. InvalidBase = false;
  1203. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1204. IsNullPtr = true;
  1205. }
  1206. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1207. set(B, true);
  1208. }
  1209. // Check that this LValue is not based on a null pointer. If it is, produce
  1210. // a diagnostic and mark the designator as invalid.
  1211. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1212. CheckSubobjectKind CSK) {
  1213. if (Designator.Invalid)
  1214. return false;
  1215. if (IsNullPtr) {
  1216. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  1217. << CSK;
  1218. Designator.setInvalid();
  1219. return false;
  1220. }
  1221. return true;
  1222. }
  1223. // Check this LValue refers to an object. If not, set the designator to be
  1224. // invalid and emit a diagnostic.
  1225. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1226. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1227. Designator.checkSubobject(Info, E, CSK);
  1228. }
  1229. void addDecl(EvalInfo &Info, const Expr *E,
  1230. const Decl *D, bool Virtual = false) {
  1231. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1232. Designator.addDeclUnchecked(D, Virtual);
  1233. }
  1234. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1235. if (!Designator.Entries.empty()) {
  1236. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1237. Designator.setInvalid();
  1238. return;
  1239. }
  1240. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1241. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1242. Designator.FirstEntryIsAnUnsizedArray = true;
  1243. Designator.addUnsizedArrayUnchecked(ElemTy);
  1244. }
  1245. }
  1246. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1247. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1248. Designator.addArrayUnchecked(CAT);
  1249. }
  1250. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1251. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1252. Designator.addComplexUnchecked(EltTy, Imag);
  1253. }
  1254. void clearIsNullPointer() {
  1255. IsNullPtr = false;
  1256. }
  1257. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1258. const APSInt &Index, CharUnits ElementSize) {
  1259. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1260. // but we're not required to diagnose it and it's valid in C++.)
  1261. if (!Index)
  1262. return;
  1263. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1264. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1265. // offsets.
  1266. uint64_t Offset64 = Offset.getQuantity();
  1267. uint64_t ElemSize64 = ElementSize.getQuantity();
  1268. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1269. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1270. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1271. Designator.adjustIndex(Info, E, Index);
  1272. clearIsNullPointer();
  1273. }
  1274. void adjustOffset(CharUnits N) {
  1275. Offset += N;
  1276. if (N.getQuantity())
  1277. clearIsNullPointer();
  1278. }
  1279. };
  1280. struct MemberPtr {
  1281. MemberPtr() {}
  1282. explicit MemberPtr(const ValueDecl *Decl) :
  1283. DeclAndIsDerivedMember(Decl, false), Path() {}
  1284. /// The member or (direct or indirect) field referred to by this member
  1285. /// pointer, or 0 if this is a null member pointer.
  1286. const ValueDecl *getDecl() const {
  1287. return DeclAndIsDerivedMember.getPointer();
  1288. }
  1289. /// Is this actually a member of some type derived from the relevant class?
  1290. bool isDerivedMember() const {
  1291. return DeclAndIsDerivedMember.getInt();
  1292. }
  1293. /// Get the class which the declaration actually lives in.
  1294. const CXXRecordDecl *getContainingRecord() const {
  1295. return cast<CXXRecordDecl>(
  1296. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1297. }
  1298. void moveInto(APValue &V) const {
  1299. V = APValue(getDecl(), isDerivedMember(), Path);
  1300. }
  1301. void setFrom(const APValue &V) {
  1302. assert(V.isMemberPointer());
  1303. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1304. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1305. Path.clear();
  1306. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1307. Path.insert(Path.end(), P.begin(), P.end());
  1308. }
  1309. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1310. /// whether the member is a member of some class derived from the class type
  1311. /// of the member pointer.
  1312. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1313. /// Path - The path of base/derived classes from the member declaration's
  1314. /// class (exclusive) to the class type of the member pointer (inclusive).
  1315. SmallVector<const CXXRecordDecl*, 4> Path;
  1316. /// Perform a cast towards the class of the Decl (either up or down the
  1317. /// hierarchy).
  1318. bool castBack(const CXXRecordDecl *Class) {
  1319. assert(!Path.empty());
  1320. const CXXRecordDecl *Expected;
  1321. if (Path.size() >= 2)
  1322. Expected = Path[Path.size() - 2];
  1323. else
  1324. Expected = getContainingRecord();
  1325. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1326. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1327. // if B does not contain the original member and is not a base or
  1328. // derived class of the class containing the original member, the result
  1329. // of the cast is undefined.
  1330. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1331. // (D::*). We consider that to be a language defect.
  1332. return false;
  1333. }
  1334. Path.pop_back();
  1335. return true;
  1336. }
  1337. /// Perform a base-to-derived member pointer cast.
  1338. bool castToDerived(const CXXRecordDecl *Derived) {
  1339. if (!getDecl())
  1340. return true;
  1341. if (!isDerivedMember()) {
  1342. Path.push_back(Derived);
  1343. return true;
  1344. }
  1345. if (!castBack(Derived))
  1346. return false;
  1347. if (Path.empty())
  1348. DeclAndIsDerivedMember.setInt(false);
  1349. return true;
  1350. }
  1351. /// Perform a derived-to-base member pointer cast.
  1352. bool castToBase(const CXXRecordDecl *Base) {
  1353. if (!getDecl())
  1354. return true;
  1355. if (Path.empty())
  1356. DeclAndIsDerivedMember.setInt(true);
  1357. if (isDerivedMember()) {
  1358. Path.push_back(Base);
  1359. return true;
  1360. }
  1361. return castBack(Base);
  1362. }
  1363. };
  1364. /// Compare two member pointers, which are assumed to be of the same type.
  1365. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1366. if (!LHS.getDecl() || !RHS.getDecl())
  1367. return !LHS.getDecl() && !RHS.getDecl();
  1368. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1369. return false;
  1370. return LHS.Path == RHS.Path;
  1371. }
  1372. }
  1373. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1374. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1375. const LValue &This, const Expr *E,
  1376. bool AllowNonLiteralTypes = false);
  1377. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1378. bool InvalidBaseOK = false);
  1379. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1380. bool InvalidBaseOK = false);
  1381. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1382. EvalInfo &Info);
  1383. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1384. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1385. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1386. EvalInfo &Info);
  1387. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1388. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1389. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1390. EvalInfo &Info);
  1391. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1392. //===----------------------------------------------------------------------===//
  1393. // Misc utilities
  1394. //===----------------------------------------------------------------------===//
  1395. /// A helper function to create a temporary and set an LValue.
  1396. template <class KeyTy>
  1397. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1398. LValue &LV, CallStackFrame &Frame) {
  1399. LV.set({Key, Frame.Info.CurrentCall->Index,
  1400. Frame.Info.CurrentCall->getTempVersion()});
  1401. return Frame.createTemporary(Key, IsLifetimeExtended);
  1402. }
  1403. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1404. /// preserving its value (by extending by up to one bit as needed).
  1405. static void negateAsSigned(APSInt &Int) {
  1406. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1407. Int = Int.extend(Int.getBitWidth() + 1);
  1408. Int.setIsSigned(true);
  1409. }
  1410. Int = -Int;
  1411. }
  1412. /// Produce a string describing the given constexpr call.
  1413. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1414. unsigned ArgIndex = 0;
  1415. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1416. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1417. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1418. if (!IsMemberCall)
  1419. Out << *Frame->Callee << '(';
  1420. if (Frame->This && IsMemberCall) {
  1421. APValue Val;
  1422. Frame->This->moveInto(Val);
  1423. Val.printPretty(Out, Frame->Info.Ctx,
  1424. Frame->This->Designator.MostDerivedType);
  1425. // FIXME: Add parens around Val if needed.
  1426. Out << "->" << *Frame->Callee << '(';
  1427. IsMemberCall = false;
  1428. }
  1429. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1430. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1431. if (ArgIndex > (unsigned)IsMemberCall)
  1432. Out << ", ";
  1433. const ParmVarDecl *Param = *I;
  1434. const APValue &Arg = Frame->Arguments[ArgIndex];
  1435. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1436. if (ArgIndex == 0 && IsMemberCall)
  1437. Out << "->" << *Frame->Callee << '(';
  1438. }
  1439. Out << ')';
  1440. }
  1441. /// Evaluate an expression to see if it had side-effects, and discard its
  1442. /// result.
  1443. /// \return \c true if the caller should keep evaluating.
  1444. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1445. APValue Scratch;
  1446. if (!Evaluate(Scratch, Info, E))
  1447. // We don't need the value, but we might have skipped a side effect here.
  1448. return Info.noteSideEffect();
  1449. return true;
  1450. }
  1451. /// Should this call expression be treated as a string literal?
  1452. static bool IsStringLiteralCall(const CallExpr *E) {
  1453. unsigned Builtin = E->getBuiltinCallee();
  1454. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1455. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1456. }
  1457. static bool IsGlobalLValue(APValue::LValueBase B) {
  1458. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1459. // constant expression of pointer type that evaluates to...
  1460. // ... a null pointer value, or a prvalue core constant expression of type
  1461. // std::nullptr_t.
  1462. if (!B) return true;
  1463. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1464. // ... the address of an object with static storage duration,
  1465. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1466. return VD->hasGlobalStorage();
  1467. // ... the address of a function,
  1468. return isa<FunctionDecl>(D);
  1469. }
  1470. const Expr *E = B.get<const Expr*>();
  1471. switch (E->getStmtClass()) {
  1472. default:
  1473. return false;
  1474. case Expr::CompoundLiteralExprClass: {
  1475. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1476. return CLE->isFileScope() && CLE->isLValue();
  1477. }
  1478. case Expr::MaterializeTemporaryExprClass:
  1479. // A materialized temporary might have been lifetime-extended to static
  1480. // storage duration.
  1481. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1482. // A string literal has static storage duration.
  1483. case Expr::StringLiteralClass:
  1484. case Expr::PredefinedExprClass:
  1485. case Expr::ObjCStringLiteralClass:
  1486. case Expr::ObjCEncodeExprClass:
  1487. case Expr::CXXTypeidExprClass:
  1488. case Expr::CXXUuidofExprClass:
  1489. return true;
  1490. case Expr::CallExprClass:
  1491. return IsStringLiteralCall(cast<CallExpr>(E));
  1492. // For GCC compatibility, &&label has static storage duration.
  1493. case Expr::AddrLabelExprClass:
  1494. return true;
  1495. // A Block literal expression may be used as the initialization value for
  1496. // Block variables at global or local static scope.
  1497. case Expr::BlockExprClass:
  1498. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1499. case Expr::ImplicitValueInitExprClass:
  1500. // FIXME:
  1501. // We can never form an lvalue with an implicit value initialization as its
  1502. // base through expression evaluation, so these only appear in one case: the
  1503. // implicit variable declaration we invent when checking whether a constexpr
  1504. // constructor can produce a constant expression. We must assume that such
  1505. // an expression might be a global lvalue.
  1506. return true;
  1507. }
  1508. }
  1509. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1510. assert(Base && "no location for a null lvalue");
  1511. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1512. if (VD)
  1513. Info.Note(VD->getLocation(), diag::note_declared_at);
  1514. else
  1515. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1516. diag::note_constexpr_temporary_here);
  1517. }
  1518. /// Check that this reference or pointer core constant expression is a valid
  1519. /// value for an address or reference constant expression. Return true if we
  1520. /// can fold this expression, whether or not it's a constant expression.
  1521. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1522. QualType Type, const LValue &LVal,
  1523. Expr::ConstExprUsage Usage) {
  1524. bool IsReferenceType = Type->isReferenceType();
  1525. APValue::LValueBase Base = LVal.getLValueBase();
  1526. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1527. // Check that the object is a global. Note that the fake 'this' object we
  1528. // manufacture when checking potential constant expressions is conservatively
  1529. // assumed to be global here.
  1530. if (!IsGlobalLValue(Base)) {
  1531. if (Info.getLangOpts().CPlusPlus11) {
  1532. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1533. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1534. << IsReferenceType << !Designator.Entries.empty()
  1535. << !!VD << VD;
  1536. NoteLValueLocation(Info, Base);
  1537. } else {
  1538. Info.FFDiag(Loc);
  1539. }
  1540. // Don't allow references to temporaries to escape.
  1541. return false;
  1542. }
  1543. assert((Info.checkingPotentialConstantExpression() ||
  1544. LVal.getLValueCallIndex() == 0) &&
  1545. "have call index for global lvalue");
  1546. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1547. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1548. // Check if this is a thread-local variable.
  1549. if (Var->getTLSKind())
  1550. return false;
  1551. // A dllimport variable never acts like a constant.
  1552. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1553. return false;
  1554. }
  1555. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1556. // __declspec(dllimport) must be handled very carefully:
  1557. // We must never initialize an expression with the thunk in C++.
  1558. // Doing otherwise would allow the same id-expression to yield
  1559. // different addresses for the same function in different translation
  1560. // units. However, this means that we must dynamically initialize the
  1561. // expression with the contents of the import address table at runtime.
  1562. //
  1563. // The C language has no notion of ODR; furthermore, it has no notion of
  1564. // dynamic initialization. This means that we are permitted to
  1565. // perform initialization with the address of the thunk.
  1566. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1567. FD->hasAttr<DLLImportAttr>())
  1568. return false;
  1569. }
  1570. }
  1571. // Allow address constant expressions to be past-the-end pointers. This is
  1572. // an extension: the standard requires them to point to an object.
  1573. if (!IsReferenceType)
  1574. return true;
  1575. // A reference constant expression must refer to an object.
  1576. if (!Base) {
  1577. // FIXME: diagnostic
  1578. Info.CCEDiag(Loc);
  1579. return true;
  1580. }
  1581. // Does this refer one past the end of some object?
  1582. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1583. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1584. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1585. << !Designator.Entries.empty() << !!VD << VD;
  1586. NoteLValueLocation(Info, Base);
  1587. }
  1588. return true;
  1589. }
  1590. /// Member pointers are constant expressions unless they point to a
  1591. /// non-virtual dllimport member function.
  1592. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1593. SourceLocation Loc,
  1594. QualType Type,
  1595. const APValue &Value,
  1596. Expr::ConstExprUsage Usage) {
  1597. const ValueDecl *Member = Value.getMemberPointerDecl();
  1598. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1599. if (!FD)
  1600. return true;
  1601. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1602. !FD->hasAttr<DLLImportAttr>();
  1603. }
  1604. /// Check that this core constant expression is of literal type, and if not,
  1605. /// produce an appropriate diagnostic.
  1606. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1607. const LValue *This = nullptr) {
  1608. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1609. return true;
  1610. // C++1y: A constant initializer for an object o [...] may also invoke
  1611. // constexpr constructors for o and its subobjects even if those objects
  1612. // are of non-literal class types.
  1613. //
  1614. // C++11 missed this detail for aggregates, so classes like this:
  1615. // struct foo_t { union { int i; volatile int j; } u; };
  1616. // are not (obviously) initializable like so:
  1617. // __attribute__((__require_constant_initialization__))
  1618. // static const foo_t x = {{0}};
  1619. // because "i" is a subobject with non-literal initialization (due to the
  1620. // volatile member of the union). See:
  1621. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1622. // Therefore, we use the C++1y behavior.
  1623. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1624. return true;
  1625. // Prvalue constant expressions must be of literal types.
  1626. if (Info.getLangOpts().CPlusPlus11)
  1627. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1628. << E->getType();
  1629. else
  1630. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1631. return false;
  1632. }
  1633. /// Check that this core constant expression value is a valid value for a
  1634. /// constant expression. If not, report an appropriate diagnostic. Does not
  1635. /// check that the expression is of literal type.
  1636. static bool
  1637. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1638. const APValue &Value,
  1639. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1640. if (Value.isUninit()) {
  1641. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1642. << true << Type;
  1643. return false;
  1644. }
  1645. // We allow _Atomic(T) to be initialized from anything that T can be
  1646. // initialized from.
  1647. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1648. Type = AT->getValueType();
  1649. // Core issue 1454: For a literal constant expression of array or class type,
  1650. // each subobject of its value shall have been initialized by a constant
  1651. // expression.
  1652. if (Value.isArray()) {
  1653. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1654. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1655. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1656. Value.getArrayInitializedElt(I), Usage))
  1657. return false;
  1658. }
  1659. if (!Value.hasArrayFiller())
  1660. return true;
  1661. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1662. Usage);
  1663. }
  1664. if (Value.isUnion() && Value.getUnionField()) {
  1665. return CheckConstantExpression(Info, DiagLoc,
  1666. Value.getUnionField()->getType(),
  1667. Value.getUnionValue(), Usage);
  1668. }
  1669. if (Value.isStruct()) {
  1670. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1671. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1672. unsigned BaseIndex = 0;
  1673. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1674. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1675. Value.getStructBase(BaseIndex), Usage))
  1676. return false;
  1677. ++BaseIndex;
  1678. }
  1679. }
  1680. for (const auto *I : RD->fields()) {
  1681. if (I->isUnnamedBitfield())
  1682. continue;
  1683. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1684. Value.getStructField(I->getFieldIndex()),
  1685. Usage))
  1686. return false;
  1687. }
  1688. }
  1689. if (Value.isLValue()) {
  1690. LValue LVal;
  1691. LVal.setFrom(Info.Ctx, Value);
  1692. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1693. }
  1694. if (Value.isMemberPointer())
  1695. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1696. // Everything else is fine.
  1697. return true;
  1698. }
  1699. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1700. return LVal.Base.dyn_cast<const ValueDecl*>();
  1701. }
  1702. static bool IsLiteralLValue(const LValue &Value) {
  1703. if (Value.getLValueCallIndex())
  1704. return false;
  1705. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1706. return E && !isa<MaterializeTemporaryExpr>(E);
  1707. }
  1708. static bool IsWeakLValue(const LValue &Value) {
  1709. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1710. return Decl && Decl->isWeak();
  1711. }
  1712. static bool isZeroSized(const LValue &Value) {
  1713. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1714. if (Decl && isa<VarDecl>(Decl)) {
  1715. QualType Ty = Decl->getType();
  1716. if (Ty->isArrayType())
  1717. return Ty->isIncompleteType() ||
  1718. Decl->getASTContext().getTypeSize(Ty) == 0;
  1719. }
  1720. return false;
  1721. }
  1722. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1723. // A null base expression indicates a null pointer. These are always
  1724. // evaluatable, and they are false unless the offset is zero.
  1725. if (!Value.getLValueBase()) {
  1726. Result = !Value.getLValueOffset().isZero();
  1727. return true;
  1728. }
  1729. // We have a non-null base. These are generally known to be true, but if it's
  1730. // a weak declaration it can be null at runtime.
  1731. Result = true;
  1732. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1733. return !Decl || !Decl->isWeak();
  1734. }
  1735. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1736. switch (Val.getKind()) {
  1737. case APValue::Uninitialized:
  1738. return false;
  1739. case APValue::Int:
  1740. Result = Val.getInt().getBoolValue();
  1741. return true;
  1742. case APValue::Float:
  1743. Result = !Val.getFloat().isZero();
  1744. return true;
  1745. case APValue::ComplexInt:
  1746. Result = Val.getComplexIntReal().getBoolValue() ||
  1747. Val.getComplexIntImag().getBoolValue();
  1748. return true;
  1749. case APValue::ComplexFloat:
  1750. Result = !Val.getComplexFloatReal().isZero() ||
  1751. !Val.getComplexFloatImag().isZero();
  1752. return true;
  1753. case APValue::LValue:
  1754. return EvalPointerValueAsBool(Val, Result);
  1755. case APValue::MemberPointer:
  1756. Result = Val.getMemberPointerDecl();
  1757. return true;
  1758. case APValue::Vector:
  1759. case APValue::Array:
  1760. case APValue::Struct:
  1761. case APValue::Union:
  1762. case APValue::AddrLabelDiff:
  1763. return false;
  1764. }
  1765. llvm_unreachable("unknown APValue kind");
  1766. }
  1767. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1768. EvalInfo &Info) {
  1769. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1770. APValue Val;
  1771. if (!Evaluate(Val, Info, E))
  1772. return false;
  1773. return HandleConversionToBool(Val, Result);
  1774. }
  1775. template<typename T>
  1776. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1777. const T &SrcValue, QualType DestType) {
  1778. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1779. << SrcValue << DestType;
  1780. return Info.noteUndefinedBehavior();
  1781. }
  1782. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1783. QualType SrcType, const APFloat &Value,
  1784. QualType DestType, APSInt &Result) {
  1785. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1786. // Determine whether we are converting to unsigned or signed.
  1787. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1788. Result = APSInt(DestWidth, !DestSigned);
  1789. bool ignored;
  1790. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1791. & APFloat::opInvalidOp)
  1792. return HandleOverflow(Info, E, Value, DestType);
  1793. return true;
  1794. }
  1795. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1796. QualType SrcType, QualType DestType,
  1797. APFloat &Result) {
  1798. APFloat Value = Result;
  1799. bool ignored;
  1800. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1801. APFloat::rmNearestTiesToEven, &ignored)
  1802. & APFloat::opOverflow)
  1803. return HandleOverflow(Info, E, Value, DestType);
  1804. return true;
  1805. }
  1806. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1807. QualType DestType, QualType SrcType,
  1808. const APSInt &Value) {
  1809. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1810. APSInt Result = Value;
  1811. // Figure out if this is a truncate, extend or noop cast.
  1812. // If the input is signed, do a sign extend, noop, or truncate.
  1813. Result = Result.extOrTrunc(DestWidth);
  1814. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1815. return Result;
  1816. }
  1817. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1818. QualType SrcType, const APSInt &Value,
  1819. QualType DestType, APFloat &Result) {
  1820. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1821. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1822. APFloat::rmNearestTiesToEven)
  1823. & APFloat::opOverflow)
  1824. return HandleOverflow(Info, E, Value, DestType);
  1825. return true;
  1826. }
  1827. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1828. APValue &Value, const FieldDecl *FD) {
  1829. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1830. if (!Value.isInt()) {
  1831. // Trying to store a pointer-cast-to-integer into a bitfield.
  1832. // FIXME: In this case, we should provide the diagnostic for casting
  1833. // a pointer to an integer.
  1834. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1835. Info.FFDiag(E);
  1836. return false;
  1837. }
  1838. APSInt &Int = Value.getInt();
  1839. unsigned OldBitWidth = Int.getBitWidth();
  1840. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1841. if (NewBitWidth < OldBitWidth)
  1842. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1843. return true;
  1844. }
  1845. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1846. llvm::APInt &Res) {
  1847. APValue SVal;
  1848. if (!Evaluate(SVal, Info, E))
  1849. return false;
  1850. if (SVal.isInt()) {
  1851. Res = SVal.getInt();
  1852. return true;
  1853. }
  1854. if (SVal.isFloat()) {
  1855. Res = SVal.getFloat().bitcastToAPInt();
  1856. return true;
  1857. }
  1858. if (SVal.isVector()) {
  1859. QualType VecTy = E->getType();
  1860. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1861. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1862. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1863. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1864. Res = llvm::APInt::getNullValue(VecSize);
  1865. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1866. APValue &Elt = SVal.getVectorElt(i);
  1867. llvm::APInt EltAsInt;
  1868. if (Elt.isInt()) {
  1869. EltAsInt = Elt.getInt();
  1870. } else if (Elt.isFloat()) {
  1871. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1872. } else {
  1873. // Don't try to handle vectors of anything other than int or float
  1874. // (not sure if it's possible to hit this case).
  1875. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1876. return false;
  1877. }
  1878. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1879. if (BigEndian)
  1880. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1881. else
  1882. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1883. }
  1884. return true;
  1885. }
  1886. // Give up if the input isn't an int, float, or vector. For example, we
  1887. // reject "(v4i16)(intptr_t)&a".
  1888. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1889. return false;
  1890. }
  1891. /// Perform the given integer operation, which is known to need at most BitWidth
  1892. /// bits, and check for overflow in the original type (if that type was not an
  1893. /// unsigned type).
  1894. template<typename Operation>
  1895. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1896. const APSInt &LHS, const APSInt &RHS,
  1897. unsigned BitWidth, Operation Op,
  1898. APSInt &Result) {
  1899. if (LHS.isUnsigned()) {
  1900. Result = Op(LHS, RHS);
  1901. return true;
  1902. }
  1903. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1904. Result = Value.trunc(LHS.getBitWidth());
  1905. if (Result.extend(BitWidth) != Value) {
  1906. if (Info.checkingForOverflow())
  1907. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1908. diag::warn_integer_constant_overflow)
  1909. << Result.toString(10) << E->getType();
  1910. else
  1911. return HandleOverflow(Info, E, Value, E->getType());
  1912. }
  1913. return true;
  1914. }
  1915. /// Perform the given binary integer operation.
  1916. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1917. BinaryOperatorKind Opcode, APSInt RHS,
  1918. APSInt &Result) {
  1919. switch (Opcode) {
  1920. default:
  1921. Info.FFDiag(E);
  1922. return false;
  1923. case BO_Mul:
  1924. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1925. std::multiplies<APSInt>(), Result);
  1926. case BO_Add:
  1927. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1928. std::plus<APSInt>(), Result);
  1929. case BO_Sub:
  1930. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1931. std::minus<APSInt>(), Result);
  1932. case BO_And: Result = LHS & RHS; return true;
  1933. case BO_Xor: Result = LHS ^ RHS; return true;
  1934. case BO_Or: Result = LHS | RHS; return true;
  1935. case BO_Div:
  1936. case BO_Rem:
  1937. if (RHS == 0) {
  1938. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  1939. return false;
  1940. }
  1941. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1942. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  1943. // this operation and gives the two's complement result.
  1944. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1945. LHS.isSigned() && LHS.isMinSignedValue())
  1946. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  1947. E->getType());
  1948. return true;
  1949. case BO_Shl: {
  1950. if (Info.getLangOpts().OpenCL)
  1951. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1952. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1953. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1954. RHS.isUnsigned());
  1955. else if (RHS.isSigned() && RHS.isNegative()) {
  1956. // During constant-folding, a negative shift is an opposite shift. Such
  1957. // a shift is not a constant expression.
  1958. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1959. RHS = -RHS;
  1960. goto shift_right;
  1961. }
  1962. shift_left:
  1963. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  1964. // the shifted type.
  1965. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1966. if (SA != RHS) {
  1967. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1968. << RHS << E->getType() << LHS.getBitWidth();
  1969. } else if (LHS.isSigned()) {
  1970. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  1971. // operand, and must not overflow the corresponding unsigned type.
  1972. if (LHS.isNegative())
  1973. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  1974. else if (LHS.countLeadingZeros() < SA)
  1975. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  1976. }
  1977. Result = LHS << SA;
  1978. return true;
  1979. }
  1980. case BO_Shr: {
  1981. if (Info.getLangOpts().OpenCL)
  1982. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1983. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1984. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1985. RHS.isUnsigned());
  1986. else if (RHS.isSigned() && RHS.isNegative()) {
  1987. // During constant-folding, a negative shift is an opposite shift. Such a
  1988. // shift is not a constant expression.
  1989. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1990. RHS = -RHS;
  1991. goto shift_left;
  1992. }
  1993. shift_right:
  1994. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  1995. // shifted type.
  1996. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1997. if (SA != RHS)
  1998. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1999. << RHS << E->getType() << LHS.getBitWidth();
  2000. Result = LHS >> SA;
  2001. return true;
  2002. }
  2003. case BO_LT: Result = LHS < RHS; return true;
  2004. case BO_GT: Result = LHS > RHS; return true;
  2005. case BO_LE: Result = LHS <= RHS; return true;
  2006. case BO_GE: Result = LHS >= RHS; return true;
  2007. case BO_EQ: Result = LHS == RHS; return true;
  2008. case BO_NE: Result = LHS != RHS; return true;
  2009. case BO_Cmp:
  2010. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2011. }
  2012. }
  2013. /// Perform the given binary floating-point operation, in-place, on LHS.
  2014. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2015. APFloat &LHS, BinaryOperatorKind Opcode,
  2016. const APFloat &RHS) {
  2017. switch (Opcode) {
  2018. default:
  2019. Info.FFDiag(E);
  2020. return false;
  2021. case BO_Mul:
  2022. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2023. break;
  2024. case BO_Add:
  2025. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2026. break;
  2027. case BO_Sub:
  2028. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2029. break;
  2030. case BO_Div:
  2031. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2032. break;
  2033. }
  2034. if (LHS.isInfinity() || LHS.isNaN()) {
  2035. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2036. return Info.noteUndefinedBehavior();
  2037. }
  2038. return true;
  2039. }
  2040. /// Cast an lvalue referring to a base subobject to a derived class, by
  2041. /// truncating the lvalue's path to the given length.
  2042. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2043. const RecordDecl *TruncatedType,
  2044. unsigned TruncatedElements) {
  2045. SubobjectDesignator &D = Result.Designator;
  2046. // Check we actually point to a derived class object.
  2047. if (TruncatedElements == D.Entries.size())
  2048. return true;
  2049. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2050. "not casting to a derived class");
  2051. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2052. return false;
  2053. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2054. const RecordDecl *RD = TruncatedType;
  2055. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2056. if (RD->isInvalidDecl()) return false;
  2057. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2058. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2059. if (isVirtualBaseClass(D.Entries[I]))
  2060. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2061. else
  2062. Result.Offset -= Layout.getBaseClassOffset(Base);
  2063. RD = Base;
  2064. }
  2065. D.Entries.resize(TruncatedElements);
  2066. return true;
  2067. }
  2068. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2069. const CXXRecordDecl *Derived,
  2070. const CXXRecordDecl *Base,
  2071. const ASTRecordLayout *RL = nullptr) {
  2072. if (!RL) {
  2073. if (Derived->isInvalidDecl()) return false;
  2074. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2075. }
  2076. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2077. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2078. return true;
  2079. }
  2080. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2081. const CXXRecordDecl *DerivedDecl,
  2082. const CXXBaseSpecifier *Base) {
  2083. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2084. if (!Base->isVirtual())
  2085. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2086. SubobjectDesignator &D = Obj.Designator;
  2087. if (D.Invalid)
  2088. return false;
  2089. // Extract most-derived object and corresponding type.
  2090. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2091. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2092. return false;
  2093. // Find the virtual base class.
  2094. if (DerivedDecl->isInvalidDecl()) return false;
  2095. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2096. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2097. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2098. return true;
  2099. }
  2100. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2101. QualType Type, LValue &Result) {
  2102. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2103. PathE = E->path_end();
  2104. PathI != PathE; ++PathI) {
  2105. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2106. *PathI))
  2107. return false;
  2108. Type = (*PathI)->getType();
  2109. }
  2110. return true;
  2111. }
  2112. /// Update LVal to refer to the given field, which must be a member of the type
  2113. /// currently described by LVal.
  2114. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2115. const FieldDecl *FD,
  2116. const ASTRecordLayout *RL = nullptr) {
  2117. if (!RL) {
  2118. if (FD->getParent()->isInvalidDecl()) return false;
  2119. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2120. }
  2121. unsigned I = FD->getFieldIndex();
  2122. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2123. LVal.addDecl(Info, E, FD);
  2124. return true;
  2125. }
  2126. /// Update LVal to refer to the given indirect field.
  2127. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2128. LValue &LVal,
  2129. const IndirectFieldDecl *IFD) {
  2130. for (const auto *C : IFD->chain())
  2131. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2132. return false;
  2133. return true;
  2134. }
  2135. /// Get the size of the given type in char units.
  2136. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2137. QualType Type, CharUnits &Size) {
  2138. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2139. // extension.
  2140. if (Type->isVoidType() || Type->isFunctionType()) {
  2141. Size = CharUnits::One();
  2142. return true;
  2143. }
  2144. if (Type->isDependentType()) {
  2145. Info.FFDiag(Loc);
  2146. return false;
  2147. }
  2148. if (!Type->isConstantSizeType()) {
  2149. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2150. // FIXME: Better diagnostic.
  2151. Info.FFDiag(Loc);
  2152. return false;
  2153. }
  2154. Size = Info.Ctx.getTypeSizeInChars(Type);
  2155. return true;
  2156. }
  2157. /// Update a pointer value to model pointer arithmetic.
  2158. /// \param Info - Information about the ongoing evaluation.
  2159. /// \param E - The expression being evaluated, for diagnostic purposes.
  2160. /// \param LVal - The pointer value to be updated.
  2161. /// \param EltTy - The pointee type represented by LVal.
  2162. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2163. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2164. LValue &LVal, QualType EltTy,
  2165. APSInt Adjustment) {
  2166. CharUnits SizeOfPointee;
  2167. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2168. return false;
  2169. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2170. return true;
  2171. }
  2172. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2173. LValue &LVal, QualType EltTy,
  2174. int64_t Adjustment) {
  2175. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2176. APSInt::get(Adjustment));
  2177. }
  2178. /// Update an lvalue to refer to a component of a complex number.
  2179. /// \param Info - Information about the ongoing evaluation.
  2180. /// \param LVal - The lvalue to be updated.
  2181. /// \param EltTy - The complex number's component type.
  2182. /// \param Imag - False for the real component, true for the imaginary.
  2183. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2184. LValue &LVal, QualType EltTy,
  2185. bool Imag) {
  2186. if (Imag) {
  2187. CharUnits SizeOfComponent;
  2188. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2189. return false;
  2190. LVal.Offset += SizeOfComponent;
  2191. }
  2192. LVal.addComplex(Info, E, EltTy, Imag);
  2193. return true;
  2194. }
  2195. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2196. QualType Type, const LValue &LVal,
  2197. APValue &RVal);
  2198. /// Try to evaluate the initializer for a variable declaration.
  2199. ///
  2200. /// \param Info Information about the ongoing evaluation.
  2201. /// \param E An expression to be used when printing diagnostics.
  2202. /// \param VD The variable whose initializer should be obtained.
  2203. /// \param Frame The frame in which the variable was created. Must be null
  2204. /// if this variable is not local to the evaluation.
  2205. /// \param Result Filled in with a pointer to the value of the variable.
  2206. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2207. const VarDecl *VD, CallStackFrame *Frame,
  2208. APValue *&Result, const LValue *LVal) {
  2209. // If this is a parameter to an active constexpr function call, perform
  2210. // argument substitution.
  2211. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2212. // Assume arguments of a potential constant expression are unknown
  2213. // constant expressions.
  2214. if (Info.checkingPotentialConstantExpression())
  2215. return false;
  2216. if (!Frame || !Frame->Arguments) {
  2217. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2218. return false;
  2219. }
  2220. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2221. return true;
  2222. }
  2223. // If this is a local variable, dig out its value.
  2224. if (Frame) {
  2225. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2226. : Frame->getCurrentTemporary(VD);
  2227. if (!Result) {
  2228. // Assume variables referenced within a lambda's call operator that were
  2229. // not declared within the call operator are captures and during checking
  2230. // of a potential constant expression, assume they are unknown constant
  2231. // expressions.
  2232. assert(isLambdaCallOperator(Frame->Callee) &&
  2233. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2234. "missing value for local variable");
  2235. if (Info.checkingPotentialConstantExpression())
  2236. return false;
  2237. // FIXME: implement capture evaluation during constant expr evaluation.
  2238. Info.FFDiag(E->getLocStart(),
  2239. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2240. << "captures not currently allowed";
  2241. return false;
  2242. }
  2243. return true;
  2244. }
  2245. // Dig out the initializer, and use the declaration which it's attached to.
  2246. const Expr *Init = VD->getAnyInitializer(VD);
  2247. if (!Init || Init->isValueDependent()) {
  2248. // If we're checking a potential constant expression, the variable could be
  2249. // initialized later.
  2250. if (!Info.checkingPotentialConstantExpression())
  2251. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2252. return false;
  2253. }
  2254. // If we're currently evaluating the initializer of this declaration, use that
  2255. // in-flight value.
  2256. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2257. Result = Info.EvaluatingDeclValue;
  2258. return true;
  2259. }
  2260. // Never evaluate the initializer of a weak variable. We can't be sure that
  2261. // this is the definition which will be used.
  2262. if (VD->isWeak()) {
  2263. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2264. return false;
  2265. }
  2266. // Check that we can fold the initializer. In C++, we will have already done
  2267. // this in the cases where it matters for conformance.
  2268. SmallVector<PartialDiagnosticAt, 8> Notes;
  2269. if (!VD->evaluateValue(Notes)) {
  2270. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2271. Notes.size() + 1) << VD;
  2272. Info.Note(VD->getLocation(), diag::note_declared_at);
  2273. Info.addNotes(Notes);
  2274. return false;
  2275. } else if (!VD->checkInitIsICE()) {
  2276. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2277. Notes.size() + 1) << VD;
  2278. Info.Note(VD->getLocation(), diag::note_declared_at);
  2279. Info.addNotes(Notes);
  2280. }
  2281. Result = VD->getEvaluatedValue();
  2282. return true;
  2283. }
  2284. static bool IsConstNonVolatile(QualType T) {
  2285. Qualifiers Quals = T.getQualifiers();
  2286. return Quals.hasConst() && !Quals.hasVolatile();
  2287. }
  2288. /// Get the base index of the given base class within an APValue representing
  2289. /// the given derived class.
  2290. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2291. const CXXRecordDecl *Base) {
  2292. Base = Base->getCanonicalDecl();
  2293. unsigned Index = 0;
  2294. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2295. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2296. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2297. return Index;
  2298. }
  2299. llvm_unreachable("base class missing from derived class's bases list");
  2300. }
  2301. /// Extract the value of a character from a string literal.
  2302. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2303. uint64_t Index) {
  2304. // FIXME: Support MakeStringConstant
  2305. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2306. std::string Str;
  2307. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2308. assert(Index <= Str.size() && "Index too large");
  2309. return APSInt::getUnsigned(Str.c_str()[Index]);
  2310. }
  2311. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2312. Lit = PE->getFunctionName();
  2313. const StringLiteral *S = cast<StringLiteral>(Lit);
  2314. const ConstantArrayType *CAT =
  2315. Info.Ctx.getAsConstantArrayType(S->getType());
  2316. assert(CAT && "string literal isn't an array");
  2317. QualType CharType = CAT->getElementType();
  2318. assert(CharType->isIntegerType() && "unexpected character type");
  2319. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2320. CharType->isUnsignedIntegerType());
  2321. if (Index < S->getLength())
  2322. Value = S->getCodeUnit(Index);
  2323. return Value;
  2324. }
  2325. // Expand a string literal into an array of characters.
  2326. static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
  2327. APValue &Result) {
  2328. const StringLiteral *S = cast<StringLiteral>(Lit);
  2329. const ConstantArrayType *CAT =
  2330. Info.Ctx.getAsConstantArrayType(S->getType());
  2331. assert(CAT && "string literal isn't an array");
  2332. QualType CharType = CAT->getElementType();
  2333. assert(CharType->isIntegerType() && "unexpected character type");
  2334. unsigned Elts = CAT->getSize().getZExtValue();
  2335. Result = APValue(APValue::UninitArray(),
  2336. std::min(S->getLength(), Elts), Elts);
  2337. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2338. CharType->isUnsignedIntegerType());
  2339. if (Result.hasArrayFiller())
  2340. Result.getArrayFiller() = APValue(Value);
  2341. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2342. Value = S->getCodeUnit(I);
  2343. Result.getArrayInitializedElt(I) = APValue(Value);
  2344. }
  2345. }
  2346. // Expand an array so that it has more than Index filled elements.
  2347. static void expandArray(APValue &Array, unsigned Index) {
  2348. unsigned Size = Array.getArraySize();
  2349. assert(Index < Size);
  2350. // Always at least double the number of elements for which we store a value.
  2351. unsigned OldElts = Array.getArrayInitializedElts();
  2352. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2353. NewElts = std::min(Size, std::max(NewElts, 8u));
  2354. // Copy the data across.
  2355. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2356. for (unsigned I = 0; I != OldElts; ++I)
  2357. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2358. for (unsigned I = OldElts; I != NewElts; ++I)
  2359. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2360. if (NewValue.hasArrayFiller())
  2361. NewValue.getArrayFiller() = Array.getArrayFiller();
  2362. Array.swap(NewValue);
  2363. }
  2364. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2365. /// conversion. If it's of class type, we may assume that the copy operation
  2366. /// is trivial. Note that this is never true for a union type with fields
  2367. /// (because the copy always "reads" the active member) and always true for
  2368. /// a non-class type.
  2369. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2370. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2371. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2372. return true;
  2373. if (RD->isEmpty())
  2374. return false;
  2375. for (auto *Field : RD->fields())
  2376. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2377. return true;
  2378. for (auto &BaseSpec : RD->bases())
  2379. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2380. return true;
  2381. return false;
  2382. }
  2383. /// Diagnose an attempt to read from any unreadable field within the specified
  2384. /// type, which might be a class type.
  2385. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2386. QualType T) {
  2387. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2388. if (!RD)
  2389. return false;
  2390. if (!RD->hasMutableFields())
  2391. return false;
  2392. for (auto *Field : RD->fields()) {
  2393. // If we're actually going to read this field in some way, then it can't
  2394. // be mutable. If we're in a union, then assigning to a mutable field
  2395. // (even an empty one) can change the active member, so that's not OK.
  2396. // FIXME: Add core issue number for the union case.
  2397. if (Field->isMutable() &&
  2398. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2399. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2400. Info.Note(Field->getLocation(), diag::note_declared_at);
  2401. return true;
  2402. }
  2403. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2404. return true;
  2405. }
  2406. for (auto &BaseSpec : RD->bases())
  2407. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2408. return true;
  2409. // All mutable fields were empty, and thus not actually read.
  2410. return false;
  2411. }
  2412. /// Kinds of access we can perform on an object, for diagnostics.
  2413. enum AccessKinds {
  2414. AK_Read,
  2415. AK_Assign,
  2416. AK_Increment,
  2417. AK_Decrement
  2418. };
  2419. namespace {
  2420. /// A handle to a complete object (an object that is not a subobject of
  2421. /// another object).
  2422. struct CompleteObject {
  2423. /// The value of the complete object.
  2424. APValue *Value;
  2425. /// The type of the complete object.
  2426. QualType Type;
  2427. bool LifetimeStartedInEvaluation;
  2428. CompleteObject() : Value(nullptr) {}
  2429. CompleteObject(APValue *Value, QualType Type,
  2430. bool LifetimeStartedInEvaluation)
  2431. : Value(Value), Type(Type),
  2432. LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
  2433. assert(Value && "missing value for complete object");
  2434. }
  2435. explicit operator bool() const { return Value; }
  2436. };
  2437. } // end anonymous namespace
  2438. /// Find the designated sub-object of an rvalue.
  2439. template<typename SubobjectHandler>
  2440. typename SubobjectHandler::result_type
  2441. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2442. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2443. if (Sub.Invalid)
  2444. // A diagnostic will have already been produced.
  2445. return handler.failed();
  2446. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2447. if (Info.getLangOpts().CPlusPlus11)
  2448. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2449. ? diag::note_constexpr_access_past_end
  2450. : diag::note_constexpr_access_unsized_array)
  2451. << handler.AccessKind;
  2452. else
  2453. Info.FFDiag(E);
  2454. return handler.failed();
  2455. }
  2456. APValue *O = Obj.Value;
  2457. QualType ObjType = Obj.Type;
  2458. const FieldDecl *LastField = nullptr;
  2459. const bool MayReadMutableMembers =
  2460. Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
  2461. // Walk the designator's path to find the subobject.
  2462. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2463. if (O->isUninit()) {
  2464. if (!Info.checkingPotentialConstantExpression())
  2465. Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
  2466. return handler.failed();
  2467. }
  2468. if (I == N) {
  2469. // If we are reading an object of class type, there may still be more
  2470. // things we need to check: if there are any mutable subobjects, we
  2471. // cannot perform this read. (This only happens when performing a trivial
  2472. // copy or assignment.)
  2473. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2474. !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
  2475. return handler.failed();
  2476. if (!handler.found(*O, ObjType))
  2477. return false;
  2478. // If we modified a bit-field, truncate it to the right width.
  2479. if (handler.AccessKind != AK_Read &&
  2480. LastField && LastField->isBitField() &&
  2481. !truncateBitfieldValue(Info, E, *O, LastField))
  2482. return false;
  2483. return true;
  2484. }
  2485. LastField = nullptr;
  2486. if (ObjType->isArrayType()) {
  2487. // Next subobject is an array element.
  2488. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2489. assert(CAT && "vla in literal type?");
  2490. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2491. if (CAT->getSize().ule(Index)) {
  2492. // Note, it should not be possible to form a pointer with a valid
  2493. // designator which points more than one past the end of the array.
  2494. if (Info.getLangOpts().CPlusPlus11)
  2495. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2496. << handler.AccessKind;
  2497. else
  2498. Info.FFDiag(E);
  2499. return handler.failed();
  2500. }
  2501. ObjType = CAT->getElementType();
  2502. // An array object is represented as either an Array APValue or as an
  2503. // LValue which refers to a string literal.
  2504. if (O->isLValue()) {
  2505. assert(I == N - 1 && "extracting subobject of character?");
  2506. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  2507. if (handler.AccessKind != AK_Read)
  2508. expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
  2509. *O);
  2510. else
  2511. return handler.foundString(*O, ObjType, Index);
  2512. }
  2513. if (O->getArrayInitializedElts() > Index)
  2514. O = &O->getArrayInitializedElt(Index);
  2515. else if (handler.AccessKind != AK_Read) {
  2516. expandArray(*O, Index);
  2517. O = &O->getArrayInitializedElt(Index);
  2518. } else
  2519. O = &O->getArrayFiller();
  2520. } else if (ObjType->isAnyComplexType()) {
  2521. // Next subobject is a complex number.
  2522. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2523. if (Index > 1) {
  2524. if (Info.getLangOpts().CPlusPlus11)
  2525. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2526. << handler.AccessKind;
  2527. else
  2528. Info.FFDiag(E);
  2529. return handler.failed();
  2530. }
  2531. bool WasConstQualified = ObjType.isConstQualified();
  2532. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2533. if (WasConstQualified)
  2534. ObjType.addConst();
  2535. assert(I == N - 1 && "extracting subobject of scalar?");
  2536. if (O->isComplexInt()) {
  2537. return handler.found(Index ? O->getComplexIntImag()
  2538. : O->getComplexIntReal(), ObjType);
  2539. } else {
  2540. assert(O->isComplexFloat());
  2541. return handler.found(Index ? O->getComplexFloatImag()
  2542. : O->getComplexFloatReal(), ObjType);
  2543. }
  2544. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2545. // In C++14 onwards, it is permitted to read a mutable member whose
  2546. // lifetime began within the evaluation.
  2547. // FIXME: Should we also allow this in C++11?
  2548. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2549. !MayReadMutableMembers) {
  2550. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2551. << Field;
  2552. Info.Note(Field->getLocation(), diag::note_declared_at);
  2553. return handler.failed();
  2554. }
  2555. // Next subobject is a class, struct or union field.
  2556. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2557. if (RD->isUnion()) {
  2558. const FieldDecl *UnionField = O->getUnionField();
  2559. if (!UnionField ||
  2560. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2561. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2562. << handler.AccessKind << Field << !UnionField << UnionField;
  2563. return handler.failed();
  2564. }
  2565. O = &O->getUnionValue();
  2566. } else
  2567. O = &O->getStructField(Field->getFieldIndex());
  2568. bool WasConstQualified = ObjType.isConstQualified();
  2569. ObjType = Field->getType();
  2570. if (WasConstQualified && !Field->isMutable())
  2571. ObjType.addConst();
  2572. if (ObjType.isVolatileQualified()) {
  2573. if (Info.getLangOpts().CPlusPlus) {
  2574. // FIXME: Include a description of the path to the volatile subobject.
  2575. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2576. << handler.AccessKind << 2 << Field;
  2577. Info.Note(Field->getLocation(), diag::note_declared_at);
  2578. } else {
  2579. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2580. }
  2581. return handler.failed();
  2582. }
  2583. LastField = Field;
  2584. } else {
  2585. // Next subobject is a base class.
  2586. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2587. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2588. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2589. bool WasConstQualified = ObjType.isConstQualified();
  2590. ObjType = Info.Ctx.getRecordType(Base);
  2591. if (WasConstQualified)
  2592. ObjType.addConst();
  2593. }
  2594. }
  2595. }
  2596. namespace {
  2597. struct ExtractSubobjectHandler {
  2598. EvalInfo &Info;
  2599. APValue &Result;
  2600. static const AccessKinds AccessKind = AK_Read;
  2601. typedef bool result_type;
  2602. bool failed() { return false; }
  2603. bool found(APValue &Subobj, QualType SubobjType) {
  2604. Result = Subobj;
  2605. return true;
  2606. }
  2607. bool found(APSInt &Value, QualType SubobjType) {
  2608. Result = APValue(Value);
  2609. return true;
  2610. }
  2611. bool found(APFloat &Value, QualType SubobjType) {
  2612. Result = APValue(Value);
  2613. return true;
  2614. }
  2615. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2616. Result = APValue(extractStringLiteralCharacter(
  2617. Info, Subobj.getLValueBase().get<const Expr *>(), Character));
  2618. return true;
  2619. }
  2620. };
  2621. } // end anonymous namespace
  2622. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2623. /// Extract the designated sub-object of an rvalue.
  2624. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2625. const CompleteObject &Obj,
  2626. const SubobjectDesignator &Sub,
  2627. APValue &Result) {
  2628. ExtractSubobjectHandler Handler = { Info, Result };
  2629. return findSubobject(Info, E, Obj, Sub, Handler);
  2630. }
  2631. namespace {
  2632. struct ModifySubobjectHandler {
  2633. EvalInfo &Info;
  2634. APValue &NewVal;
  2635. const Expr *E;
  2636. typedef bool result_type;
  2637. static const AccessKinds AccessKind = AK_Assign;
  2638. bool checkConst(QualType QT) {
  2639. // Assigning to a const object has undefined behavior.
  2640. if (QT.isConstQualified()) {
  2641. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2642. return false;
  2643. }
  2644. return true;
  2645. }
  2646. bool failed() { return false; }
  2647. bool found(APValue &Subobj, QualType SubobjType) {
  2648. if (!checkConst(SubobjType))
  2649. return false;
  2650. // We've been given ownership of NewVal, so just swap it in.
  2651. Subobj.swap(NewVal);
  2652. return true;
  2653. }
  2654. bool found(APSInt &Value, QualType SubobjType) {
  2655. if (!checkConst(SubobjType))
  2656. return false;
  2657. if (!NewVal.isInt()) {
  2658. // Maybe trying to write a cast pointer value into a complex?
  2659. Info.FFDiag(E);
  2660. return false;
  2661. }
  2662. Value = NewVal.getInt();
  2663. return true;
  2664. }
  2665. bool found(APFloat &Value, QualType SubobjType) {
  2666. if (!checkConst(SubobjType))
  2667. return false;
  2668. Value = NewVal.getFloat();
  2669. return true;
  2670. }
  2671. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2672. llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
  2673. }
  2674. };
  2675. } // end anonymous namespace
  2676. const AccessKinds ModifySubobjectHandler::AccessKind;
  2677. /// Update the designated sub-object of an rvalue to the given value.
  2678. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2679. const CompleteObject &Obj,
  2680. const SubobjectDesignator &Sub,
  2681. APValue &NewVal) {
  2682. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2683. return findSubobject(Info, E, Obj, Sub, Handler);
  2684. }
  2685. /// Find the position where two subobject designators diverge, or equivalently
  2686. /// the length of the common initial subsequence.
  2687. static unsigned FindDesignatorMismatch(QualType ObjType,
  2688. const SubobjectDesignator &A,
  2689. const SubobjectDesignator &B,
  2690. bool &WasArrayIndex) {
  2691. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2692. for (/**/; I != N; ++I) {
  2693. if (!ObjType.isNull() &&
  2694. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2695. // Next subobject is an array element.
  2696. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  2697. WasArrayIndex = true;
  2698. return I;
  2699. }
  2700. if (ObjType->isAnyComplexType())
  2701. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2702. else
  2703. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2704. } else {
  2705. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  2706. WasArrayIndex = false;
  2707. return I;
  2708. }
  2709. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2710. // Next subobject is a field.
  2711. ObjType = FD->getType();
  2712. else
  2713. // Next subobject is a base class.
  2714. ObjType = QualType();
  2715. }
  2716. }
  2717. WasArrayIndex = false;
  2718. return I;
  2719. }
  2720. /// Determine whether the given subobject designators refer to elements of the
  2721. /// same array object.
  2722. static bool AreElementsOfSameArray(QualType ObjType,
  2723. const SubobjectDesignator &A,
  2724. const SubobjectDesignator &B) {
  2725. if (A.Entries.size() != B.Entries.size())
  2726. return false;
  2727. bool IsArray = A.MostDerivedIsArrayElement;
  2728. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2729. // A is a subobject of the array element.
  2730. return false;
  2731. // If A (and B) designates an array element, the last entry will be the array
  2732. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2733. // of length 1' case, and the entire path must match.
  2734. bool WasArrayIndex;
  2735. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2736. return CommonLength >= A.Entries.size() - IsArray;
  2737. }
  2738. /// Find the complete object to which an LValue refers.
  2739. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2740. AccessKinds AK, const LValue &LVal,
  2741. QualType LValType) {
  2742. if (!LVal.Base) {
  2743. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2744. return CompleteObject();
  2745. }
  2746. CallStackFrame *Frame = nullptr;
  2747. if (LVal.getLValueCallIndex()) {
  2748. Frame = Info.getCallFrame(LVal.getLValueCallIndex());
  2749. if (!Frame) {
  2750. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2751. << AK << LVal.Base.is<const ValueDecl*>();
  2752. NoteLValueLocation(Info, LVal.Base);
  2753. return CompleteObject();
  2754. }
  2755. }
  2756. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2757. // is not a constant expression (even if the object is non-volatile). We also
  2758. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2759. // semantics.
  2760. if (LValType.isVolatileQualified()) {
  2761. if (Info.getLangOpts().CPlusPlus)
  2762. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2763. << AK << LValType;
  2764. else
  2765. Info.FFDiag(E);
  2766. return CompleteObject();
  2767. }
  2768. // Compute value storage location and type of base object.
  2769. APValue *BaseVal = nullptr;
  2770. QualType BaseType = getType(LVal.Base);
  2771. bool LifetimeStartedInEvaluation = Frame;
  2772. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2773. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2774. // In C++11, constexpr, non-volatile variables initialized with constant
  2775. // expressions are constant expressions too. Inside constexpr functions,
  2776. // parameters are constant expressions even if they're non-const.
  2777. // In C++1y, objects local to a constant expression (those with a Frame) are
  2778. // both readable and writable inside constant expressions.
  2779. // In C, such things can also be folded, although they are not ICEs.
  2780. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2781. if (VD) {
  2782. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2783. VD = VDef;
  2784. }
  2785. if (!VD || VD->isInvalidDecl()) {
  2786. Info.FFDiag(E);
  2787. return CompleteObject();
  2788. }
  2789. // Accesses of volatile-qualified objects are not allowed.
  2790. if (BaseType.isVolatileQualified()) {
  2791. if (Info.getLangOpts().CPlusPlus) {
  2792. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2793. << AK << 1 << VD;
  2794. Info.Note(VD->getLocation(), diag::note_declared_at);
  2795. } else {
  2796. Info.FFDiag(E);
  2797. }
  2798. return CompleteObject();
  2799. }
  2800. // Unless we're looking at a local variable or argument in a constexpr call,
  2801. // the variable we're reading must be const.
  2802. if (!Frame) {
  2803. if (Info.getLangOpts().CPlusPlus14 &&
  2804. VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
  2805. // OK, we can read and modify an object if we're in the process of
  2806. // evaluating its initializer, because its lifetime began in this
  2807. // evaluation.
  2808. } else if (AK != AK_Read) {
  2809. // All the remaining cases only permit reading.
  2810. Info.FFDiag(E, diag::note_constexpr_modify_global);
  2811. return CompleteObject();
  2812. } else if (VD->isConstexpr()) {
  2813. // OK, we can read this variable.
  2814. } else if (BaseType->isIntegralOrEnumerationType()) {
  2815. // In OpenCL if a variable is in constant address space it is a const value.
  2816. if (!(BaseType.isConstQualified() ||
  2817. (Info.getLangOpts().OpenCL &&
  2818. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  2819. if (Info.getLangOpts().CPlusPlus) {
  2820. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2821. Info.Note(VD->getLocation(), diag::note_declared_at);
  2822. } else {
  2823. Info.FFDiag(E);
  2824. }
  2825. return CompleteObject();
  2826. }
  2827. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2828. // We support folding of const floating-point types, in order to make
  2829. // static const data members of such types (supported as an extension)
  2830. // more useful.
  2831. if (Info.getLangOpts().CPlusPlus11) {
  2832. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2833. Info.Note(VD->getLocation(), diag::note_declared_at);
  2834. } else {
  2835. Info.CCEDiag(E);
  2836. }
  2837. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  2838. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  2839. // Keep evaluating to see what we can do.
  2840. } else {
  2841. // FIXME: Allow folding of values of any literal type in all languages.
  2842. if (Info.checkingPotentialConstantExpression() &&
  2843. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  2844. // The definition of this variable could be constexpr. We can't
  2845. // access it right now, but may be able to in future.
  2846. } else if (Info.getLangOpts().CPlusPlus11) {
  2847. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2848. Info.Note(VD->getLocation(), diag::note_declared_at);
  2849. } else {
  2850. Info.FFDiag(E);
  2851. }
  2852. return CompleteObject();
  2853. }
  2854. }
  2855. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  2856. return CompleteObject();
  2857. } else {
  2858. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2859. if (!Frame) {
  2860. if (const MaterializeTemporaryExpr *MTE =
  2861. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  2862. assert(MTE->getStorageDuration() == SD_Static &&
  2863. "should have a frame for a non-global materialized temporary");
  2864. // Per C++1y [expr.const]p2:
  2865. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2866. // - a [...] glvalue of integral or enumeration type that refers to
  2867. // a non-volatile const object [...]
  2868. // [...]
  2869. // - a [...] glvalue of literal type that refers to a non-volatile
  2870. // object whose lifetime began within the evaluation of e.
  2871. //
  2872. // C++11 misses the 'began within the evaluation of e' check and
  2873. // instead allows all temporaries, including things like:
  2874. // int &&r = 1;
  2875. // int x = ++r;
  2876. // constexpr int k = r;
  2877. // Therefore we use the C++14 rules in C++11 too.
  2878. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2879. const ValueDecl *ED = MTE->getExtendingDecl();
  2880. if (!(BaseType.isConstQualified() &&
  2881. BaseType->isIntegralOrEnumerationType()) &&
  2882. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2883. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2884. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2885. return CompleteObject();
  2886. }
  2887. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2888. assert(BaseVal && "got reference to unevaluated temporary");
  2889. LifetimeStartedInEvaluation = true;
  2890. } else {
  2891. Info.FFDiag(E);
  2892. return CompleteObject();
  2893. }
  2894. } else {
  2895. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  2896. assert(BaseVal && "missing value for temporary");
  2897. }
  2898. // Volatile temporary objects cannot be accessed in constant expressions.
  2899. if (BaseType.isVolatileQualified()) {
  2900. if (Info.getLangOpts().CPlusPlus) {
  2901. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2902. << AK << 0;
  2903. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  2904. } else {
  2905. Info.FFDiag(E);
  2906. }
  2907. return CompleteObject();
  2908. }
  2909. }
  2910. // During the construction of an object, it is not yet 'const'.
  2911. // FIXME: This doesn't do quite the right thing for const subobjects of the
  2912. // object under construction.
  2913. if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
  2914. LVal.getLValueCallIndex(),
  2915. LVal.getLValueVersion())) {
  2916. BaseType = Info.Ctx.getCanonicalType(BaseType);
  2917. BaseType.removeLocalConst();
  2918. LifetimeStartedInEvaluation = true;
  2919. }
  2920. // In C++14, we can't safely access any mutable state when we might be
  2921. // evaluating after an unmodeled side effect.
  2922. //
  2923. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2924. // to be read here (but take care with 'mutable' fields).
  2925. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  2926. Info.EvalStatus.HasSideEffects) ||
  2927. (AK != AK_Read && Info.IsSpeculativelyEvaluating))
  2928. return CompleteObject();
  2929. return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
  2930. }
  2931. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2932. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2933. /// glvalue referred to by an entity of reference type.
  2934. ///
  2935. /// \param Info - Information about the ongoing evaluation.
  2936. /// \param Conv - The expression for which we are performing the conversion.
  2937. /// Used for diagnostics.
  2938. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  2939. /// case of a non-class type).
  2940. /// \param LVal - The glvalue on which we are attempting to perform this action.
  2941. /// \param RVal - The produced value will be placed here.
  2942. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2943. QualType Type,
  2944. const LValue &LVal, APValue &RVal) {
  2945. if (LVal.Designator.Invalid)
  2946. return false;
  2947. // Check for special cases where there is no existing APValue to look at.
  2948. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2949. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  2950. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  2951. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  2952. // initializer until now for such expressions. Such an expression can't be
  2953. // an ICE in C, so this only matters for fold.
  2954. if (Type.isVolatileQualified()) {
  2955. Info.FFDiag(Conv);
  2956. return false;
  2957. }
  2958. APValue Lit;
  2959. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  2960. return false;
  2961. CompleteObject LitObj(&Lit, Base->getType(), false);
  2962. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  2963. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  2964. // We represent a string literal array as an lvalue pointing at the
  2965. // corresponding expression, rather than building an array of chars.
  2966. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  2967. APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  2968. CompleteObject StrObj(&Str, Base->getType(), false);
  2969. return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
  2970. }
  2971. }
  2972. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  2973. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  2974. }
  2975. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  2976. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  2977. QualType LValType, APValue &Val) {
  2978. if (LVal.Designator.Invalid)
  2979. return false;
  2980. if (!Info.getLangOpts().CPlusPlus14) {
  2981. Info.FFDiag(E);
  2982. return false;
  2983. }
  2984. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  2985. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  2986. }
  2987. namespace {
  2988. struct CompoundAssignSubobjectHandler {
  2989. EvalInfo &Info;
  2990. const Expr *E;
  2991. QualType PromotedLHSType;
  2992. BinaryOperatorKind Opcode;
  2993. const APValue &RHS;
  2994. static const AccessKinds AccessKind = AK_Assign;
  2995. typedef bool result_type;
  2996. bool checkConst(QualType QT) {
  2997. // Assigning to a const object has undefined behavior.
  2998. if (QT.isConstQualified()) {
  2999. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3000. return false;
  3001. }
  3002. return true;
  3003. }
  3004. bool failed() { return false; }
  3005. bool found(APValue &Subobj, QualType SubobjType) {
  3006. switch (Subobj.getKind()) {
  3007. case APValue::Int:
  3008. return found(Subobj.getInt(), SubobjType);
  3009. case APValue::Float:
  3010. return found(Subobj.getFloat(), SubobjType);
  3011. case APValue::ComplexInt:
  3012. case APValue::ComplexFloat:
  3013. // FIXME: Implement complex compound assignment.
  3014. Info.FFDiag(E);
  3015. return false;
  3016. case APValue::LValue:
  3017. return foundPointer(Subobj, SubobjType);
  3018. default:
  3019. // FIXME: can this happen?
  3020. Info.FFDiag(E);
  3021. return false;
  3022. }
  3023. }
  3024. bool found(APSInt &Value, QualType SubobjType) {
  3025. if (!checkConst(SubobjType))
  3026. return false;
  3027. if (!SubobjType->isIntegerType() || !RHS.isInt()) {
  3028. // We don't support compound assignment on integer-cast-to-pointer
  3029. // values.
  3030. Info.FFDiag(E);
  3031. return false;
  3032. }
  3033. APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
  3034. SubobjType, Value);
  3035. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3036. return false;
  3037. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3038. return true;
  3039. }
  3040. bool found(APFloat &Value, QualType SubobjType) {
  3041. return checkConst(SubobjType) &&
  3042. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3043. Value) &&
  3044. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3045. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3046. }
  3047. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3048. if (!checkConst(SubobjType))
  3049. return false;
  3050. QualType PointeeType;
  3051. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3052. PointeeType = PT->getPointeeType();
  3053. if (PointeeType.isNull() || !RHS.isInt() ||
  3054. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3055. Info.FFDiag(E);
  3056. return false;
  3057. }
  3058. APSInt Offset = RHS.getInt();
  3059. if (Opcode == BO_Sub)
  3060. negateAsSigned(Offset);
  3061. LValue LVal;
  3062. LVal.setFrom(Info.Ctx, Subobj);
  3063. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3064. return false;
  3065. LVal.moveInto(Subobj);
  3066. return true;
  3067. }
  3068. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3069. llvm_unreachable("shouldn't encounter string elements here");
  3070. }
  3071. };
  3072. } // end anonymous namespace
  3073. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3074. /// Perform a compound assignment of LVal <op>= RVal.
  3075. static bool handleCompoundAssignment(
  3076. EvalInfo &Info, const Expr *E,
  3077. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3078. BinaryOperatorKind Opcode, const APValue &RVal) {
  3079. if (LVal.Designator.Invalid)
  3080. return false;
  3081. if (!Info.getLangOpts().CPlusPlus14) {
  3082. Info.FFDiag(E);
  3083. return false;
  3084. }
  3085. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3086. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3087. RVal };
  3088. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3089. }
  3090. namespace {
  3091. struct IncDecSubobjectHandler {
  3092. EvalInfo &Info;
  3093. const UnaryOperator *E;
  3094. AccessKinds AccessKind;
  3095. APValue *Old;
  3096. typedef bool result_type;
  3097. bool checkConst(QualType QT) {
  3098. // Assigning to a const object has undefined behavior.
  3099. if (QT.isConstQualified()) {
  3100. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3101. return false;
  3102. }
  3103. return true;
  3104. }
  3105. bool failed() { return false; }
  3106. bool found(APValue &Subobj, QualType SubobjType) {
  3107. // Stash the old value. Also clear Old, so we don't clobber it later
  3108. // if we're post-incrementing a complex.
  3109. if (Old) {
  3110. *Old = Subobj;
  3111. Old = nullptr;
  3112. }
  3113. switch (Subobj.getKind()) {
  3114. case APValue::Int:
  3115. return found(Subobj.getInt(), SubobjType);
  3116. case APValue::Float:
  3117. return found(Subobj.getFloat(), SubobjType);
  3118. case APValue::ComplexInt:
  3119. return found(Subobj.getComplexIntReal(),
  3120. SubobjType->castAs<ComplexType>()->getElementType()
  3121. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3122. case APValue::ComplexFloat:
  3123. return found(Subobj.getComplexFloatReal(),
  3124. SubobjType->castAs<ComplexType>()->getElementType()
  3125. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3126. case APValue::LValue:
  3127. return foundPointer(Subobj, SubobjType);
  3128. default:
  3129. // FIXME: can this happen?
  3130. Info.FFDiag(E);
  3131. return false;
  3132. }
  3133. }
  3134. bool found(APSInt &Value, QualType SubobjType) {
  3135. if (!checkConst(SubobjType))
  3136. return false;
  3137. if (!SubobjType->isIntegerType()) {
  3138. // We don't support increment / decrement on integer-cast-to-pointer
  3139. // values.
  3140. Info.FFDiag(E);
  3141. return false;
  3142. }
  3143. if (Old) *Old = APValue(Value);
  3144. // bool arithmetic promotes to int, and the conversion back to bool
  3145. // doesn't reduce mod 2^n, so special-case it.
  3146. if (SubobjType->isBooleanType()) {
  3147. if (AccessKind == AK_Increment)
  3148. Value = 1;
  3149. else
  3150. Value = !Value;
  3151. return true;
  3152. }
  3153. bool WasNegative = Value.isNegative();
  3154. if (AccessKind == AK_Increment) {
  3155. ++Value;
  3156. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3157. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3158. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3159. }
  3160. } else {
  3161. --Value;
  3162. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3163. unsigned BitWidth = Value.getBitWidth();
  3164. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3165. ActualValue.setBit(BitWidth);
  3166. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3167. }
  3168. }
  3169. return true;
  3170. }
  3171. bool found(APFloat &Value, QualType SubobjType) {
  3172. if (!checkConst(SubobjType))
  3173. return false;
  3174. if (Old) *Old = APValue(Value);
  3175. APFloat One(Value.getSemantics(), 1);
  3176. if (AccessKind == AK_Increment)
  3177. Value.add(One, APFloat::rmNearestTiesToEven);
  3178. else
  3179. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3180. return true;
  3181. }
  3182. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3183. if (!checkConst(SubobjType))
  3184. return false;
  3185. QualType PointeeType;
  3186. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3187. PointeeType = PT->getPointeeType();
  3188. else {
  3189. Info.FFDiag(E);
  3190. return false;
  3191. }
  3192. LValue LVal;
  3193. LVal.setFrom(Info.Ctx, Subobj);
  3194. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3195. AccessKind == AK_Increment ? 1 : -1))
  3196. return false;
  3197. LVal.moveInto(Subobj);
  3198. return true;
  3199. }
  3200. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3201. llvm_unreachable("shouldn't encounter string elements here");
  3202. }
  3203. };
  3204. } // end anonymous namespace
  3205. /// Perform an increment or decrement on LVal.
  3206. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3207. QualType LValType, bool IsIncrement, APValue *Old) {
  3208. if (LVal.Designator.Invalid)
  3209. return false;
  3210. if (!Info.getLangOpts().CPlusPlus14) {
  3211. Info.FFDiag(E);
  3212. return false;
  3213. }
  3214. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3215. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3216. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3217. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3218. }
  3219. /// Build an lvalue for the object argument of a member function call.
  3220. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3221. LValue &This) {
  3222. if (Object->getType()->isPointerType())
  3223. return EvaluatePointer(Object, This, Info);
  3224. if (Object->isGLValue())
  3225. return EvaluateLValue(Object, This, Info);
  3226. if (Object->getType()->isLiteralType(Info.Ctx))
  3227. return EvaluateTemporary(Object, This, Info);
  3228. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3229. return false;
  3230. }
  3231. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3232. /// lvalue referring to the result.
  3233. ///
  3234. /// \param Info - Information about the ongoing evaluation.
  3235. /// \param LV - An lvalue referring to the base of the member pointer.
  3236. /// \param RHS - The member pointer expression.
  3237. /// \param IncludeMember - Specifies whether the member itself is included in
  3238. /// the resulting LValue subobject designator. This is not possible when
  3239. /// creating a bound member function.
  3240. /// \return The field or method declaration to which the member pointer refers,
  3241. /// or 0 if evaluation fails.
  3242. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3243. QualType LVType,
  3244. LValue &LV,
  3245. const Expr *RHS,
  3246. bool IncludeMember = true) {
  3247. MemberPtr MemPtr;
  3248. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3249. return nullptr;
  3250. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3251. // member value, the behavior is undefined.
  3252. if (!MemPtr.getDecl()) {
  3253. // FIXME: Specific diagnostic.
  3254. Info.FFDiag(RHS);
  3255. return nullptr;
  3256. }
  3257. if (MemPtr.isDerivedMember()) {
  3258. // This is a member of some derived class. Truncate LV appropriately.
  3259. // The end of the derived-to-base path for the base object must match the
  3260. // derived-to-base path for the member pointer.
  3261. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3262. LV.Designator.Entries.size()) {
  3263. Info.FFDiag(RHS);
  3264. return nullptr;
  3265. }
  3266. unsigned PathLengthToMember =
  3267. LV.Designator.Entries.size() - MemPtr.Path.size();
  3268. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3269. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3270. LV.Designator.Entries[PathLengthToMember + I]);
  3271. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3272. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3273. Info.FFDiag(RHS);
  3274. return nullptr;
  3275. }
  3276. }
  3277. // Truncate the lvalue to the appropriate derived class.
  3278. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3279. PathLengthToMember))
  3280. return nullptr;
  3281. } else if (!MemPtr.Path.empty()) {
  3282. // Extend the LValue path with the member pointer's path.
  3283. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3284. MemPtr.Path.size() + IncludeMember);
  3285. // Walk down to the appropriate base class.
  3286. if (const PointerType *PT = LVType->getAs<PointerType>())
  3287. LVType = PT->getPointeeType();
  3288. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3289. assert(RD && "member pointer access on non-class-type expression");
  3290. // The first class in the path is that of the lvalue.
  3291. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3292. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3293. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3294. return nullptr;
  3295. RD = Base;
  3296. }
  3297. // Finally cast to the class containing the member.
  3298. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3299. MemPtr.getContainingRecord()))
  3300. return nullptr;
  3301. }
  3302. // Add the member. Note that we cannot build bound member functions here.
  3303. if (IncludeMember) {
  3304. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3305. if (!HandleLValueMember(Info, RHS, LV, FD))
  3306. return nullptr;
  3307. } else if (const IndirectFieldDecl *IFD =
  3308. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3309. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3310. return nullptr;
  3311. } else {
  3312. llvm_unreachable("can't construct reference to bound member function");
  3313. }
  3314. }
  3315. return MemPtr.getDecl();
  3316. }
  3317. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3318. const BinaryOperator *BO,
  3319. LValue &LV,
  3320. bool IncludeMember = true) {
  3321. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3322. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3323. if (Info.noteFailure()) {
  3324. MemberPtr MemPtr;
  3325. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3326. }
  3327. return nullptr;
  3328. }
  3329. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3330. BO->getRHS(), IncludeMember);
  3331. }
  3332. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3333. /// the provided lvalue, which currently refers to the base object.
  3334. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3335. LValue &Result) {
  3336. SubobjectDesignator &D = Result.Designator;
  3337. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3338. return false;
  3339. QualType TargetQT = E->getType();
  3340. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3341. TargetQT = PT->getPointeeType();
  3342. // Check this cast lands within the final derived-to-base subobject path.
  3343. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3344. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3345. << D.MostDerivedType << TargetQT;
  3346. return false;
  3347. }
  3348. // Check the type of the final cast. We don't need to check the path,
  3349. // since a cast can only be formed if the path is unique.
  3350. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3351. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3352. const CXXRecordDecl *FinalType;
  3353. if (NewEntriesSize == D.MostDerivedPathLength)
  3354. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3355. else
  3356. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3357. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3358. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3359. << D.MostDerivedType << TargetQT;
  3360. return false;
  3361. }
  3362. // Truncate the lvalue to the appropriate derived class.
  3363. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3364. }
  3365. namespace {
  3366. enum EvalStmtResult {
  3367. /// Evaluation failed.
  3368. ESR_Failed,
  3369. /// Hit a 'return' statement.
  3370. ESR_Returned,
  3371. /// Evaluation succeeded.
  3372. ESR_Succeeded,
  3373. /// Hit a 'continue' statement.
  3374. ESR_Continue,
  3375. /// Hit a 'break' statement.
  3376. ESR_Break,
  3377. /// Still scanning for 'case' or 'default' statement.
  3378. ESR_CaseNotFound
  3379. };
  3380. }
  3381. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3382. // We don't need to evaluate the initializer for a static local.
  3383. if (!VD->hasLocalStorage())
  3384. return true;
  3385. LValue Result;
  3386. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3387. const Expr *InitE = VD->getInit();
  3388. if (!InitE) {
  3389. Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
  3390. << false << VD->getType();
  3391. Val = APValue();
  3392. return false;
  3393. }
  3394. if (InitE->isValueDependent())
  3395. return false;
  3396. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3397. // Wipe out any partially-computed value, to allow tracking that this
  3398. // evaluation failed.
  3399. Val = APValue();
  3400. return false;
  3401. }
  3402. return true;
  3403. }
  3404. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3405. bool OK = true;
  3406. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3407. OK &= EvaluateVarDecl(Info, VD);
  3408. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3409. for (auto *BD : DD->bindings())
  3410. if (auto *VD = BD->getHoldingVar())
  3411. OK &= EvaluateDecl(Info, VD);
  3412. return OK;
  3413. }
  3414. /// Evaluate a condition (either a variable declaration or an expression).
  3415. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3416. const Expr *Cond, bool &Result) {
  3417. FullExpressionRAII Scope(Info);
  3418. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3419. return false;
  3420. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3421. }
  3422. namespace {
  3423. /// A location where the result (returned value) of evaluating a
  3424. /// statement should be stored.
  3425. struct StmtResult {
  3426. /// The APValue that should be filled in with the returned value.
  3427. APValue &Value;
  3428. /// The location containing the result, if any (used to support RVO).
  3429. const LValue *Slot;
  3430. };
  3431. struct TempVersionRAII {
  3432. CallStackFrame &Frame;
  3433. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3434. Frame.pushTempVersion();
  3435. }
  3436. ~TempVersionRAII() {
  3437. Frame.popTempVersion();
  3438. }
  3439. };
  3440. }
  3441. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3442. const Stmt *S,
  3443. const SwitchCase *SC = nullptr);
  3444. /// Evaluate the body of a loop, and translate the result as appropriate.
  3445. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3446. const Stmt *Body,
  3447. const SwitchCase *Case = nullptr) {
  3448. BlockScopeRAII Scope(Info);
  3449. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3450. case ESR_Break:
  3451. return ESR_Succeeded;
  3452. case ESR_Succeeded:
  3453. case ESR_Continue:
  3454. return ESR_Continue;
  3455. case ESR_Failed:
  3456. case ESR_Returned:
  3457. case ESR_CaseNotFound:
  3458. return ESR;
  3459. }
  3460. llvm_unreachable("Invalid EvalStmtResult!");
  3461. }
  3462. /// Evaluate a switch statement.
  3463. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3464. const SwitchStmt *SS) {
  3465. BlockScopeRAII Scope(Info);
  3466. // Evaluate the switch condition.
  3467. APSInt Value;
  3468. {
  3469. FullExpressionRAII Scope(Info);
  3470. if (const Stmt *Init = SS->getInit()) {
  3471. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3472. if (ESR != ESR_Succeeded)
  3473. return ESR;
  3474. }
  3475. if (SS->getConditionVariable() &&
  3476. !EvaluateDecl(Info, SS->getConditionVariable()))
  3477. return ESR_Failed;
  3478. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3479. return ESR_Failed;
  3480. }
  3481. // Find the switch case corresponding to the value of the condition.
  3482. // FIXME: Cache this lookup.
  3483. const SwitchCase *Found = nullptr;
  3484. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3485. SC = SC->getNextSwitchCase()) {
  3486. if (isa<DefaultStmt>(SC)) {
  3487. Found = SC;
  3488. continue;
  3489. }
  3490. const CaseStmt *CS = cast<CaseStmt>(SC);
  3491. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3492. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3493. : LHS;
  3494. if (LHS <= Value && Value <= RHS) {
  3495. Found = SC;
  3496. break;
  3497. }
  3498. }
  3499. if (!Found)
  3500. return ESR_Succeeded;
  3501. // Search the switch body for the switch case and evaluate it from there.
  3502. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3503. case ESR_Break:
  3504. return ESR_Succeeded;
  3505. case ESR_Succeeded:
  3506. case ESR_Continue:
  3507. case ESR_Failed:
  3508. case ESR_Returned:
  3509. return ESR;
  3510. case ESR_CaseNotFound:
  3511. // This can only happen if the switch case is nested within a statement
  3512. // expression. We have no intention of supporting that.
  3513. Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
  3514. return ESR_Failed;
  3515. }
  3516. llvm_unreachable("Invalid EvalStmtResult!");
  3517. }
  3518. // Evaluate a statement.
  3519. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3520. const Stmt *S, const SwitchCase *Case) {
  3521. if (!Info.nextStep(S))
  3522. return ESR_Failed;
  3523. // If we're hunting down a 'case' or 'default' label, recurse through
  3524. // substatements until we hit the label.
  3525. if (Case) {
  3526. // FIXME: We don't start the lifetime of objects whose initialization we
  3527. // jump over. However, such objects must be of class type with a trivial
  3528. // default constructor that initialize all subobjects, so must be empty,
  3529. // so this almost never matters.
  3530. switch (S->getStmtClass()) {
  3531. case Stmt::CompoundStmtClass:
  3532. // FIXME: Precompute which substatement of a compound statement we
  3533. // would jump to, and go straight there rather than performing a
  3534. // linear scan each time.
  3535. case Stmt::LabelStmtClass:
  3536. case Stmt::AttributedStmtClass:
  3537. case Stmt::DoStmtClass:
  3538. break;
  3539. case Stmt::CaseStmtClass:
  3540. case Stmt::DefaultStmtClass:
  3541. if (Case == S)
  3542. Case = nullptr;
  3543. break;
  3544. case Stmt::IfStmtClass: {
  3545. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3546. // straight there rather than scanning both sides.
  3547. const IfStmt *IS = cast<IfStmt>(S);
  3548. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3549. // preceded by our switch label.
  3550. BlockScopeRAII Scope(Info);
  3551. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3552. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3553. return ESR;
  3554. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3555. }
  3556. case Stmt::WhileStmtClass: {
  3557. EvalStmtResult ESR =
  3558. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3559. if (ESR != ESR_Continue)
  3560. return ESR;
  3561. break;
  3562. }
  3563. case Stmt::ForStmtClass: {
  3564. const ForStmt *FS = cast<ForStmt>(S);
  3565. EvalStmtResult ESR =
  3566. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3567. if (ESR != ESR_Continue)
  3568. return ESR;
  3569. if (FS->getInc()) {
  3570. FullExpressionRAII IncScope(Info);
  3571. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3572. return ESR_Failed;
  3573. }
  3574. break;
  3575. }
  3576. case Stmt::DeclStmtClass:
  3577. // FIXME: If the variable has initialization that can't be jumped over,
  3578. // bail out of any immediately-surrounding compound-statement too.
  3579. default:
  3580. return ESR_CaseNotFound;
  3581. }
  3582. }
  3583. switch (S->getStmtClass()) {
  3584. default:
  3585. if (const Expr *E = dyn_cast<Expr>(S)) {
  3586. // Don't bother evaluating beyond an expression-statement which couldn't
  3587. // be evaluated.
  3588. FullExpressionRAII Scope(Info);
  3589. if (!EvaluateIgnoredValue(Info, E))
  3590. return ESR_Failed;
  3591. return ESR_Succeeded;
  3592. }
  3593. Info.FFDiag(S->getLocStart());
  3594. return ESR_Failed;
  3595. case Stmt::NullStmtClass:
  3596. return ESR_Succeeded;
  3597. case Stmt::DeclStmtClass: {
  3598. const DeclStmt *DS = cast<DeclStmt>(S);
  3599. for (const auto *DclIt : DS->decls()) {
  3600. // Each declaration initialization is its own full-expression.
  3601. // FIXME: This isn't quite right; if we're performing aggregate
  3602. // initialization, each braced subexpression is its own full-expression.
  3603. FullExpressionRAII Scope(Info);
  3604. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3605. return ESR_Failed;
  3606. }
  3607. return ESR_Succeeded;
  3608. }
  3609. case Stmt::ReturnStmtClass: {
  3610. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3611. FullExpressionRAII Scope(Info);
  3612. if (RetExpr &&
  3613. !(Result.Slot
  3614. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3615. : Evaluate(Result.Value, Info, RetExpr)))
  3616. return ESR_Failed;
  3617. return ESR_Returned;
  3618. }
  3619. case Stmt::CompoundStmtClass: {
  3620. BlockScopeRAII Scope(Info);
  3621. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3622. for (const auto *BI : CS->body()) {
  3623. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3624. if (ESR == ESR_Succeeded)
  3625. Case = nullptr;
  3626. else if (ESR != ESR_CaseNotFound)
  3627. return ESR;
  3628. }
  3629. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3630. }
  3631. case Stmt::IfStmtClass: {
  3632. const IfStmt *IS = cast<IfStmt>(S);
  3633. // Evaluate the condition, as either a var decl or as an expression.
  3634. BlockScopeRAII Scope(Info);
  3635. if (const Stmt *Init = IS->getInit()) {
  3636. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3637. if (ESR != ESR_Succeeded)
  3638. return ESR;
  3639. }
  3640. bool Cond;
  3641. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3642. return ESR_Failed;
  3643. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3644. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3645. if (ESR != ESR_Succeeded)
  3646. return ESR;
  3647. }
  3648. return ESR_Succeeded;
  3649. }
  3650. case Stmt::WhileStmtClass: {
  3651. const WhileStmt *WS = cast<WhileStmt>(S);
  3652. while (true) {
  3653. BlockScopeRAII Scope(Info);
  3654. bool Continue;
  3655. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3656. Continue))
  3657. return ESR_Failed;
  3658. if (!Continue)
  3659. break;
  3660. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3661. if (ESR != ESR_Continue)
  3662. return ESR;
  3663. }
  3664. return ESR_Succeeded;
  3665. }
  3666. case Stmt::DoStmtClass: {
  3667. const DoStmt *DS = cast<DoStmt>(S);
  3668. bool Continue;
  3669. do {
  3670. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3671. if (ESR != ESR_Continue)
  3672. return ESR;
  3673. Case = nullptr;
  3674. FullExpressionRAII CondScope(Info);
  3675. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3676. return ESR_Failed;
  3677. } while (Continue);
  3678. return ESR_Succeeded;
  3679. }
  3680. case Stmt::ForStmtClass: {
  3681. const ForStmt *FS = cast<ForStmt>(S);
  3682. BlockScopeRAII Scope(Info);
  3683. if (FS->getInit()) {
  3684. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3685. if (ESR != ESR_Succeeded)
  3686. return ESR;
  3687. }
  3688. while (true) {
  3689. BlockScopeRAII Scope(Info);
  3690. bool Continue = true;
  3691. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3692. FS->getCond(), Continue))
  3693. return ESR_Failed;
  3694. if (!Continue)
  3695. break;
  3696. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3697. if (ESR != ESR_Continue)
  3698. return ESR;
  3699. if (FS->getInc()) {
  3700. FullExpressionRAII IncScope(Info);
  3701. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3702. return ESR_Failed;
  3703. }
  3704. }
  3705. return ESR_Succeeded;
  3706. }
  3707. case Stmt::CXXForRangeStmtClass: {
  3708. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3709. BlockScopeRAII Scope(Info);
  3710. // Initialize the __range variable.
  3711. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3712. if (ESR != ESR_Succeeded)
  3713. return ESR;
  3714. // Create the __begin and __end iterators.
  3715. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3716. if (ESR != ESR_Succeeded)
  3717. return ESR;
  3718. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3719. if (ESR != ESR_Succeeded)
  3720. return ESR;
  3721. while (true) {
  3722. // Condition: __begin != __end.
  3723. {
  3724. bool Continue = true;
  3725. FullExpressionRAII CondExpr(Info);
  3726. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3727. return ESR_Failed;
  3728. if (!Continue)
  3729. break;
  3730. }
  3731. // User's variable declaration, initialized by *__begin.
  3732. BlockScopeRAII InnerScope(Info);
  3733. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3734. if (ESR != ESR_Succeeded)
  3735. return ESR;
  3736. // Loop body.
  3737. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3738. if (ESR != ESR_Continue)
  3739. return ESR;
  3740. // Increment: ++__begin
  3741. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3742. return ESR_Failed;
  3743. }
  3744. return ESR_Succeeded;
  3745. }
  3746. case Stmt::SwitchStmtClass:
  3747. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3748. case Stmt::ContinueStmtClass:
  3749. return ESR_Continue;
  3750. case Stmt::BreakStmtClass:
  3751. return ESR_Break;
  3752. case Stmt::LabelStmtClass:
  3753. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3754. case Stmt::AttributedStmtClass:
  3755. // As a general principle, C++11 attributes can be ignored without
  3756. // any semantic impact.
  3757. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3758. Case);
  3759. case Stmt::CaseStmtClass:
  3760. case Stmt::DefaultStmtClass:
  3761. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3762. }
  3763. }
  3764. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3765. /// default constructor. If so, we'll fold it whether or not it's marked as
  3766. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3767. /// so we need special handling.
  3768. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3769. const CXXConstructorDecl *CD,
  3770. bool IsValueInitialization) {
  3771. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3772. return false;
  3773. // Value-initialization does not call a trivial default constructor, so such a
  3774. // call is a core constant expression whether or not the constructor is
  3775. // constexpr.
  3776. if (!CD->isConstexpr() && !IsValueInitialization) {
  3777. if (Info.getLangOpts().CPlusPlus11) {
  3778. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3779. // we should be much more explicit about why it's not constexpr.
  3780. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3781. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3782. Info.Note(CD->getLocation(), diag::note_declared_at);
  3783. } else {
  3784. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3785. }
  3786. }
  3787. return true;
  3788. }
  3789. /// CheckConstexprFunction - Check that a function can be called in a constant
  3790. /// expression.
  3791. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3792. const FunctionDecl *Declaration,
  3793. const FunctionDecl *Definition,
  3794. const Stmt *Body) {
  3795. // Potential constant expressions can contain calls to declared, but not yet
  3796. // defined, constexpr functions.
  3797. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3798. Declaration->isConstexpr())
  3799. return false;
  3800. // Bail out with no diagnostic if the function declaration itself is invalid.
  3801. // We will have produced a relevant diagnostic while parsing it.
  3802. if (Declaration->isInvalidDecl())
  3803. return false;
  3804. // Can we evaluate this function call?
  3805. if (Definition && Definition->isConstexpr() &&
  3806. !Definition->isInvalidDecl() && Body)
  3807. return true;
  3808. if (Info.getLangOpts().CPlusPlus11) {
  3809. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3810. // If this function is not constexpr because it is an inherited
  3811. // non-constexpr constructor, diagnose that directly.
  3812. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  3813. if (CD && CD->isInheritingConstructor()) {
  3814. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  3815. if (!Inherited->isConstexpr())
  3816. DiagDecl = CD = Inherited;
  3817. }
  3818. // FIXME: If DiagDecl is an implicitly-declared special member function
  3819. // or an inheriting constructor, we should be much more explicit about why
  3820. // it's not constexpr.
  3821. if (CD && CD->isInheritingConstructor())
  3822. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  3823. << CD->getInheritedConstructor().getConstructor()->getParent();
  3824. else
  3825. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3826. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  3827. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3828. } else {
  3829. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3830. }
  3831. return false;
  3832. }
  3833. /// Determine if a class has any fields that might need to be copied by a
  3834. /// trivial copy or move operation.
  3835. static bool hasFields(const CXXRecordDecl *RD) {
  3836. if (!RD || RD->isEmpty())
  3837. return false;
  3838. for (auto *FD : RD->fields()) {
  3839. if (FD->isUnnamedBitfield())
  3840. continue;
  3841. return true;
  3842. }
  3843. for (auto &Base : RD->bases())
  3844. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  3845. return true;
  3846. return false;
  3847. }
  3848. namespace {
  3849. typedef SmallVector<APValue, 8> ArgVector;
  3850. }
  3851. /// EvaluateArgs - Evaluate the arguments to a function call.
  3852. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  3853. EvalInfo &Info) {
  3854. bool Success = true;
  3855. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  3856. I != E; ++I) {
  3857. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  3858. // If we're checking for a potential constant expression, evaluate all
  3859. // initializers even if some of them fail.
  3860. if (!Info.noteFailure())
  3861. return false;
  3862. Success = false;
  3863. }
  3864. }
  3865. return Success;
  3866. }
  3867. /// Evaluate a function call.
  3868. static bool HandleFunctionCall(SourceLocation CallLoc,
  3869. const FunctionDecl *Callee, const LValue *This,
  3870. ArrayRef<const Expr*> Args, const Stmt *Body,
  3871. EvalInfo &Info, APValue &Result,
  3872. const LValue *ResultSlot) {
  3873. ArgVector ArgValues(Args.size());
  3874. if (!EvaluateArgs(Args, ArgValues, Info))
  3875. return false;
  3876. if (!Info.CheckCallLimit(CallLoc))
  3877. return false;
  3878. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  3879. // For a trivial copy or move assignment, perform an APValue copy. This is
  3880. // essential for unions, where the operations performed by the assignment
  3881. // operator cannot be represented as statements.
  3882. //
  3883. // Skip this for non-union classes with no fields; in that case, the defaulted
  3884. // copy/move does not actually read the object.
  3885. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  3886. if (MD && MD->isDefaulted() &&
  3887. (MD->getParent()->isUnion() ||
  3888. (MD->isTrivial() && hasFields(MD->getParent())))) {
  3889. assert(This &&
  3890. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  3891. LValue RHS;
  3892. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3893. APValue RHSValue;
  3894. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3895. RHS, RHSValue))
  3896. return false;
  3897. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
  3898. RHSValue))
  3899. return false;
  3900. This->moveInto(Result);
  3901. return true;
  3902. } else if (MD && isLambdaCallOperator(MD)) {
  3903. // We're in a lambda; determine the lambda capture field maps unless we're
  3904. // just constexpr checking a lambda's call operator. constexpr checking is
  3905. // done before the captures have been added to the closure object (unless
  3906. // we're inferring constexpr-ness), so we don't have access to them in this
  3907. // case. But since we don't need the captures to constexpr check, we can
  3908. // just ignore them.
  3909. if (!Info.checkingPotentialConstantExpression())
  3910. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  3911. Frame.LambdaThisCaptureField);
  3912. }
  3913. StmtResult Ret = {Result, ResultSlot};
  3914. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  3915. if (ESR == ESR_Succeeded) {
  3916. if (Callee->getReturnType()->isVoidType())
  3917. return true;
  3918. Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
  3919. }
  3920. return ESR == ESR_Returned;
  3921. }
  3922. /// Evaluate a constructor call.
  3923. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  3924. APValue *ArgValues,
  3925. const CXXConstructorDecl *Definition,
  3926. EvalInfo &Info, APValue &Result) {
  3927. SourceLocation CallLoc = E->getExprLoc();
  3928. if (!Info.CheckCallLimit(CallLoc))
  3929. return false;
  3930. const CXXRecordDecl *RD = Definition->getParent();
  3931. if (RD->getNumVBases()) {
  3932. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  3933. return false;
  3934. }
  3935. EvalInfo::EvaluatingConstructorRAII EvalObj(
  3936. Info, {This.getLValueBase(),
  3937. {This.getLValueCallIndex(), This.getLValueVersion()}});
  3938. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  3939. // FIXME: Creating an APValue just to hold a nonexistent return value is
  3940. // wasteful.
  3941. APValue RetVal;
  3942. StmtResult Ret = {RetVal, nullptr};
  3943. // If it's a delegating constructor, delegate.
  3944. if (Definition->isDelegatingConstructor()) {
  3945. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  3946. {
  3947. FullExpressionRAII InitScope(Info);
  3948. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  3949. return false;
  3950. }
  3951. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  3952. }
  3953. // For a trivial copy or move constructor, perform an APValue copy. This is
  3954. // essential for unions (or classes with anonymous union members), where the
  3955. // operations performed by the constructor cannot be represented by
  3956. // ctor-initializers.
  3957. //
  3958. // Skip this for empty non-union classes; we should not perform an
  3959. // lvalue-to-rvalue conversion on them because their copy constructor does not
  3960. // actually read them.
  3961. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  3962. (Definition->getParent()->isUnion() ||
  3963. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  3964. LValue RHS;
  3965. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3966. return handleLValueToRValueConversion(
  3967. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  3968. RHS, Result);
  3969. }
  3970. // Reserve space for the struct members.
  3971. if (!RD->isUnion() && Result.isUninit())
  3972. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  3973. std::distance(RD->field_begin(), RD->field_end()));
  3974. if (RD->isInvalidDecl()) return false;
  3975. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  3976. // A scope for temporaries lifetime-extended by reference members.
  3977. BlockScopeRAII LifetimeExtendedScope(Info);
  3978. bool Success = true;
  3979. unsigned BasesSeen = 0;
  3980. #ifndef NDEBUG
  3981. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  3982. #endif
  3983. for (const auto *I : Definition->inits()) {
  3984. LValue Subobject = This;
  3985. LValue SubobjectParent = This;
  3986. APValue *Value = &Result;
  3987. // Determine the subobject to initialize.
  3988. FieldDecl *FD = nullptr;
  3989. if (I->isBaseInitializer()) {
  3990. QualType BaseType(I->getBaseClass(), 0);
  3991. #ifndef NDEBUG
  3992. // Non-virtual base classes are initialized in the order in the class
  3993. // definition. We have already checked for virtual base classes.
  3994. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  3995. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  3996. "base class initializers not in expected order");
  3997. ++BaseIt;
  3998. #endif
  3999. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4000. BaseType->getAsCXXRecordDecl(), &Layout))
  4001. return false;
  4002. Value = &Result.getStructBase(BasesSeen++);
  4003. } else if ((FD = I->getMember())) {
  4004. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4005. return false;
  4006. if (RD->isUnion()) {
  4007. Result = APValue(FD);
  4008. Value = &Result.getUnionValue();
  4009. } else {
  4010. Value = &Result.getStructField(FD->getFieldIndex());
  4011. }
  4012. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4013. // Walk the indirect field decl's chain to find the object to initialize,
  4014. // and make sure we've initialized every step along it.
  4015. auto IndirectFieldChain = IFD->chain();
  4016. for (auto *C : IndirectFieldChain) {
  4017. FD = cast<FieldDecl>(C);
  4018. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4019. // Switch the union field if it differs. This happens if we had
  4020. // preceding zero-initialization, and we're now initializing a union
  4021. // subobject other than the first.
  4022. // FIXME: In this case, the values of the other subobjects are
  4023. // specified, since zero-initialization sets all padding bits to zero.
  4024. if (Value->isUninit() ||
  4025. (Value->isUnion() && Value->getUnionField() != FD)) {
  4026. if (CD->isUnion())
  4027. *Value = APValue(FD);
  4028. else
  4029. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4030. std::distance(CD->field_begin(), CD->field_end()));
  4031. }
  4032. // Store Subobject as its parent before updating it for the last element
  4033. // in the chain.
  4034. if (C == IndirectFieldChain.back())
  4035. SubobjectParent = Subobject;
  4036. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4037. return false;
  4038. if (CD->isUnion())
  4039. Value = &Value->getUnionValue();
  4040. else
  4041. Value = &Value->getStructField(FD->getFieldIndex());
  4042. }
  4043. } else {
  4044. llvm_unreachable("unknown base initializer kind");
  4045. }
  4046. // Need to override This for implicit field initializers as in this case
  4047. // This refers to innermost anonymous struct/union containing initializer,
  4048. // not to currently constructed class.
  4049. const Expr *Init = I->getInit();
  4050. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4051. isa<CXXDefaultInitExpr>(Init));
  4052. FullExpressionRAII InitScope(Info);
  4053. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4054. (FD && FD->isBitField() &&
  4055. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4056. // If we're checking for a potential constant expression, evaluate all
  4057. // initializers even if some of them fail.
  4058. if (!Info.noteFailure())
  4059. return false;
  4060. Success = false;
  4061. }
  4062. }
  4063. return Success &&
  4064. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4065. }
  4066. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4067. ArrayRef<const Expr*> Args,
  4068. const CXXConstructorDecl *Definition,
  4069. EvalInfo &Info, APValue &Result) {
  4070. ArgVector ArgValues(Args.size());
  4071. if (!EvaluateArgs(Args, ArgValues, Info))
  4072. return false;
  4073. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4074. Info, Result);
  4075. }
  4076. //===----------------------------------------------------------------------===//
  4077. // Generic Evaluation
  4078. //===----------------------------------------------------------------------===//
  4079. namespace {
  4080. template <class Derived>
  4081. class ExprEvaluatorBase
  4082. : public ConstStmtVisitor<Derived, bool> {
  4083. private:
  4084. Derived &getDerived() { return static_cast<Derived&>(*this); }
  4085. bool DerivedSuccess(const APValue &V, const Expr *E) {
  4086. return getDerived().Success(V, E);
  4087. }
  4088. bool DerivedZeroInitialization(const Expr *E) {
  4089. return getDerived().ZeroInitialization(E);
  4090. }
  4091. // Check whether a conditional operator with a non-constant condition is a
  4092. // potential constant expression. If neither arm is a potential constant
  4093. // expression, then the conditional operator is not either.
  4094. template<typename ConditionalOperator>
  4095. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  4096. assert(Info.checkingPotentialConstantExpression());
  4097. // Speculatively evaluate both arms.
  4098. SmallVector<PartialDiagnosticAt, 8> Diag;
  4099. {
  4100. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4101. StmtVisitorTy::Visit(E->getFalseExpr());
  4102. if (Diag.empty())
  4103. return;
  4104. }
  4105. {
  4106. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4107. Diag.clear();
  4108. StmtVisitorTy::Visit(E->getTrueExpr());
  4109. if (Diag.empty())
  4110. return;
  4111. }
  4112. Error(E, diag::note_constexpr_conditional_never_const);
  4113. }
  4114. template<typename ConditionalOperator>
  4115. bool HandleConditionalOperator(const ConditionalOperator *E) {
  4116. bool BoolResult;
  4117. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  4118. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  4119. CheckPotentialConstantConditional(E);
  4120. return false;
  4121. }
  4122. if (Info.noteFailure()) {
  4123. StmtVisitorTy::Visit(E->getTrueExpr());
  4124. StmtVisitorTy::Visit(E->getFalseExpr());
  4125. }
  4126. return false;
  4127. }
  4128. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  4129. return StmtVisitorTy::Visit(EvalExpr);
  4130. }
  4131. protected:
  4132. EvalInfo &Info;
  4133. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  4134. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  4135. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  4136. return Info.CCEDiag(E, D);
  4137. }
  4138. bool ZeroInitialization(const Expr *E) { return Error(E); }
  4139. public:
  4140. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  4141. EvalInfo &getEvalInfo() { return Info; }
  4142. /// Report an evaluation error. This should only be called when an error is
  4143. /// first discovered. When propagating an error, just return false.
  4144. bool Error(const Expr *E, diag::kind D) {
  4145. Info.FFDiag(E, D);
  4146. return false;
  4147. }
  4148. bool Error(const Expr *E) {
  4149. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  4150. }
  4151. bool VisitStmt(const Stmt *) {
  4152. llvm_unreachable("Expression evaluator should not be called on stmts");
  4153. }
  4154. bool VisitExpr(const Expr *E) {
  4155. return Error(E);
  4156. }
  4157. bool VisitParenExpr(const ParenExpr *E)
  4158. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4159. bool VisitUnaryExtension(const UnaryOperator *E)
  4160. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4161. bool VisitUnaryPlus(const UnaryOperator *E)
  4162. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4163. bool VisitChooseExpr(const ChooseExpr *E)
  4164. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  4165. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  4166. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  4167. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  4168. { return StmtVisitorTy::Visit(E->getReplacement()); }
  4169. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  4170. TempVersionRAII RAII(*Info.CurrentCall);
  4171. return StmtVisitorTy::Visit(E->getExpr());
  4172. }
  4173. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  4174. TempVersionRAII RAII(*Info.CurrentCall);
  4175. // The initializer may not have been parsed yet, or might be erroneous.
  4176. if (!E->getExpr())
  4177. return Error(E);
  4178. return StmtVisitorTy::Visit(E->getExpr());
  4179. }
  4180. // We cannot create any objects for which cleanups are required, so there is
  4181. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  4182. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  4183. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4184. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  4185. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  4186. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4187. }
  4188. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  4189. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  4190. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4191. }
  4192. bool VisitBinaryOperator(const BinaryOperator *E) {
  4193. switch (E->getOpcode()) {
  4194. default:
  4195. return Error(E);
  4196. case BO_Comma:
  4197. VisitIgnoredValue(E->getLHS());
  4198. return StmtVisitorTy::Visit(E->getRHS());
  4199. case BO_PtrMemD:
  4200. case BO_PtrMemI: {
  4201. LValue Obj;
  4202. if (!HandleMemberPointerAccess(Info, E, Obj))
  4203. return false;
  4204. APValue Result;
  4205. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  4206. return false;
  4207. return DerivedSuccess(Result, E);
  4208. }
  4209. }
  4210. }
  4211. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  4212. // Evaluate and cache the common expression. We treat it as a temporary,
  4213. // even though it's not quite the same thing.
  4214. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  4215. Info, E->getCommon()))
  4216. return false;
  4217. return HandleConditionalOperator(E);
  4218. }
  4219. bool VisitConditionalOperator(const ConditionalOperator *E) {
  4220. bool IsBcpCall = false;
  4221. // If the condition (ignoring parens) is a __builtin_constant_p call,
  4222. // the result is a constant expression if it can be folded without
  4223. // side-effects. This is an important GNU extension. See GCC PR38377
  4224. // for discussion.
  4225. if (const CallExpr *CallCE =
  4226. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  4227. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  4228. IsBcpCall = true;
  4229. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  4230. // constant expression; we can't check whether it's potentially foldable.
  4231. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  4232. return false;
  4233. FoldConstant Fold(Info, IsBcpCall);
  4234. if (!HandleConditionalOperator(E)) {
  4235. Fold.keepDiagnostics();
  4236. return false;
  4237. }
  4238. return true;
  4239. }
  4240. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  4241. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  4242. return DerivedSuccess(*Value, E);
  4243. const Expr *Source = E->getSourceExpr();
  4244. if (!Source)
  4245. return Error(E);
  4246. if (Source == E) { // sanity checking.
  4247. assert(0 && "OpaqueValueExpr recursively refers to itself");
  4248. return Error(E);
  4249. }
  4250. return StmtVisitorTy::Visit(Source);
  4251. }
  4252. bool VisitCallExpr(const CallExpr *E) {
  4253. APValue Result;
  4254. if (!handleCallExpr(E, Result, nullptr))
  4255. return false;
  4256. return DerivedSuccess(Result, E);
  4257. }
  4258. bool handleCallExpr(const CallExpr *E, APValue &Result,
  4259. const LValue *ResultSlot) {
  4260. const Expr *Callee = E->getCallee()->IgnoreParens();
  4261. QualType CalleeType = Callee->getType();
  4262. const FunctionDecl *FD = nullptr;
  4263. LValue *This = nullptr, ThisVal;
  4264. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4265. bool HasQualifier = false;
  4266. // Extract function decl and 'this' pointer from the callee.
  4267. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  4268. const ValueDecl *Member = nullptr;
  4269. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  4270. // Explicit bound member calls, such as x.f() or p->g();
  4271. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  4272. return false;
  4273. Member = ME->getMemberDecl();
  4274. This = &ThisVal;
  4275. HasQualifier = ME->hasQualifier();
  4276. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  4277. // Indirect bound member calls ('.*' or '->*').
  4278. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  4279. if (!Member) return false;
  4280. This = &ThisVal;
  4281. } else
  4282. return Error(Callee);
  4283. FD = dyn_cast<FunctionDecl>(Member);
  4284. if (!FD)
  4285. return Error(Callee);
  4286. } else if (CalleeType->isFunctionPointerType()) {
  4287. LValue Call;
  4288. if (!EvaluatePointer(Callee, Call, Info))
  4289. return false;
  4290. if (!Call.getLValueOffset().isZero())
  4291. return Error(Callee);
  4292. FD = dyn_cast_or_null<FunctionDecl>(
  4293. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  4294. if (!FD)
  4295. return Error(Callee);
  4296. // Don't call function pointers which have been cast to some other type.
  4297. // Per DR (no number yet), the caller and callee can differ in noexcept.
  4298. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  4299. CalleeType->getPointeeType(), FD->getType())) {
  4300. return Error(E);
  4301. }
  4302. // Overloaded operator calls to member functions are represented as normal
  4303. // calls with '*this' as the first argument.
  4304. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  4305. if (MD && !MD->isStatic()) {
  4306. // FIXME: When selecting an implicit conversion for an overloaded
  4307. // operator delete, we sometimes try to evaluate calls to conversion
  4308. // operators without a 'this' parameter!
  4309. if (Args.empty())
  4310. return Error(E);
  4311. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  4312. return false;
  4313. This = &ThisVal;
  4314. Args = Args.slice(1);
  4315. } else if (MD && MD->isLambdaStaticInvoker()) {
  4316. // Map the static invoker for the lambda back to the call operator.
  4317. // Conveniently, we don't have to slice out the 'this' argument (as is
  4318. // being done for the non-static case), since a static member function
  4319. // doesn't have an implicit argument passed in.
  4320. const CXXRecordDecl *ClosureClass = MD->getParent();
  4321. assert(
  4322. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  4323. "Number of captures must be zero for conversion to function-ptr");
  4324. const CXXMethodDecl *LambdaCallOp =
  4325. ClosureClass->getLambdaCallOperator();
  4326. // Set 'FD', the function that will be called below, to the call
  4327. // operator. If the closure object represents a generic lambda, find
  4328. // the corresponding specialization of the call operator.
  4329. if (ClosureClass->isGenericLambda()) {
  4330. assert(MD->isFunctionTemplateSpecialization() &&
  4331. "A generic lambda's static-invoker function must be a "
  4332. "template specialization");
  4333. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  4334. FunctionTemplateDecl *CallOpTemplate =
  4335. LambdaCallOp->getDescribedFunctionTemplate();
  4336. void *InsertPos = nullptr;
  4337. FunctionDecl *CorrespondingCallOpSpecialization =
  4338. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  4339. assert(CorrespondingCallOpSpecialization &&
  4340. "We must always have a function call operator specialization "
  4341. "that corresponds to our static invoker specialization");
  4342. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  4343. } else
  4344. FD = LambdaCallOp;
  4345. }
  4346. } else
  4347. return Error(E);
  4348. if (This && !This->checkSubobject(Info, E, CSK_This))
  4349. return false;
  4350. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  4351. // calls to such functions in constant expressions.
  4352. if (This && !HasQualifier &&
  4353. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  4354. return Error(E, diag::note_constexpr_virtual_call);
  4355. const FunctionDecl *Definition = nullptr;
  4356. Stmt *Body = FD->getBody(Definition);
  4357. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  4358. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  4359. Result, ResultSlot))
  4360. return false;
  4361. return true;
  4362. }
  4363. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4364. return StmtVisitorTy::Visit(E->getInitializer());
  4365. }
  4366. bool VisitInitListExpr(const InitListExpr *E) {
  4367. if (E->getNumInits() == 0)
  4368. return DerivedZeroInitialization(E);
  4369. if (E->getNumInits() == 1)
  4370. return StmtVisitorTy::Visit(E->getInit(0));
  4371. return Error(E);
  4372. }
  4373. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  4374. return DerivedZeroInitialization(E);
  4375. }
  4376. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  4377. return DerivedZeroInitialization(E);
  4378. }
  4379. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  4380. return DerivedZeroInitialization(E);
  4381. }
  4382. /// A member expression where the object is a prvalue is itself a prvalue.
  4383. bool VisitMemberExpr(const MemberExpr *E) {
  4384. assert(!E->isArrow() && "missing call to bound member function?");
  4385. APValue Val;
  4386. if (!Evaluate(Val, Info, E->getBase()))
  4387. return false;
  4388. QualType BaseTy = E->getBase()->getType();
  4389. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  4390. if (!FD) return Error(E);
  4391. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  4392. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4393. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4394. CompleteObject Obj(&Val, BaseTy, true);
  4395. SubobjectDesignator Designator(BaseTy);
  4396. Designator.addDeclUnchecked(FD);
  4397. APValue Result;
  4398. return extractSubobject(Info, E, Obj, Designator, Result) &&
  4399. DerivedSuccess(Result, E);
  4400. }
  4401. bool VisitCastExpr(const CastExpr *E) {
  4402. switch (E->getCastKind()) {
  4403. default:
  4404. break;
  4405. case CK_AtomicToNonAtomic: {
  4406. APValue AtomicVal;
  4407. // This does not need to be done in place even for class/array types:
  4408. // atomic-to-non-atomic conversion implies copying the object
  4409. // representation.
  4410. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  4411. return false;
  4412. return DerivedSuccess(AtomicVal, E);
  4413. }
  4414. case CK_NoOp:
  4415. case CK_UserDefinedConversion:
  4416. return StmtVisitorTy::Visit(E->getSubExpr());
  4417. case CK_LValueToRValue: {
  4418. LValue LVal;
  4419. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  4420. return false;
  4421. APValue RVal;
  4422. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  4423. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  4424. LVal, RVal))
  4425. return false;
  4426. return DerivedSuccess(RVal, E);
  4427. }
  4428. }
  4429. return Error(E);
  4430. }
  4431. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  4432. return VisitUnaryPostIncDec(UO);
  4433. }
  4434. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  4435. return VisitUnaryPostIncDec(UO);
  4436. }
  4437. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  4438. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4439. return Error(UO);
  4440. LValue LVal;
  4441. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  4442. return false;
  4443. APValue RVal;
  4444. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  4445. UO->isIncrementOp(), &RVal))
  4446. return false;
  4447. return DerivedSuccess(RVal, UO);
  4448. }
  4449. bool VisitStmtExpr(const StmtExpr *E) {
  4450. // We will have checked the full-expressions inside the statement expression
  4451. // when they were completed, and don't need to check them again now.
  4452. if (Info.checkingForOverflow())
  4453. return Error(E);
  4454. BlockScopeRAII Scope(Info);
  4455. const CompoundStmt *CS = E->getSubStmt();
  4456. if (CS->body_empty())
  4457. return true;
  4458. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  4459. BE = CS->body_end();
  4460. /**/; ++BI) {
  4461. if (BI + 1 == BE) {
  4462. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  4463. if (!FinalExpr) {
  4464. Info.FFDiag((*BI)->getLocStart(),
  4465. diag::note_constexpr_stmt_expr_unsupported);
  4466. return false;
  4467. }
  4468. return this->Visit(FinalExpr);
  4469. }
  4470. APValue ReturnValue;
  4471. StmtResult Result = { ReturnValue, nullptr };
  4472. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  4473. if (ESR != ESR_Succeeded) {
  4474. // FIXME: If the statement-expression terminated due to 'return',
  4475. // 'break', or 'continue', it would be nice to propagate that to
  4476. // the outer statement evaluation rather than bailing out.
  4477. if (ESR != ESR_Failed)
  4478. Info.FFDiag((*BI)->getLocStart(),
  4479. diag::note_constexpr_stmt_expr_unsupported);
  4480. return false;
  4481. }
  4482. }
  4483. llvm_unreachable("Return from function from the loop above.");
  4484. }
  4485. /// Visit a value which is evaluated, but whose value is ignored.
  4486. void VisitIgnoredValue(const Expr *E) {
  4487. EvaluateIgnoredValue(Info, E);
  4488. }
  4489. /// Potentially visit a MemberExpr's base expression.
  4490. void VisitIgnoredBaseExpression(const Expr *E) {
  4491. // While MSVC doesn't evaluate the base expression, it does diagnose the
  4492. // presence of side-effecting behavior.
  4493. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  4494. return;
  4495. VisitIgnoredValue(E);
  4496. }
  4497. };
  4498. } // namespace
  4499. //===----------------------------------------------------------------------===//
  4500. // Common base class for lvalue and temporary evaluation.
  4501. //===----------------------------------------------------------------------===//
  4502. namespace {
  4503. template<class Derived>
  4504. class LValueExprEvaluatorBase
  4505. : public ExprEvaluatorBase<Derived> {
  4506. protected:
  4507. LValue &Result;
  4508. bool InvalidBaseOK;
  4509. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  4510. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  4511. bool Success(APValue::LValueBase B) {
  4512. Result.set(B);
  4513. return true;
  4514. }
  4515. bool evaluatePointer(const Expr *E, LValue &Result) {
  4516. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  4517. }
  4518. public:
  4519. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  4520. : ExprEvaluatorBaseTy(Info), Result(Result),
  4521. InvalidBaseOK(InvalidBaseOK) {}
  4522. bool Success(const APValue &V, const Expr *E) {
  4523. Result.setFrom(this->Info.Ctx, V);
  4524. return true;
  4525. }
  4526. bool VisitMemberExpr(const MemberExpr *E) {
  4527. // Handle non-static data members.
  4528. QualType BaseTy;
  4529. bool EvalOK;
  4530. if (E->isArrow()) {
  4531. EvalOK = evaluatePointer(E->getBase(), Result);
  4532. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  4533. } else if (E->getBase()->isRValue()) {
  4534. assert(E->getBase()->getType()->isRecordType());
  4535. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  4536. BaseTy = E->getBase()->getType();
  4537. } else {
  4538. EvalOK = this->Visit(E->getBase());
  4539. BaseTy = E->getBase()->getType();
  4540. }
  4541. if (!EvalOK) {
  4542. if (!InvalidBaseOK)
  4543. return false;
  4544. Result.setInvalid(E);
  4545. return true;
  4546. }
  4547. const ValueDecl *MD = E->getMemberDecl();
  4548. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  4549. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4550. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4551. (void)BaseTy;
  4552. if (!HandleLValueMember(this->Info, E, Result, FD))
  4553. return false;
  4554. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  4555. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  4556. return false;
  4557. } else
  4558. return this->Error(E);
  4559. if (MD->getType()->isReferenceType()) {
  4560. APValue RefValue;
  4561. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  4562. RefValue))
  4563. return false;
  4564. return Success(RefValue, E);
  4565. }
  4566. return true;
  4567. }
  4568. bool VisitBinaryOperator(const BinaryOperator *E) {
  4569. switch (E->getOpcode()) {
  4570. default:
  4571. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4572. case BO_PtrMemD:
  4573. case BO_PtrMemI:
  4574. return HandleMemberPointerAccess(this->Info, E, Result);
  4575. }
  4576. }
  4577. bool VisitCastExpr(const CastExpr *E) {
  4578. switch (E->getCastKind()) {
  4579. default:
  4580. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4581. case CK_DerivedToBase:
  4582. case CK_UncheckedDerivedToBase:
  4583. if (!this->Visit(E->getSubExpr()))
  4584. return false;
  4585. // Now figure out the necessary offset to add to the base LV to get from
  4586. // the derived class to the base class.
  4587. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  4588. Result);
  4589. }
  4590. }
  4591. };
  4592. }
  4593. //===----------------------------------------------------------------------===//
  4594. // LValue Evaluation
  4595. //
  4596. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  4597. // function designators (in C), decl references to void objects (in C), and
  4598. // temporaries (if building with -Wno-address-of-temporary).
  4599. //
  4600. // LValue evaluation produces values comprising a base expression of one of the
  4601. // following types:
  4602. // - Declarations
  4603. // * VarDecl
  4604. // * FunctionDecl
  4605. // - Literals
  4606. // * CompoundLiteralExpr in C (and in global scope in C++)
  4607. // * StringLiteral
  4608. // * CXXTypeidExpr
  4609. // * PredefinedExpr
  4610. // * ObjCStringLiteralExpr
  4611. // * ObjCEncodeExpr
  4612. // * AddrLabelExpr
  4613. // * BlockExpr
  4614. // * CallExpr for a MakeStringConstant builtin
  4615. // - Locals and temporaries
  4616. // * MaterializeTemporaryExpr
  4617. // * Any Expr, with a CallIndex indicating the function in which the temporary
  4618. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  4619. // from the AST (FIXME).
  4620. // * A MaterializeTemporaryExpr that has static storage duration, with no
  4621. // CallIndex, for a lifetime-extended temporary.
  4622. // plus an offset in bytes.
  4623. //===----------------------------------------------------------------------===//
  4624. namespace {
  4625. class LValueExprEvaluator
  4626. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  4627. public:
  4628. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  4629. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  4630. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  4631. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  4632. bool VisitDeclRefExpr(const DeclRefExpr *E);
  4633. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  4634. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  4635. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  4636. bool VisitMemberExpr(const MemberExpr *E);
  4637. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  4638. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  4639. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  4640. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  4641. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  4642. bool VisitUnaryDeref(const UnaryOperator *E);
  4643. bool VisitUnaryReal(const UnaryOperator *E);
  4644. bool VisitUnaryImag(const UnaryOperator *E);
  4645. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  4646. return VisitUnaryPreIncDec(UO);
  4647. }
  4648. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  4649. return VisitUnaryPreIncDec(UO);
  4650. }
  4651. bool VisitBinAssign(const BinaryOperator *BO);
  4652. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  4653. bool VisitCastExpr(const CastExpr *E) {
  4654. switch (E->getCastKind()) {
  4655. default:
  4656. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4657. case CK_LValueBitCast:
  4658. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4659. if (!Visit(E->getSubExpr()))
  4660. return false;
  4661. Result.Designator.setInvalid();
  4662. return true;
  4663. case CK_BaseToDerived:
  4664. if (!Visit(E->getSubExpr()))
  4665. return false;
  4666. return HandleBaseToDerivedCast(Info, E, Result);
  4667. }
  4668. }
  4669. };
  4670. } // end anonymous namespace
  4671. /// Evaluate an expression as an lvalue. This can be legitimately called on
  4672. /// expressions which are not glvalues, in three cases:
  4673. /// * function designators in C, and
  4674. /// * "extern void" objects
  4675. /// * @selector() expressions in Objective-C
  4676. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  4677. bool InvalidBaseOK) {
  4678. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  4679. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  4680. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  4681. }
  4682. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  4683. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  4684. return Success(FD);
  4685. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  4686. return VisitVarDecl(E, VD);
  4687. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  4688. return Visit(BD->getBinding());
  4689. return Error(E);
  4690. }
  4691. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  4692. // If we are within a lambda's call operator, check whether the 'VD' referred
  4693. // to within 'E' actually represents a lambda-capture that maps to a
  4694. // data-member/field within the closure object, and if so, evaluate to the
  4695. // field or what the field refers to.
  4696. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  4697. isa<DeclRefExpr>(E) &&
  4698. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  4699. // We don't always have a complete capture-map when checking or inferring if
  4700. // the function call operator meets the requirements of a constexpr function
  4701. // - but we don't need to evaluate the captures to determine constexprness
  4702. // (dcl.constexpr C++17).
  4703. if (Info.checkingPotentialConstantExpression())
  4704. return false;
  4705. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  4706. // Start with 'Result' referring to the complete closure object...
  4707. Result = *Info.CurrentCall->This;
  4708. // ... then update it to refer to the field of the closure object
  4709. // that represents the capture.
  4710. if (!HandleLValueMember(Info, E, Result, FD))
  4711. return false;
  4712. // And if the field is of reference type, update 'Result' to refer to what
  4713. // the field refers to.
  4714. if (FD->getType()->isReferenceType()) {
  4715. APValue RVal;
  4716. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  4717. RVal))
  4718. return false;
  4719. Result.setFrom(Info.Ctx, RVal);
  4720. }
  4721. return true;
  4722. }
  4723. }
  4724. CallStackFrame *Frame = nullptr;
  4725. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  4726. // Only if a local variable was declared in the function currently being
  4727. // evaluated, do we expect to be able to find its value in the current
  4728. // frame. (Otherwise it was likely declared in an enclosing context and
  4729. // could either have a valid evaluatable value (for e.g. a constexpr
  4730. // variable) or be ill-formed (and trigger an appropriate evaluation
  4731. // diagnostic)).
  4732. if (Info.CurrentCall->Callee &&
  4733. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  4734. Frame = Info.CurrentCall;
  4735. }
  4736. }
  4737. if (!VD->getType()->isReferenceType()) {
  4738. if (Frame) {
  4739. Result.set({VD, Frame->Index,
  4740. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  4741. return true;
  4742. }
  4743. return Success(VD);
  4744. }
  4745. APValue *V;
  4746. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  4747. return false;
  4748. if (V->isUninit()) {
  4749. if (!Info.checkingPotentialConstantExpression())
  4750. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  4751. return false;
  4752. }
  4753. return Success(*V, E);
  4754. }
  4755. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  4756. const MaterializeTemporaryExpr *E) {
  4757. // Walk through the expression to find the materialized temporary itself.
  4758. SmallVector<const Expr *, 2> CommaLHSs;
  4759. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4760. const Expr *Inner = E->GetTemporaryExpr()->
  4761. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  4762. // If we passed any comma operators, evaluate their LHSs.
  4763. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  4764. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  4765. return false;
  4766. // A materialized temporary with static storage duration can appear within the
  4767. // result of a constant expression evaluation, so we need to preserve its
  4768. // value for use outside this evaluation.
  4769. APValue *Value;
  4770. if (E->getStorageDuration() == SD_Static) {
  4771. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  4772. *Value = APValue();
  4773. Result.set(E);
  4774. } else {
  4775. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  4776. *Info.CurrentCall);
  4777. }
  4778. QualType Type = Inner->getType();
  4779. // Materialize the temporary itself.
  4780. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  4781. (E->getStorageDuration() == SD_Static &&
  4782. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  4783. *Value = APValue();
  4784. return false;
  4785. }
  4786. // Adjust our lvalue to refer to the desired subobject.
  4787. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  4788. --I;
  4789. switch (Adjustments[I].Kind) {
  4790. case SubobjectAdjustment::DerivedToBaseAdjustment:
  4791. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  4792. Type, Result))
  4793. return false;
  4794. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  4795. break;
  4796. case SubobjectAdjustment::FieldAdjustment:
  4797. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  4798. return false;
  4799. Type = Adjustments[I].Field->getType();
  4800. break;
  4801. case SubobjectAdjustment::MemberPointerAdjustment:
  4802. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  4803. Adjustments[I].Ptr.RHS))
  4804. return false;
  4805. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  4806. break;
  4807. }
  4808. }
  4809. return true;
  4810. }
  4811. bool
  4812. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4813. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  4814. "lvalue compound literal in c++?");
  4815. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  4816. // only see this when folding in C, so there's no standard to follow here.
  4817. return Success(E);
  4818. }
  4819. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  4820. if (!E->isPotentiallyEvaluated())
  4821. return Success(E);
  4822. Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
  4823. << E->getExprOperand()->getType()
  4824. << E->getExprOperand()->getSourceRange();
  4825. return false;
  4826. }
  4827. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4828. return Success(E);
  4829. }
  4830. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  4831. // Handle static data members.
  4832. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  4833. VisitIgnoredBaseExpression(E->getBase());
  4834. return VisitVarDecl(E, VD);
  4835. }
  4836. // Handle static member functions.
  4837. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  4838. if (MD->isStatic()) {
  4839. VisitIgnoredBaseExpression(E->getBase());
  4840. return Success(MD);
  4841. }
  4842. }
  4843. // Handle non-static data members.
  4844. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  4845. }
  4846. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  4847. // FIXME: Deal with vectors as array subscript bases.
  4848. if (E->getBase()->getType()->isVectorType())
  4849. return Error(E);
  4850. bool Success = true;
  4851. if (!evaluatePointer(E->getBase(), Result)) {
  4852. if (!Info.noteFailure())
  4853. return false;
  4854. Success = false;
  4855. }
  4856. APSInt Index;
  4857. if (!EvaluateInteger(E->getIdx(), Index, Info))
  4858. return false;
  4859. return Success &&
  4860. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  4861. }
  4862. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  4863. return evaluatePointer(E->getSubExpr(), Result);
  4864. }
  4865. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4866. if (!Visit(E->getSubExpr()))
  4867. return false;
  4868. // __real is a no-op on scalar lvalues.
  4869. if (E->getSubExpr()->getType()->isAnyComplexType())
  4870. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  4871. return true;
  4872. }
  4873. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4874. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  4875. "lvalue __imag__ on scalar?");
  4876. if (!Visit(E->getSubExpr()))
  4877. return false;
  4878. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  4879. return true;
  4880. }
  4881. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  4882. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4883. return Error(UO);
  4884. if (!this->Visit(UO->getSubExpr()))
  4885. return false;
  4886. return handleIncDec(
  4887. this->Info, UO, Result, UO->getSubExpr()->getType(),
  4888. UO->isIncrementOp(), nullptr);
  4889. }
  4890. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  4891. const CompoundAssignOperator *CAO) {
  4892. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4893. return Error(CAO);
  4894. APValue RHS;
  4895. // The overall lvalue result is the result of evaluating the LHS.
  4896. if (!this->Visit(CAO->getLHS())) {
  4897. if (Info.noteFailure())
  4898. Evaluate(RHS, this->Info, CAO->getRHS());
  4899. return false;
  4900. }
  4901. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  4902. return false;
  4903. return handleCompoundAssignment(
  4904. this->Info, CAO,
  4905. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  4906. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  4907. }
  4908. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  4909. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4910. return Error(E);
  4911. APValue NewVal;
  4912. if (!this->Visit(E->getLHS())) {
  4913. if (Info.noteFailure())
  4914. Evaluate(NewVal, this->Info, E->getRHS());
  4915. return false;
  4916. }
  4917. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  4918. return false;
  4919. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  4920. NewVal);
  4921. }
  4922. //===----------------------------------------------------------------------===//
  4923. // Pointer Evaluation
  4924. //===----------------------------------------------------------------------===//
  4925. /// Attempts to compute the number of bytes available at the pointer
  4926. /// returned by a function with the alloc_size attribute. Returns true if we
  4927. /// were successful. Places an unsigned number into `Result`.
  4928. ///
  4929. /// This expects the given CallExpr to be a call to a function with an
  4930. /// alloc_size attribute.
  4931. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  4932. const CallExpr *Call,
  4933. llvm::APInt &Result) {
  4934. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  4935. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  4936. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  4937. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  4938. if (Call->getNumArgs() <= SizeArgNo)
  4939. return false;
  4940. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  4941. if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
  4942. return false;
  4943. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  4944. return false;
  4945. Into = Into.zextOrSelf(BitsInSizeT);
  4946. return true;
  4947. };
  4948. APSInt SizeOfElem;
  4949. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  4950. return false;
  4951. if (!AllocSize->getNumElemsParam().isValid()) {
  4952. Result = std::move(SizeOfElem);
  4953. return true;
  4954. }
  4955. APSInt NumberOfElems;
  4956. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  4957. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  4958. return false;
  4959. bool Overflow;
  4960. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  4961. if (Overflow)
  4962. return false;
  4963. Result = std::move(BytesAvailable);
  4964. return true;
  4965. }
  4966. /// Convenience function. LVal's base must be a call to an alloc_size
  4967. /// function.
  4968. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  4969. const LValue &LVal,
  4970. llvm::APInt &Result) {
  4971. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  4972. "Can't get the size of a non alloc_size function");
  4973. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  4974. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  4975. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  4976. }
  4977. /// Attempts to evaluate the given LValueBase as the result of a call to
  4978. /// a function with the alloc_size attribute. If it was possible to do so, this
  4979. /// function will return true, make Result's Base point to said function call,
  4980. /// and mark Result's Base as invalid.
  4981. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  4982. LValue &Result) {
  4983. if (Base.isNull())
  4984. return false;
  4985. // Because we do no form of static analysis, we only support const variables.
  4986. //
  4987. // Additionally, we can't support parameters, nor can we support static
  4988. // variables (in the latter case, use-before-assign isn't UB; in the former,
  4989. // we have no clue what they'll be assigned to).
  4990. const auto *VD =
  4991. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  4992. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  4993. return false;
  4994. const Expr *Init = VD->getAnyInitializer();
  4995. if (!Init)
  4996. return false;
  4997. const Expr *E = Init->IgnoreParens();
  4998. if (!tryUnwrapAllocSizeCall(E))
  4999. return false;
  5000. // Store E instead of E unwrapped so that the type of the LValue's base is
  5001. // what the user wanted.
  5002. Result.setInvalid(E);
  5003. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  5004. Result.addUnsizedArray(Info, E, Pointee);
  5005. return true;
  5006. }
  5007. namespace {
  5008. class PointerExprEvaluator
  5009. : public ExprEvaluatorBase<PointerExprEvaluator> {
  5010. LValue &Result;
  5011. bool InvalidBaseOK;
  5012. bool Success(const Expr *E) {
  5013. Result.set(E);
  5014. return true;
  5015. }
  5016. bool evaluateLValue(const Expr *E, LValue &Result) {
  5017. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  5018. }
  5019. bool evaluatePointer(const Expr *E, LValue &Result) {
  5020. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  5021. }
  5022. bool visitNonBuiltinCallExpr(const CallExpr *E);
  5023. public:
  5024. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  5025. : ExprEvaluatorBaseTy(info), Result(Result),
  5026. InvalidBaseOK(InvalidBaseOK) {}
  5027. bool Success(const APValue &V, const Expr *E) {
  5028. Result.setFrom(Info.Ctx, V);
  5029. return true;
  5030. }
  5031. bool ZeroInitialization(const Expr *E) {
  5032. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  5033. Result.setNull(E->getType(), TargetVal);
  5034. return true;
  5035. }
  5036. bool VisitBinaryOperator(const BinaryOperator *E);
  5037. bool VisitCastExpr(const CastExpr* E);
  5038. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5039. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  5040. { return Success(E); }
  5041. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  5042. if (Info.noteFailure())
  5043. EvaluateIgnoredValue(Info, E->getSubExpr());
  5044. return Error(E);
  5045. }
  5046. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  5047. { return Success(E); }
  5048. bool VisitCallExpr(const CallExpr *E);
  5049. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  5050. bool VisitBlockExpr(const BlockExpr *E) {
  5051. if (!E->getBlockDecl()->hasCaptures())
  5052. return Success(E);
  5053. return Error(E);
  5054. }
  5055. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  5056. // Can't look at 'this' when checking a potential constant expression.
  5057. if (Info.checkingPotentialConstantExpression())
  5058. return false;
  5059. if (!Info.CurrentCall->This) {
  5060. if (Info.getLangOpts().CPlusPlus11)
  5061. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  5062. else
  5063. Info.FFDiag(E);
  5064. return false;
  5065. }
  5066. Result = *Info.CurrentCall->This;
  5067. // If we are inside a lambda's call operator, the 'this' expression refers
  5068. // to the enclosing '*this' object (either by value or reference) which is
  5069. // either copied into the closure object's field that represents the '*this'
  5070. // or refers to '*this'.
  5071. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  5072. // Update 'Result' to refer to the data member/field of the closure object
  5073. // that represents the '*this' capture.
  5074. if (!HandleLValueMember(Info, E, Result,
  5075. Info.CurrentCall->LambdaThisCaptureField))
  5076. return false;
  5077. // If we captured '*this' by reference, replace the field with its referent.
  5078. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  5079. ->isPointerType()) {
  5080. APValue RVal;
  5081. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  5082. RVal))
  5083. return false;
  5084. Result.setFrom(Info.Ctx, RVal);
  5085. }
  5086. }
  5087. return true;
  5088. }
  5089. // FIXME: Missing: @protocol, @selector
  5090. };
  5091. } // end anonymous namespace
  5092. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  5093. bool InvalidBaseOK) {
  5094. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  5095. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5096. }
  5097. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5098. if (E->getOpcode() != BO_Add &&
  5099. E->getOpcode() != BO_Sub)
  5100. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5101. const Expr *PExp = E->getLHS();
  5102. const Expr *IExp = E->getRHS();
  5103. if (IExp->getType()->isPointerType())
  5104. std::swap(PExp, IExp);
  5105. bool EvalPtrOK = evaluatePointer(PExp, Result);
  5106. if (!EvalPtrOK && !Info.noteFailure())
  5107. return false;
  5108. llvm::APSInt Offset;
  5109. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  5110. return false;
  5111. if (E->getOpcode() == BO_Sub)
  5112. negateAsSigned(Offset);
  5113. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  5114. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  5115. }
  5116. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5117. return evaluateLValue(E->getSubExpr(), Result);
  5118. }
  5119. bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  5120. const Expr* SubExpr = E->getSubExpr();
  5121. switch (E->getCastKind()) {
  5122. default:
  5123. break;
  5124. case CK_BitCast:
  5125. case CK_CPointerToObjCPointerCast:
  5126. case CK_BlockPointerToObjCPointerCast:
  5127. case CK_AnyPointerToBlockPointerCast:
  5128. case CK_AddressSpaceConversion:
  5129. if (!Visit(SubExpr))
  5130. return false;
  5131. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  5132. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  5133. // also static_casts, but we disallow them as a resolution to DR1312.
  5134. if (!E->getType()->isVoidPointerType()) {
  5135. Result.Designator.setInvalid();
  5136. if (SubExpr->getType()->isVoidPointerType())
  5137. CCEDiag(E, diag::note_constexpr_invalid_cast)
  5138. << 3 << SubExpr->getType();
  5139. else
  5140. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5141. }
  5142. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  5143. ZeroInitialization(E);
  5144. return true;
  5145. case CK_DerivedToBase:
  5146. case CK_UncheckedDerivedToBase:
  5147. if (!evaluatePointer(E->getSubExpr(), Result))
  5148. return false;
  5149. if (!Result.Base && Result.Offset.isZero())
  5150. return true;
  5151. // Now figure out the necessary offset to add to the base LV to get from
  5152. // the derived class to the base class.
  5153. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  5154. castAs<PointerType>()->getPointeeType(),
  5155. Result);
  5156. case CK_BaseToDerived:
  5157. if (!Visit(E->getSubExpr()))
  5158. return false;
  5159. if (!Result.Base && Result.Offset.isZero())
  5160. return true;
  5161. return HandleBaseToDerivedCast(Info, E, Result);
  5162. case CK_NullToPointer:
  5163. VisitIgnoredValue(E->getSubExpr());
  5164. return ZeroInitialization(E);
  5165. case CK_IntegralToPointer: {
  5166. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5167. APValue Value;
  5168. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  5169. break;
  5170. if (Value.isInt()) {
  5171. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  5172. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  5173. Result.Base = (Expr*)nullptr;
  5174. Result.InvalidBase = false;
  5175. Result.Offset = CharUnits::fromQuantity(N);
  5176. Result.Designator.setInvalid();
  5177. Result.IsNullPtr = false;
  5178. return true;
  5179. } else {
  5180. // Cast is of an lvalue, no need to change value.
  5181. Result.setFrom(Info.Ctx, Value);
  5182. return true;
  5183. }
  5184. }
  5185. case CK_ArrayToPointerDecay: {
  5186. if (SubExpr->isGLValue()) {
  5187. if (!evaluateLValue(SubExpr, Result))
  5188. return false;
  5189. } else {
  5190. APValue &Value = createTemporary(SubExpr, false, Result,
  5191. *Info.CurrentCall);
  5192. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  5193. return false;
  5194. }
  5195. // The result is a pointer to the first element of the array.
  5196. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  5197. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5198. Result.addArray(Info, E, CAT);
  5199. else
  5200. Result.addUnsizedArray(Info, E, AT->getElementType());
  5201. return true;
  5202. }
  5203. case CK_FunctionToPointerDecay:
  5204. return evaluateLValue(SubExpr, Result);
  5205. case CK_LValueToRValue: {
  5206. LValue LVal;
  5207. if (!evaluateLValue(E->getSubExpr(), LVal))
  5208. return false;
  5209. APValue RVal;
  5210. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5211. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5212. LVal, RVal))
  5213. return InvalidBaseOK &&
  5214. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  5215. return Success(RVal, E);
  5216. }
  5217. }
  5218. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5219. }
  5220. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
  5221. // C++ [expr.alignof]p3:
  5222. // When alignof is applied to a reference type, the result is the
  5223. // alignment of the referenced type.
  5224. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  5225. T = Ref->getPointeeType();
  5226. // __alignof is defined to return the preferred alignment.
  5227. if (T.getQualifiers().hasUnaligned())
  5228. return CharUnits::One();
  5229. return Info.Ctx.toCharUnitsFromBits(
  5230. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  5231. }
  5232. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
  5233. E = E->IgnoreParens();
  5234. // The kinds of expressions that we have special-case logic here for
  5235. // should be kept up to date with the special checks for those
  5236. // expressions in Sema.
  5237. // alignof decl is always accepted, even if it doesn't make sense: we default
  5238. // to 1 in those cases.
  5239. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5240. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  5241. /*RefAsPointee*/true);
  5242. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  5243. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  5244. /*RefAsPointee*/true);
  5245. return GetAlignOfType(Info, E->getType());
  5246. }
  5247. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  5248. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  5249. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  5250. return true;
  5251. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  5252. return false;
  5253. Result.setInvalid(E);
  5254. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  5255. Result.addUnsizedArray(Info, E, PointeeTy);
  5256. return true;
  5257. }
  5258. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  5259. if (IsStringLiteralCall(E))
  5260. return Success(E);
  5261. if (unsigned BuiltinOp = E->getBuiltinCallee())
  5262. return VisitBuiltinCallExpr(E, BuiltinOp);
  5263. return visitNonBuiltinCallExpr(E);
  5264. }
  5265. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  5266. unsigned BuiltinOp) {
  5267. switch (BuiltinOp) {
  5268. case Builtin::BI__builtin_addressof:
  5269. return evaluateLValue(E->getArg(0), Result);
  5270. case Builtin::BI__builtin_assume_aligned: {
  5271. // We need to be very careful here because: if the pointer does not have the
  5272. // asserted alignment, then the behavior is undefined, and undefined
  5273. // behavior is non-constant.
  5274. if (!evaluatePointer(E->getArg(0), Result))
  5275. return false;
  5276. LValue OffsetResult(Result);
  5277. APSInt Alignment;
  5278. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  5279. return false;
  5280. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  5281. if (E->getNumArgs() > 2) {
  5282. APSInt Offset;
  5283. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  5284. return false;
  5285. int64_t AdditionalOffset = -Offset.getZExtValue();
  5286. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  5287. }
  5288. // If there is a base object, then it must have the correct alignment.
  5289. if (OffsetResult.Base) {
  5290. CharUnits BaseAlignment;
  5291. if (const ValueDecl *VD =
  5292. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  5293. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  5294. } else {
  5295. BaseAlignment =
  5296. GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
  5297. }
  5298. if (BaseAlignment < Align) {
  5299. Result.Designator.setInvalid();
  5300. // FIXME: Add support to Diagnostic for long / long long.
  5301. CCEDiag(E->getArg(0),
  5302. diag::note_constexpr_baa_insufficient_alignment) << 0
  5303. << (unsigned)BaseAlignment.getQuantity()
  5304. << (unsigned)Align.getQuantity();
  5305. return false;
  5306. }
  5307. }
  5308. // The offset must also have the correct alignment.
  5309. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  5310. Result.Designator.setInvalid();
  5311. (OffsetResult.Base
  5312. ? CCEDiag(E->getArg(0),
  5313. diag::note_constexpr_baa_insufficient_alignment) << 1
  5314. : CCEDiag(E->getArg(0),
  5315. diag::note_constexpr_baa_value_insufficient_alignment))
  5316. << (int)OffsetResult.Offset.getQuantity()
  5317. << (unsigned)Align.getQuantity();
  5318. return false;
  5319. }
  5320. return true;
  5321. }
  5322. case Builtin::BIstrchr:
  5323. case Builtin::BIwcschr:
  5324. case Builtin::BImemchr:
  5325. case Builtin::BIwmemchr:
  5326. if (Info.getLangOpts().CPlusPlus11)
  5327. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5328. << /*isConstexpr*/0 << /*isConstructor*/0
  5329. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5330. else
  5331. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5332. LLVM_FALLTHROUGH;
  5333. case Builtin::BI__builtin_strchr:
  5334. case Builtin::BI__builtin_wcschr:
  5335. case Builtin::BI__builtin_memchr:
  5336. case Builtin::BI__builtin_char_memchr:
  5337. case Builtin::BI__builtin_wmemchr: {
  5338. if (!Visit(E->getArg(0)))
  5339. return false;
  5340. APSInt Desired;
  5341. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  5342. return false;
  5343. uint64_t MaxLength = uint64_t(-1);
  5344. if (BuiltinOp != Builtin::BIstrchr &&
  5345. BuiltinOp != Builtin::BIwcschr &&
  5346. BuiltinOp != Builtin::BI__builtin_strchr &&
  5347. BuiltinOp != Builtin::BI__builtin_wcschr) {
  5348. APSInt N;
  5349. if (!EvaluateInteger(E->getArg(2), N, Info))
  5350. return false;
  5351. MaxLength = N.getExtValue();
  5352. }
  5353. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  5354. // Figure out what value we're actually looking for (after converting to
  5355. // the corresponding unsigned type if necessary).
  5356. uint64_t DesiredVal;
  5357. bool StopAtNull = false;
  5358. switch (BuiltinOp) {
  5359. case Builtin::BIstrchr:
  5360. case Builtin::BI__builtin_strchr:
  5361. // strchr compares directly to the passed integer, and therefore
  5362. // always fails if given an int that is not a char.
  5363. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  5364. E->getArg(1)->getType(),
  5365. Desired),
  5366. Desired))
  5367. return ZeroInitialization(E);
  5368. StopAtNull = true;
  5369. LLVM_FALLTHROUGH;
  5370. case Builtin::BImemchr:
  5371. case Builtin::BI__builtin_memchr:
  5372. case Builtin::BI__builtin_char_memchr:
  5373. // memchr compares by converting both sides to unsigned char. That's also
  5374. // correct for strchr if we get this far (to cope with plain char being
  5375. // unsigned in the strchr case).
  5376. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  5377. break;
  5378. case Builtin::BIwcschr:
  5379. case Builtin::BI__builtin_wcschr:
  5380. StopAtNull = true;
  5381. LLVM_FALLTHROUGH;
  5382. case Builtin::BIwmemchr:
  5383. case Builtin::BI__builtin_wmemchr:
  5384. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  5385. DesiredVal = Desired.getZExtValue();
  5386. break;
  5387. }
  5388. for (; MaxLength; --MaxLength) {
  5389. APValue Char;
  5390. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  5391. !Char.isInt())
  5392. return false;
  5393. if (Char.getInt().getZExtValue() == DesiredVal)
  5394. return true;
  5395. if (StopAtNull && !Char.getInt())
  5396. break;
  5397. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  5398. return false;
  5399. }
  5400. // Not found: return nullptr.
  5401. return ZeroInitialization(E);
  5402. }
  5403. default:
  5404. return visitNonBuiltinCallExpr(E);
  5405. }
  5406. }
  5407. //===----------------------------------------------------------------------===//
  5408. // Member Pointer Evaluation
  5409. //===----------------------------------------------------------------------===//
  5410. namespace {
  5411. class MemberPointerExprEvaluator
  5412. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  5413. MemberPtr &Result;
  5414. bool Success(const ValueDecl *D) {
  5415. Result = MemberPtr(D);
  5416. return true;
  5417. }
  5418. public:
  5419. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  5420. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  5421. bool Success(const APValue &V, const Expr *E) {
  5422. Result.setFrom(V);
  5423. return true;
  5424. }
  5425. bool ZeroInitialization(const Expr *E) {
  5426. return Success((const ValueDecl*)nullptr);
  5427. }
  5428. bool VisitCastExpr(const CastExpr *E);
  5429. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5430. };
  5431. } // end anonymous namespace
  5432. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  5433. EvalInfo &Info) {
  5434. assert(E->isRValue() && E->getType()->isMemberPointerType());
  5435. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  5436. }
  5437. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5438. switch (E->getCastKind()) {
  5439. default:
  5440. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5441. case CK_NullToMemberPointer:
  5442. VisitIgnoredValue(E->getSubExpr());
  5443. return ZeroInitialization(E);
  5444. case CK_BaseToDerivedMemberPointer: {
  5445. if (!Visit(E->getSubExpr()))
  5446. return false;
  5447. if (E->path_empty())
  5448. return true;
  5449. // Base-to-derived member pointer casts store the path in derived-to-base
  5450. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  5451. // the wrong end of the derived->base arc, so stagger the path by one class.
  5452. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  5453. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  5454. PathI != PathE; ++PathI) {
  5455. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5456. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  5457. if (!Result.castToDerived(Derived))
  5458. return Error(E);
  5459. }
  5460. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  5461. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  5462. return Error(E);
  5463. return true;
  5464. }
  5465. case CK_DerivedToBaseMemberPointer:
  5466. if (!Visit(E->getSubExpr()))
  5467. return false;
  5468. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5469. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5470. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5471. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5472. if (!Result.castToBase(Base))
  5473. return Error(E);
  5474. }
  5475. return true;
  5476. }
  5477. }
  5478. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5479. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  5480. // member can be formed.
  5481. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  5482. }
  5483. //===----------------------------------------------------------------------===//
  5484. // Record Evaluation
  5485. //===----------------------------------------------------------------------===//
  5486. namespace {
  5487. class RecordExprEvaluator
  5488. : public ExprEvaluatorBase<RecordExprEvaluator> {
  5489. const LValue &This;
  5490. APValue &Result;
  5491. public:
  5492. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  5493. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  5494. bool Success(const APValue &V, const Expr *E) {
  5495. Result = V;
  5496. return true;
  5497. }
  5498. bool ZeroInitialization(const Expr *E) {
  5499. return ZeroInitialization(E, E->getType());
  5500. }
  5501. bool ZeroInitialization(const Expr *E, QualType T);
  5502. bool VisitCallExpr(const CallExpr *E) {
  5503. return handleCallExpr(E, Result, &This);
  5504. }
  5505. bool VisitCastExpr(const CastExpr *E);
  5506. bool VisitInitListExpr(const InitListExpr *E);
  5507. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5508. return VisitCXXConstructExpr(E, E->getType());
  5509. }
  5510. bool VisitLambdaExpr(const LambdaExpr *E);
  5511. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  5512. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  5513. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  5514. bool VisitBinCmp(const BinaryOperator *E);
  5515. };
  5516. }
  5517. /// Perform zero-initialization on an object of non-union class type.
  5518. /// C++11 [dcl.init]p5:
  5519. /// To zero-initialize an object or reference of type T means:
  5520. /// [...]
  5521. /// -- if T is a (possibly cv-qualified) non-union class type,
  5522. /// each non-static data member and each base-class subobject is
  5523. /// zero-initialized
  5524. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  5525. const RecordDecl *RD,
  5526. const LValue &This, APValue &Result) {
  5527. assert(!RD->isUnion() && "Expected non-union class type");
  5528. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  5529. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  5530. std::distance(RD->field_begin(), RD->field_end()));
  5531. if (RD->isInvalidDecl()) return false;
  5532. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5533. if (CD) {
  5534. unsigned Index = 0;
  5535. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  5536. End = CD->bases_end(); I != End; ++I, ++Index) {
  5537. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  5538. LValue Subobject = This;
  5539. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  5540. return false;
  5541. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  5542. Result.getStructBase(Index)))
  5543. return false;
  5544. }
  5545. }
  5546. for (const auto *I : RD->fields()) {
  5547. // -- if T is a reference type, no initialization is performed.
  5548. if (I->getType()->isReferenceType())
  5549. continue;
  5550. LValue Subobject = This;
  5551. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  5552. return false;
  5553. ImplicitValueInitExpr VIE(I->getType());
  5554. if (!EvaluateInPlace(
  5555. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  5556. return false;
  5557. }
  5558. return true;
  5559. }
  5560. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  5561. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  5562. if (RD->isInvalidDecl()) return false;
  5563. if (RD->isUnion()) {
  5564. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  5565. // object's first non-static named data member is zero-initialized
  5566. RecordDecl::field_iterator I = RD->field_begin();
  5567. if (I == RD->field_end()) {
  5568. Result = APValue((const FieldDecl*)nullptr);
  5569. return true;
  5570. }
  5571. LValue Subobject = This;
  5572. if (!HandleLValueMember(Info, E, Subobject, *I))
  5573. return false;
  5574. Result = APValue(*I);
  5575. ImplicitValueInitExpr VIE(I->getType());
  5576. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  5577. }
  5578. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  5579. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  5580. return false;
  5581. }
  5582. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  5583. }
  5584. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5585. switch (E->getCastKind()) {
  5586. default:
  5587. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5588. case CK_ConstructorConversion:
  5589. return Visit(E->getSubExpr());
  5590. case CK_DerivedToBase:
  5591. case CK_UncheckedDerivedToBase: {
  5592. APValue DerivedObject;
  5593. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  5594. return false;
  5595. if (!DerivedObject.isStruct())
  5596. return Error(E->getSubExpr());
  5597. // Derived-to-base rvalue conversion: just slice off the derived part.
  5598. APValue *Value = &DerivedObject;
  5599. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  5600. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5601. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5602. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  5603. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5604. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  5605. RD = Base;
  5606. }
  5607. Result = *Value;
  5608. return true;
  5609. }
  5610. }
  5611. }
  5612. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5613. if (E->isTransparent())
  5614. return Visit(E->getInit(0));
  5615. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  5616. if (RD->isInvalidDecl()) return false;
  5617. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5618. if (RD->isUnion()) {
  5619. const FieldDecl *Field = E->getInitializedFieldInUnion();
  5620. Result = APValue(Field);
  5621. if (!Field)
  5622. return true;
  5623. // If the initializer list for a union does not contain any elements, the
  5624. // first element of the union is value-initialized.
  5625. // FIXME: The element should be initialized from an initializer list.
  5626. // Is this difference ever observable for initializer lists which
  5627. // we don't build?
  5628. ImplicitValueInitExpr VIE(Field->getType());
  5629. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  5630. LValue Subobject = This;
  5631. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  5632. return false;
  5633. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5634. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5635. isa<CXXDefaultInitExpr>(InitExpr));
  5636. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  5637. }
  5638. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  5639. if (Result.isUninit())
  5640. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  5641. std::distance(RD->field_begin(), RD->field_end()));
  5642. unsigned ElementNo = 0;
  5643. bool Success = true;
  5644. // Initialize base classes.
  5645. if (CXXRD) {
  5646. for (const auto &Base : CXXRD->bases()) {
  5647. assert(ElementNo < E->getNumInits() && "missing init for base class");
  5648. const Expr *Init = E->getInit(ElementNo);
  5649. LValue Subobject = This;
  5650. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  5651. return false;
  5652. APValue &FieldVal = Result.getStructBase(ElementNo);
  5653. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  5654. if (!Info.noteFailure())
  5655. return false;
  5656. Success = false;
  5657. }
  5658. ++ElementNo;
  5659. }
  5660. }
  5661. // Initialize members.
  5662. for (const auto *Field : RD->fields()) {
  5663. // Anonymous bit-fields are not considered members of the class for
  5664. // purposes of aggregate initialization.
  5665. if (Field->isUnnamedBitfield())
  5666. continue;
  5667. LValue Subobject = This;
  5668. bool HaveInit = ElementNo < E->getNumInits();
  5669. // FIXME: Diagnostics here should point to the end of the initializer
  5670. // list, not the start.
  5671. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  5672. Subobject, Field, &Layout))
  5673. return false;
  5674. // Perform an implicit value-initialization for members beyond the end of
  5675. // the initializer list.
  5676. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  5677. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  5678. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5679. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5680. isa<CXXDefaultInitExpr>(Init));
  5681. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5682. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  5683. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  5684. FieldVal, Field))) {
  5685. if (!Info.noteFailure())
  5686. return false;
  5687. Success = false;
  5688. }
  5689. }
  5690. return Success;
  5691. }
  5692. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5693. QualType T) {
  5694. // Note that E's type is not necessarily the type of our class here; we might
  5695. // be initializing an array element instead.
  5696. const CXXConstructorDecl *FD = E->getConstructor();
  5697. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  5698. bool ZeroInit = E->requiresZeroInitialization();
  5699. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  5700. // If we've already performed zero-initialization, we're already done.
  5701. if (!Result.isUninit())
  5702. return true;
  5703. // We can get here in two different ways:
  5704. // 1) We're performing value-initialization, and should zero-initialize
  5705. // the object, or
  5706. // 2) We're performing default-initialization of an object with a trivial
  5707. // constexpr default constructor, in which case we should start the
  5708. // lifetimes of all the base subobjects (there can be no data member
  5709. // subobjects in this case) per [basic.life]p1.
  5710. // Either way, ZeroInitialization is appropriate.
  5711. return ZeroInitialization(E, T);
  5712. }
  5713. const FunctionDecl *Definition = nullptr;
  5714. auto Body = FD->getBody(Definition);
  5715. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5716. return false;
  5717. // Avoid materializing a temporary for an elidable copy/move constructor.
  5718. if (E->isElidable() && !ZeroInit)
  5719. if (const MaterializeTemporaryExpr *ME
  5720. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  5721. return Visit(ME->GetTemporaryExpr());
  5722. if (ZeroInit && !ZeroInitialization(E, T))
  5723. return false;
  5724. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5725. return HandleConstructorCall(E, This, Args,
  5726. cast<CXXConstructorDecl>(Definition), Info,
  5727. Result);
  5728. }
  5729. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  5730. const CXXInheritedCtorInitExpr *E) {
  5731. if (!Info.CurrentCall) {
  5732. assert(Info.checkingPotentialConstantExpression());
  5733. return false;
  5734. }
  5735. const CXXConstructorDecl *FD = E->getConstructor();
  5736. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  5737. return false;
  5738. const FunctionDecl *Definition = nullptr;
  5739. auto Body = FD->getBody(Definition);
  5740. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5741. return false;
  5742. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  5743. cast<CXXConstructorDecl>(Definition), Info,
  5744. Result);
  5745. }
  5746. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  5747. const CXXStdInitializerListExpr *E) {
  5748. const ConstantArrayType *ArrayType =
  5749. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  5750. LValue Array;
  5751. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  5752. return false;
  5753. // Get a pointer to the first element of the array.
  5754. Array.addArray(Info, E, ArrayType);
  5755. // FIXME: Perform the checks on the field types in SemaInit.
  5756. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  5757. RecordDecl::field_iterator Field = Record->field_begin();
  5758. if (Field == Record->field_end())
  5759. return Error(E);
  5760. // Start pointer.
  5761. if (!Field->getType()->isPointerType() ||
  5762. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5763. ArrayType->getElementType()))
  5764. return Error(E);
  5765. // FIXME: What if the initializer_list type has base classes, etc?
  5766. Result = APValue(APValue::UninitStruct(), 0, 2);
  5767. Array.moveInto(Result.getStructField(0));
  5768. if (++Field == Record->field_end())
  5769. return Error(E);
  5770. if (Field->getType()->isPointerType() &&
  5771. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5772. ArrayType->getElementType())) {
  5773. // End pointer.
  5774. if (!HandleLValueArrayAdjustment(Info, E, Array,
  5775. ArrayType->getElementType(),
  5776. ArrayType->getSize().getZExtValue()))
  5777. return false;
  5778. Array.moveInto(Result.getStructField(1));
  5779. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  5780. // Length.
  5781. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  5782. else
  5783. return Error(E);
  5784. if (++Field != Record->field_end())
  5785. return Error(E);
  5786. return true;
  5787. }
  5788. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  5789. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  5790. if (ClosureClass->isInvalidDecl()) return false;
  5791. if (Info.checkingPotentialConstantExpression()) return true;
  5792. const size_t NumFields =
  5793. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  5794. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  5795. E->capture_init_end()) &&
  5796. "The number of lambda capture initializers should equal the number of "
  5797. "fields within the closure type");
  5798. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  5799. // Iterate through all the lambda's closure object's fields and initialize
  5800. // them.
  5801. auto *CaptureInitIt = E->capture_init_begin();
  5802. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  5803. bool Success = true;
  5804. for (const auto *Field : ClosureClass->fields()) {
  5805. assert(CaptureInitIt != E->capture_init_end());
  5806. // Get the initializer for this field
  5807. Expr *const CurFieldInit = *CaptureInitIt++;
  5808. // If there is no initializer, either this is a VLA or an error has
  5809. // occurred.
  5810. if (!CurFieldInit)
  5811. return Error(E);
  5812. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5813. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  5814. if (!Info.keepEvaluatingAfterFailure())
  5815. return false;
  5816. Success = false;
  5817. }
  5818. ++CaptureIt;
  5819. }
  5820. return Success;
  5821. }
  5822. static bool EvaluateRecord(const Expr *E, const LValue &This,
  5823. APValue &Result, EvalInfo &Info) {
  5824. assert(E->isRValue() && E->getType()->isRecordType() &&
  5825. "can't evaluate expression as a record rvalue");
  5826. return RecordExprEvaluator(Info, This, Result).Visit(E);
  5827. }
  5828. //===----------------------------------------------------------------------===//
  5829. // Temporary Evaluation
  5830. //
  5831. // Temporaries are represented in the AST as rvalues, but generally behave like
  5832. // lvalues. The full-object of which the temporary is a subobject is implicitly
  5833. // materialized so that a reference can bind to it.
  5834. //===----------------------------------------------------------------------===//
  5835. namespace {
  5836. class TemporaryExprEvaluator
  5837. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  5838. public:
  5839. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  5840. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  5841. /// Visit an expression which constructs the value of this temporary.
  5842. bool VisitConstructExpr(const Expr *E) {
  5843. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  5844. return EvaluateInPlace(Value, Info, Result, E);
  5845. }
  5846. bool VisitCastExpr(const CastExpr *E) {
  5847. switch (E->getCastKind()) {
  5848. default:
  5849. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  5850. case CK_ConstructorConversion:
  5851. return VisitConstructExpr(E->getSubExpr());
  5852. }
  5853. }
  5854. bool VisitInitListExpr(const InitListExpr *E) {
  5855. return VisitConstructExpr(E);
  5856. }
  5857. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5858. return VisitConstructExpr(E);
  5859. }
  5860. bool VisitCallExpr(const CallExpr *E) {
  5861. return VisitConstructExpr(E);
  5862. }
  5863. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  5864. return VisitConstructExpr(E);
  5865. }
  5866. bool VisitLambdaExpr(const LambdaExpr *E) {
  5867. return VisitConstructExpr(E);
  5868. }
  5869. };
  5870. } // end anonymous namespace
  5871. /// Evaluate an expression of record type as a temporary.
  5872. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  5873. assert(E->isRValue() && E->getType()->isRecordType());
  5874. return TemporaryExprEvaluator(Info, Result).Visit(E);
  5875. }
  5876. //===----------------------------------------------------------------------===//
  5877. // Vector Evaluation
  5878. //===----------------------------------------------------------------------===//
  5879. namespace {
  5880. class VectorExprEvaluator
  5881. : public ExprEvaluatorBase<VectorExprEvaluator> {
  5882. APValue &Result;
  5883. public:
  5884. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  5885. : ExprEvaluatorBaseTy(info), Result(Result) {}
  5886. bool Success(ArrayRef<APValue> V, const Expr *E) {
  5887. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  5888. // FIXME: remove this APValue copy.
  5889. Result = APValue(V.data(), V.size());
  5890. return true;
  5891. }
  5892. bool Success(const APValue &V, const Expr *E) {
  5893. assert(V.isVector());
  5894. Result = V;
  5895. return true;
  5896. }
  5897. bool ZeroInitialization(const Expr *E);
  5898. bool VisitUnaryReal(const UnaryOperator *E)
  5899. { return Visit(E->getSubExpr()); }
  5900. bool VisitCastExpr(const CastExpr* E);
  5901. bool VisitInitListExpr(const InitListExpr *E);
  5902. bool VisitUnaryImag(const UnaryOperator *E);
  5903. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  5904. // binary comparisons, binary and/or/xor,
  5905. // shufflevector, ExtVectorElementExpr
  5906. };
  5907. } // end anonymous namespace
  5908. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  5909. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  5910. return VectorExprEvaluator(Info, Result).Visit(E);
  5911. }
  5912. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5913. const VectorType *VTy = E->getType()->castAs<VectorType>();
  5914. unsigned NElts = VTy->getNumElements();
  5915. const Expr *SE = E->getSubExpr();
  5916. QualType SETy = SE->getType();
  5917. switch (E->getCastKind()) {
  5918. case CK_VectorSplat: {
  5919. APValue Val = APValue();
  5920. if (SETy->isIntegerType()) {
  5921. APSInt IntResult;
  5922. if (!EvaluateInteger(SE, IntResult, Info))
  5923. return false;
  5924. Val = APValue(std::move(IntResult));
  5925. } else if (SETy->isRealFloatingType()) {
  5926. APFloat FloatResult(0.0);
  5927. if (!EvaluateFloat(SE, FloatResult, Info))
  5928. return false;
  5929. Val = APValue(std::move(FloatResult));
  5930. } else {
  5931. return Error(E);
  5932. }
  5933. // Splat and create vector APValue.
  5934. SmallVector<APValue, 4> Elts(NElts, Val);
  5935. return Success(Elts, E);
  5936. }
  5937. case CK_BitCast: {
  5938. // Evaluate the operand into an APInt we can extract from.
  5939. llvm::APInt SValInt;
  5940. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  5941. return false;
  5942. // Extract the elements
  5943. QualType EltTy = VTy->getElementType();
  5944. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  5945. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  5946. SmallVector<APValue, 4> Elts;
  5947. if (EltTy->isRealFloatingType()) {
  5948. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  5949. unsigned FloatEltSize = EltSize;
  5950. if (&Sem == &APFloat::x87DoubleExtended())
  5951. FloatEltSize = 80;
  5952. for (unsigned i = 0; i < NElts; i++) {
  5953. llvm::APInt Elt;
  5954. if (BigEndian)
  5955. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  5956. else
  5957. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  5958. Elts.push_back(APValue(APFloat(Sem, Elt)));
  5959. }
  5960. } else if (EltTy->isIntegerType()) {
  5961. for (unsigned i = 0; i < NElts; i++) {
  5962. llvm::APInt Elt;
  5963. if (BigEndian)
  5964. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  5965. else
  5966. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  5967. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  5968. }
  5969. } else {
  5970. return Error(E);
  5971. }
  5972. return Success(Elts, E);
  5973. }
  5974. default:
  5975. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5976. }
  5977. }
  5978. bool
  5979. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5980. const VectorType *VT = E->getType()->castAs<VectorType>();
  5981. unsigned NumInits = E->getNumInits();
  5982. unsigned NumElements = VT->getNumElements();
  5983. QualType EltTy = VT->getElementType();
  5984. SmallVector<APValue, 4> Elements;
  5985. // The number of initializers can be less than the number of
  5986. // vector elements. For OpenCL, this can be due to nested vector
  5987. // initialization. For GCC compatibility, missing trailing elements
  5988. // should be initialized with zeroes.
  5989. unsigned CountInits = 0, CountElts = 0;
  5990. while (CountElts < NumElements) {
  5991. // Handle nested vector initialization.
  5992. if (CountInits < NumInits
  5993. && E->getInit(CountInits)->getType()->isVectorType()) {
  5994. APValue v;
  5995. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  5996. return Error(E);
  5997. unsigned vlen = v.getVectorLength();
  5998. for (unsigned j = 0; j < vlen; j++)
  5999. Elements.push_back(v.getVectorElt(j));
  6000. CountElts += vlen;
  6001. } else if (EltTy->isIntegerType()) {
  6002. llvm::APSInt sInt(32);
  6003. if (CountInits < NumInits) {
  6004. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  6005. return false;
  6006. } else // trailing integer zero.
  6007. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  6008. Elements.push_back(APValue(sInt));
  6009. CountElts++;
  6010. } else {
  6011. llvm::APFloat f(0.0);
  6012. if (CountInits < NumInits) {
  6013. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  6014. return false;
  6015. } else // trailing float zero.
  6016. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  6017. Elements.push_back(APValue(f));
  6018. CountElts++;
  6019. }
  6020. CountInits++;
  6021. }
  6022. return Success(Elements, E);
  6023. }
  6024. bool
  6025. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  6026. const VectorType *VT = E->getType()->getAs<VectorType>();
  6027. QualType EltTy = VT->getElementType();
  6028. APValue ZeroElement;
  6029. if (EltTy->isIntegerType())
  6030. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  6031. else
  6032. ZeroElement =
  6033. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  6034. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  6035. return Success(Elements, E);
  6036. }
  6037. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6038. VisitIgnoredValue(E->getSubExpr());
  6039. return ZeroInitialization(E);
  6040. }
  6041. //===----------------------------------------------------------------------===//
  6042. // Array Evaluation
  6043. //===----------------------------------------------------------------------===//
  6044. namespace {
  6045. class ArrayExprEvaluator
  6046. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  6047. const LValue &This;
  6048. APValue &Result;
  6049. public:
  6050. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  6051. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  6052. bool Success(const APValue &V, const Expr *E) {
  6053. assert((V.isArray() || V.isLValue()) &&
  6054. "expected array or string literal");
  6055. Result = V;
  6056. return true;
  6057. }
  6058. bool ZeroInitialization(const Expr *E) {
  6059. const ConstantArrayType *CAT =
  6060. Info.Ctx.getAsConstantArrayType(E->getType());
  6061. if (!CAT)
  6062. return Error(E);
  6063. Result = APValue(APValue::UninitArray(), 0,
  6064. CAT->getSize().getZExtValue());
  6065. if (!Result.hasArrayFiller()) return true;
  6066. // Zero-initialize all elements.
  6067. LValue Subobject = This;
  6068. Subobject.addArray(Info, E, CAT);
  6069. ImplicitValueInitExpr VIE(CAT->getElementType());
  6070. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  6071. }
  6072. bool VisitCallExpr(const CallExpr *E) {
  6073. return handleCallExpr(E, Result, &This);
  6074. }
  6075. bool VisitInitListExpr(const InitListExpr *E);
  6076. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  6077. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  6078. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  6079. const LValue &Subobject,
  6080. APValue *Value, QualType Type);
  6081. };
  6082. } // end anonymous namespace
  6083. static bool EvaluateArray(const Expr *E, const LValue &This,
  6084. APValue &Result, EvalInfo &Info) {
  6085. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  6086. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  6087. }
  6088. // Return true iff the given array filler may depend on the element index.
  6089. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  6090. // For now, just whitelist non-class value-initialization and initialization
  6091. // lists comprised of them.
  6092. if (isa<ImplicitValueInitExpr>(FillerExpr))
  6093. return false;
  6094. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  6095. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  6096. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  6097. return true;
  6098. }
  6099. return false;
  6100. }
  6101. return true;
  6102. }
  6103. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6104. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  6105. if (!CAT)
  6106. return Error(E);
  6107. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  6108. // an appropriately-typed string literal enclosed in braces.
  6109. if (E->isStringLiteralInit()) {
  6110. LValue LV;
  6111. if (!EvaluateLValue(E->getInit(0), LV, Info))
  6112. return false;
  6113. APValue Val;
  6114. LV.moveInto(Val);
  6115. return Success(Val, E);
  6116. }
  6117. bool Success = true;
  6118. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  6119. "zero-initialized array shouldn't have any initialized elts");
  6120. APValue Filler;
  6121. if (Result.isArray() && Result.hasArrayFiller())
  6122. Filler = Result.getArrayFiller();
  6123. unsigned NumEltsToInit = E->getNumInits();
  6124. unsigned NumElts = CAT->getSize().getZExtValue();
  6125. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  6126. // If the initializer might depend on the array index, run it for each
  6127. // array element.
  6128. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  6129. NumEltsToInit = NumElts;
  6130. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  6131. << NumEltsToInit << ".\n");
  6132. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  6133. // If the array was previously zero-initialized, preserve the
  6134. // zero-initialized values.
  6135. if (!Filler.isUninit()) {
  6136. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  6137. Result.getArrayInitializedElt(I) = Filler;
  6138. if (Result.hasArrayFiller())
  6139. Result.getArrayFiller() = Filler;
  6140. }
  6141. LValue Subobject = This;
  6142. Subobject.addArray(Info, E, CAT);
  6143. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  6144. const Expr *Init =
  6145. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  6146. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6147. Info, Subobject, Init) ||
  6148. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  6149. CAT->getElementType(), 1)) {
  6150. if (!Info.noteFailure())
  6151. return false;
  6152. Success = false;
  6153. }
  6154. }
  6155. if (!Result.hasArrayFiller())
  6156. return Success;
  6157. // If we get here, we have a trivial filler, which we can just evaluate
  6158. // once and splat over the rest of the array elements.
  6159. assert(FillerExpr && "no array filler for incomplete init list");
  6160. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  6161. FillerExpr) && Success;
  6162. }
  6163. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  6164. if (E->getCommonExpr() &&
  6165. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  6166. Info, E->getCommonExpr()->getSourceExpr()))
  6167. return false;
  6168. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  6169. uint64_t Elements = CAT->getSize().getZExtValue();
  6170. Result = APValue(APValue::UninitArray(), Elements, Elements);
  6171. LValue Subobject = This;
  6172. Subobject.addArray(Info, E, CAT);
  6173. bool Success = true;
  6174. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  6175. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6176. Info, Subobject, E->getSubExpr()) ||
  6177. !HandleLValueArrayAdjustment(Info, E, Subobject,
  6178. CAT->getElementType(), 1)) {
  6179. if (!Info.noteFailure())
  6180. return false;
  6181. Success = false;
  6182. }
  6183. }
  6184. return Success;
  6185. }
  6186. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6187. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  6188. }
  6189. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6190. const LValue &Subobject,
  6191. APValue *Value,
  6192. QualType Type) {
  6193. bool HadZeroInit = !Value->isUninit();
  6194. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  6195. unsigned N = CAT->getSize().getZExtValue();
  6196. // Preserve the array filler if we had prior zero-initialization.
  6197. APValue Filler =
  6198. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  6199. : APValue();
  6200. *Value = APValue(APValue::UninitArray(), N, N);
  6201. if (HadZeroInit)
  6202. for (unsigned I = 0; I != N; ++I)
  6203. Value->getArrayInitializedElt(I) = Filler;
  6204. // Initialize the elements.
  6205. LValue ArrayElt = Subobject;
  6206. ArrayElt.addArray(Info, E, CAT);
  6207. for (unsigned I = 0; I != N; ++I)
  6208. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  6209. CAT->getElementType()) ||
  6210. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  6211. CAT->getElementType(), 1))
  6212. return false;
  6213. return true;
  6214. }
  6215. if (!Type->isRecordType())
  6216. return Error(E);
  6217. return RecordExprEvaluator(Info, Subobject, *Value)
  6218. .VisitCXXConstructExpr(E, Type);
  6219. }
  6220. //===----------------------------------------------------------------------===//
  6221. // Integer Evaluation
  6222. //
  6223. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  6224. // types and back in constant folding. Integer values are thus represented
  6225. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  6226. //===----------------------------------------------------------------------===//
  6227. namespace {
  6228. class IntExprEvaluator
  6229. : public ExprEvaluatorBase<IntExprEvaluator> {
  6230. APValue &Result;
  6231. public:
  6232. IntExprEvaluator(EvalInfo &info, APValue &result)
  6233. : ExprEvaluatorBaseTy(info), Result(result) {}
  6234. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6235. assert(E->getType()->isIntegralOrEnumerationType() &&
  6236. "Invalid evaluation result.");
  6237. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  6238. "Invalid evaluation result.");
  6239. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6240. "Invalid evaluation result.");
  6241. Result = APValue(SI);
  6242. return true;
  6243. }
  6244. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6245. return Success(SI, E, Result);
  6246. }
  6247. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6248. assert(E->getType()->isIntegralOrEnumerationType() &&
  6249. "Invalid evaluation result.");
  6250. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6251. "Invalid evaluation result.");
  6252. Result = APValue(APSInt(I));
  6253. Result.getInt().setIsUnsigned(
  6254. E->getType()->isUnsignedIntegerOrEnumerationType());
  6255. return true;
  6256. }
  6257. bool Success(const llvm::APInt &I, const Expr *E) {
  6258. return Success(I, E, Result);
  6259. }
  6260. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6261. assert(E->getType()->isIntegralOrEnumerationType() &&
  6262. "Invalid evaluation result.");
  6263. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6264. return true;
  6265. }
  6266. bool Success(uint64_t Value, const Expr *E) {
  6267. return Success(Value, E, Result);
  6268. }
  6269. bool Success(CharUnits Size, const Expr *E) {
  6270. return Success(Size.getQuantity(), E);
  6271. }
  6272. bool Success(const APValue &V, const Expr *E) {
  6273. if (V.isLValue() || V.isAddrLabelDiff()) {
  6274. Result = V;
  6275. return true;
  6276. }
  6277. return Success(V.getInt(), E);
  6278. }
  6279. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6280. //===--------------------------------------------------------------------===//
  6281. // Visitor Methods
  6282. //===--------------------------------------------------------------------===//
  6283. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  6284. return Success(E->getValue(), E);
  6285. }
  6286. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  6287. return Success(E->getValue(), E);
  6288. }
  6289. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  6290. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  6291. if (CheckReferencedDecl(E, E->getDecl()))
  6292. return true;
  6293. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  6294. }
  6295. bool VisitMemberExpr(const MemberExpr *E) {
  6296. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  6297. VisitIgnoredBaseExpression(E->getBase());
  6298. return true;
  6299. }
  6300. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  6301. }
  6302. bool VisitCallExpr(const CallExpr *E);
  6303. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6304. bool VisitBinaryOperator(const BinaryOperator *E);
  6305. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  6306. bool VisitUnaryOperator(const UnaryOperator *E);
  6307. bool VisitCastExpr(const CastExpr* E);
  6308. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  6309. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  6310. return Success(E->getValue(), E);
  6311. }
  6312. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  6313. return Success(E->getValue(), E);
  6314. }
  6315. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  6316. if (Info.ArrayInitIndex == uint64_t(-1)) {
  6317. // We were asked to evaluate this subexpression independent of the
  6318. // enclosing ArrayInitLoopExpr. We can't do that.
  6319. Info.FFDiag(E);
  6320. return false;
  6321. }
  6322. return Success(Info.ArrayInitIndex, E);
  6323. }
  6324. // Note, GNU defines __null as an integer, not a pointer.
  6325. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  6326. return ZeroInitialization(E);
  6327. }
  6328. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  6329. return Success(E->getValue(), E);
  6330. }
  6331. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  6332. return Success(E->getValue(), E);
  6333. }
  6334. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  6335. return Success(E->getValue(), E);
  6336. }
  6337. bool VisitUnaryReal(const UnaryOperator *E);
  6338. bool VisitUnaryImag(const UnaryOperator *E);
  6339. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  6340. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  6341. // FIXME: Missing: array subscript of vector, member of vector
  6342. };
  6343. class FixedPointExprEvaluator
  6344. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  6345. APValue &Result;
  6346. public:
  6347. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  6348. : ExprEvaluatorBaseTy(info), Result(result) {}
  6349. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6350. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6351. assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
  6352. "Invalid evaluation result.");
  6353. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6354. "Invalid evaluation result.");
  6355. Result = APValue(SI);
  6356. return true;
  6357. }
  6358. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6359. return Success(SI, E, Result);
  6360. }
  6361. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6362. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6363. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6364. "Invalid evaluation result.");
  6365. Result = APValue(APSInt(I));
  6366. Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
  6367. return true;
  6368. }
  6369. bool Success(const llvm::APInt &I, const Expr *E) {
  6370. return Success(I, E, Result);
  6371. }
  6372. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6373. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6374. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6375. return true;
  6376. }
  6377. bool Success(uint64_t Value, const Expr *E) {
  6378. return Success(Value, E, Result);
  6379. }
  6380. bool Success(CharUnits Size, const Expr *E) {
  6381. return Success(Size.getQuantity(), E);
  6382. }
  6383. bool Success(const APValue &V, const Expr *E) {
  6384. if (V.isLValue() || V.isAddrLabelDiff()) {
  6385. Result = V;
  6386. return true;
  6387. }
  6388. return Success(V.getInt(), E);
  6389. }
  6390. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6391. //===--------------------------------------------------------------------===//
  6392. // Visitor Methods
  6393. //===--------------------------------------------------------------------===//
  6394. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  6395. return Success(E->getValue(), E);
  6396. }
  6397. bool VisitUnaryOperator(const UnaryOperator *E);
  6398. };
  6399. } // end anonymous namespace
  6400. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  6401. /// produce either the integer value or a pointer.
  6402. ///
  6403. /// GCC has a heinous extension which folds casts between pointer types and
  6404. /// pointer-sized integral types. We support this by allowing the evaluation of
  6405. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  6406. /// Some simple arithmetic on such values is supported (they are treated much
  6407. /// like char*).
  6408. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  6409. EvalInfo &Info) {
  6410. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  6411. return IntExprEvaluator(Info, Result).Visit(E);
  6412. }
  6413. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  6414. APValue Val;
  6415. if (!EvaluateIntegerOrLValue(E, Val, Info))
  6416. return false;
  6417. if (!Val.isInt()) {
  6418. // FIXME: It would be better to produce the diagnostic for casting
  6419. // a pointer to an integer.
  6420. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6421. return false;
  6422. }
  6423. Result = Val.getInt();
  6424. return true;
  6425. }
  6426. /// Check whether the given declaration can be directly converted to an integral
  6427. /// rvalue. If not, no diagnostic is produced; there are other things we can
  6428. /// try.
  6429. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  6430. // Enums are integer constant exprs.
  6431. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  6432. // Check for signedness/width mismatches between E type and ECD value.
  6433. bool SameSign = (ECD->getInitVal().isSigned()
  6434. == E->getType()->isSignedIntegerOrEnumerationType());
  6435. bool SameWidth = (ECD->getInitVal().getBitWidth()
  6436. == Info.Ctx.getIntWidth(E->getType()));
  6437. if (SameSign && SameWidth)
  6438. return Success(ECD->getInitVal(), E);
  6439. else {
  6440. // Get rid of mismatch (otherwise Success assertions will fail)
  6441. // by computing a new value matching the type of E.
  6442. llvm::APSInt Val = ECD->getInitVal();
  6443. if (!SameSign)
  6444. Val.setIsSigned(!ECD->getInitVal().isSigned());
  6445. if (!SameWidth)
  6446. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  6447. return Success(Val, E);
  6448. }
  6449. }
  6450. return false;
  6451. }
  6452. /// Values returned by __builtin_classify_type, chosen to match the values
  6453. /// produced by GCC's builtin.
  6454. enum class GCCTypeClass {
  6455. None = -1,
  6456. Void = 0,
  6457. Integer = 1,
  6458. // GCC reserves 2 for character types, but instead classifies them as
  6459. // integers.
  6460. Enum = 3,
  6461. Bool = 4,
  6462. Pointer = 5,
  6463. // GCC reserves 6 for references, but appears to never use it (because
  6464. // expressions never have reference type, presumably).
  6465. PointerToDataMember = 7,
  6466. RealFloat = 8,
  6467. Complex = 9,
  6468. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  6469. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6470. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  6471. // uses 12 for that purpose, same as for a class or struct. Maybe it
  6472. // internally implements a pointer to member as a struct? Who knows.
  6473. PointerToMemberFunction = 12, // Not a bug, see above.
  6474. ClassOrStruct = 12,
  6475. Union = 13,
  6476. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  6477. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6478. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  6479. // literals.
  6480. };
  6481. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6482. /// as GCC.
  6483. static GCCTypeClass
  6484. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  6485. assert(!T->isDependentType() && "unexpected dependent type");
  6486. QualType CanTy = T.getCanonicalType();
  6487. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  6488. switch (CanTy->getTypeClass()) {
  6489. #define TYPE(ID, BASE)
  6490. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6491. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  6492. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6493. #include "clang/AST/TypeNodes.def"
  6494. case Type::Auto:
  6495. case Type::DeducedTemplateSpecialization:
  6496. llvm_unreachable("unexpected non-canonical or dependent type");
  6497. case Type::Builtin:
  6498. switch (BT->getKind()) {
  6499. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  6500. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  6501. case BuiltinType::ID: return GCCTypeClass::Integer;
  6502. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  6503. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  6504. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  6505. case BuiltinType::ID: break;
  6506. #include "clang/AST/BuiltinTypes.def"
  6507. case BuiltinType::Void:
  6508. return GCCTypeClass::Void;
  6509. case BuiltinType::Bool:
  6510. return GCCTypeClass::Bool;
  6511. case BuiltinType::Char_U:
  6512. case BuiltinType::UChar:
  6513. case BuiltinType::WChar_U:
  6514. case BuiltinType::Char8:
  6515. case BuiltinType::Char16:
  6516. case BuiltinType::Char32:
  6517. case BuiltinType::UShort:
  6518. case BuiltinType::UInt:
  6519. case BuiltinType::ULong:
  6520. case BuiltinType::ULongLong:
  6521. case BuiltinType::UInt128:
  6522. return GCCTypeClass::Integer;
  6523. case BuiltinType::UShortAccum:
  6524. case BuiltinType::UAccum:
  6525. case BuiltinType::ULongAccum:
  6526. case BuiltinType::UShortFract:
  6527. case BuiltinType::UFract:
  6528. case BuiltinType::ULongFract:
  6529. case BuiltinType::SatUShortAccum:
  6530. case BuiltinType::SatUAccum:
  6531. case BuiltinType::SatULongAccum:
  6532. case BuiltinType::SatUShortFract:
  6533. case BuiltinType::SatUFract:
  6534. case BuiltinType::SatULongFract:
  6535. return GCCTypeClass::None;
  6536. case BuiltinType::NullPtr:
  6537. case BuiltinType::ObjCId:
  6538. case BuiltinType::ObjCClass:
  6539. case BuiltinType::ObjCSel:
  6540. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6541. case BuiltinType::Id:
  6542. #include "clang/Basic/OpenCLImageTypes.def"
  6543. case BuiltinType::OCLSampler:
  6544. case BuiltinType::OCLEvent:
  6545. case BuiltinType::OCLClkEvent:
  6546. case BuiltinType::OCLQueue:
  6547. case BuiltinType::OCLReserveID:
  6548. return GCCTypeClass::None;
  6549. case BuiltinType::Dependent:
  6550. llvm_unreachable("unexpected dependent type");
  6551. };
  6552. llvm_unreachable("unexpected placeholder type");
  6553. case Type::Enum:
  6554. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  6555. case Type::Pointer:
  6556. case Type::ConstantArray:
  6557. case Type::VariableArray:
  6558. case Type::IncompleteArray:
  6559. case Type::FunctionNoProto:
  6560. case Type::FunctionProto:
  6561. return GCCTypeClass::Pointer;
  6562. case Type::MemberPointer:
  6563. return CanTy->isMemberDataPointerType()
  6564. ? GCCTypeClass::PointerToDataMember
  6565. : GCCTypeClass::PointerToMemberFunction;
  6566. case Type::Complex:
  6567. return GCCTypeClass::Complex;
  6568. case Type::Record:
  6569. return CanTy->isUnionType() ? GCCTypeClass::Union
  6570. : GCCTypeClass::ClassOrStruct;
  6571. case Type::Atomic:
  6572. // GCC classifies _Atomic T the same as T.
  6573. return EvaluateBuiltinClassifyType(
  6574. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  6575. case Type::BlockPointer:
  6576. case Type::Vector:
  6577. case Type::ExtVector:
  6578. case Type::ObjCObject:
  6579. case Type::ObjCInterface:
  6580. case Type::ObjCObjectPointer:
  6581. case Type::Pipe:
  6582. // GCC classifies vectors as None. We follow its lead and classify all
  6583. // other types that don't fit into the regular classification the same way.
  6584. return GCCTypeClass::None;
  6585. case Type::LValueReference:
  6586. case Type::RValueReference:
  6587. llvm_unreachable("invalid type for expression");
  6588. }
  6589. llvm_unreachable("unexpected type class");
  6590. }
  6591. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6592. /// as GCC.
  6593. static GCCTypeClass
  6594. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  6595. // If no argument was supplied, default to None. This isn't
  6596. // ideal, however it is what gcc does.
  6597. if (E->getNumArgs() == 0)
  6598. return GCCTypeClass::None;
  6599. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  6600. // being an ICE, but still folds it to a constant using the type of the first
  6601. // argument.
  6602. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  6603. }
  6604. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  6605. /// __builtin_constant_p when applied to the given lvalue.
  6606. ///
  6607. /// An lvalue is only "constant" if it is a pointer or reference to the first
  6608. /// character of a string literal.
  6609. template<typename LValue>
  6610. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  6611. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  6612. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  6613. }
  6614. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  6615. /// GCC as we can manage.
  6616. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  6617. QualType ArgType = Arg->getType();
  6618. // __builtin_constant_p always has one operand. The rules which gcc follows
  6619. // are not precisely documented, but are as follows:
  6620. //
  6621. // - If the operand is of integral, floating, complex or enumeration type,
  6622. // and can be folded to a known value of that type, it returns 1.
  6623. // - If the operand and can be folded to a pointer to the first character
  6624. // of a string literal (or such a pointer cast to an integral type), it
  6625. // returns 1.
  6626. //
  6627. // Otherwise, it returns 0.
  6628. //
  6629. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  6630. // its support for this does not currently work.
  6631. if (ArgType->isIntegralOrEnumerationType()) {
  6632. Expr::EvalResult Result;
  6633. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  6634. return false;
  6635. APValue &V = Result.Val;
  6636. if (V.getKind() == APValue::Int)
  6637. return true;
  6638. if (V.getKind() == APValue::LValue)
  6639. return EvaluateBuiltinConstantPForLValue(V);
  6640. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  6641. return Arg->isEvaluatable(Ctx);
  6642. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  6643. LValue LV;
  6644. Expr::EvalStatus Status;
  6645. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  6646. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  6647. : EvaluatePointer(Arg, LV, Info)) &&
  6648. !Status.HasSideEffects)
  6649. return EvaluateBuiltinConstantPForLValue(LV);
  6650. }
  6651. // Anything else isn't considered to be sufficiently constant.
  6652. return false;
  6653. }
  6654. /// Retrieves the "underlying object type" of the given expression,
  6655. /// as used by __builtin_object_size.
  6656. static QualType getObjectType(APValue::LValueBase B) {
  6657. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  6658. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  6659. return VD->getType();
  6660. } else if (const Expr *E = B.get<const Expr*>()) {
  6661. if (isa<CompoundLiteralExpr>(E))
  6662. return E->getType();
  6663. }
  6664. return QualType();
  6665. }
  6666. /// A more selective version of E->IgnoreParenCasts for
  6667. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  6668. /// to change the type of E.
  6669. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  6670. ///
  6671. /// Always returns an RValue with a pointer representation.
  6672. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  6673. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6674. auto *NoParens = E->IgnoreParens();
  6675. auto *Cast = dyn_cast<CastExpr>(NoParens);
  6676. if (Cast == nullptr)
  6677. return NoParens;
  6678. // We only conservatively allow a few kinds of casts, because this code is
  6679. // inherently a simple solution that seeks to support the common case.
  6680. auto CastKind = Cast->getCastKind();
  6681. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  6682. CastKind != CK_AddressSpaceConversion)
  6683. return NoParens;
  6684. auto *SubExpr = Cast->getSubExpr();
  6685. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  6686. return NoParens;
  6687. return ignorePointerCastsAndParens(SubExpr);
  6688. }
  6689. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  6690. /// record layout. e.g.
  6691. /// struct { struct { int a, b; } fst, snd; } obj;
  6692. /// obj.fst // no
  6693. /// obj.snd // yes
  6694. /// obj.fst.a // no
  6695. /// obj.fst.b // no
  6696. /// obj.snd.a // no
  6697. /// obj.snd.b // yes
  6698. ///
  6699. /// Please note: this function is specialized for how __builtin_object_size
  6700. /// views "objects".
  6701. ///
  6702. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  6703. /// correct result, it will always return true.
  6704. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  6705. assert(!LVal.Designator.Invalid);
  6706. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  6707. const RecordDecl *Parent = FD->getParent();
  6708. Invalid = Parent->isInvalidDecl();
  6709. if (Invalid || Parent->isUnion())
  6710. return true;
  6711. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  6712. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  6713. };
  6714. auto &Base = LVal.getLValueBase();
  6715. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  6716. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  6717. bool Invalid;
  6718. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6719. return Invalid;
  6720. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  6721. for (auto *FD : IFD->chain()) {
  6722. bool Invalid;
  6723. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  6724. return Invalid;
  6725. }
  6726. }
  6727. }
  6728. unsigned I = 0;
  6729. QualType BaseType = getType(Base);
  6730. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  6731. // If we don't know the array bound, conservatively assume we're looking at
  6732. // the final array element.
  6733. ++I;
  6734. if (BaseType->isIncompleteArrayType())
  6735. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  6736. else
  6737. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  6738. }
  6739. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  6740. const auto &Entry = LVal.Designator.Entries[I];
  6741. if (BaseType->isArrayType()) {
  6742. // Because __builtin_object_size treats arrays as objects, we can ignore
  6743. // the index iff this is the last array in the Designator.
  6744. if (I + 1 == E)
  6745. return true;
  6746. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  6747. uint64_t Index = Entry.ArrayIndex;
  6748. if (Index + 1 != CAT->getSize())
  6749. return false;
  6750. BaseType = CAT->getElementType();
  6751. } else if (BaseType->isAnyComplexType()) {
  6752. const auto *CT = BaseType->castAs<ComplexType>();
  6753. uint64_t Index = Entry.ArrayIndex;
  6754. if (Index != 1)
  6755. return false;
  6756. BaseType = CT->getElementType();
  6757. } else if (auto *FD = getAsField(Entry)) {
  6758. bool Invalid;
  6759. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6760. return Invalid;
  6761. BaseType = FD->getType();
  6762. } else {
  6763. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  6764. return false;
  6765. }
  6766. }
  6767. return true;
  6768. }
  6769. /// Tests to see if the LValue has a user-specified designator (that isn't
  6770. /// necessarily valid). Note that this always returns 'true' if the LValue has
  6771. /// an unsized array as its first designator entry, because there's currently no
  6772. /// way to tell if the user typed *foo or foo[0].
  6773. static bool refersToCompleteObject(const LValue &LVal) {
  6774. if (LVal.Designator.Invalid)
  6775. return false;
  6776. if (!LVal.Designator.Entries.empty())
  6777. return LVal.Designator.isMostDerivedAnUnsizedArray();
  6778. if (!LVal.InvalidBase)
  6779. return true;
  6780. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  6781. // the LValueBase.
  6782. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  6783. return !E || !isa<MemberExpr>(E);
  6784. }
  6785. /// Attempts to detect a user writing into a piece of memory that's impossible
  6786. /// to figure out the size of by just using types.
  6787. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  6788. const SubobjectDesignator &Designator = LVal.Designator;
  6789. // Notes:
  6790. // - Users can only write off of the end when we have an invalid base. Invalid
  6791. // bases imply we don't know where the memory came from.
  6792. // - We used to be a bit more aggressive here; we'd only be conservative if
  6793. // the array at the end was flexible, or if it had 0 or 1 elements. This
  6794. // broke some common standard library extensions (PR30346), but was
  6795. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  6796. // with some sort of whitelist. OTOH, it seems that GCC is always
  6797. // conservative with the last element in structs (if it's an array), so our
  6798. // current behavior is more compatible than a whitelisting approach would
  6799. // be.
  6800. return LVal.InvalidBase &&
  6801. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  6802. Designator.MostDerivedIsArrayElement &&
  6803. isDesignatorAtObjectEnd(Ctx, LVal);
  6804. }
  6805. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  6806. /// Fails if the conversion would cause loss of precision.
  6807. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  6808. CharUnits &Result) {
  6809. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  6810. if (Int.ugt(CharUnitsMax))
  6811. return false;
  6812. Result = CharUnits::fromQuantity(Int.getZExtValue());
  6813. return true;
  6814. }
  6815. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  6816. /// determine how many bytes exist from the beginning of the object to either
  6817. /// the end of the current subobject, or the end of the object itself, depending
  6818. /// on what the LValue looks like + the value of Type.
  6819. ///
  6820. /// If this returns false, the value of Result is undefined.
  6821. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  6822. unsigned Type, const LValue &LVal,
  6823. CharUnits &EndOffset) {
  6824. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  6825. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  6826. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  6827. return false;
  6828. return HandleSizeof(Info, ExprLoc, Ty, Result);
  6829. };
  6830. // We want to evaluate the size of the entire object. This is a valid fallback
  6831. // for when Type=1 and the designator is invalid, because we're asked for an
  6832. // upper-bound.
  6833. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  6834. // Type=3 wants a lower bound, so we can't fall back to this.
  6835. if (Type == 3 && !DetermineForCompleteObject)
  6836. return false;
  6837. llvm::APInt APEndOffset;
  6838. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6839. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  6840. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  6841. if (LVal.InvalidBase)
  6842. return false;
  6843. QualType BaseTy = getObjectType(LVal.getLValueBase());
  6844. return CheckedHandleSizeof(BaseTy, EndOffset);
  6845. }
  6846. // We want to evaluate the size of a subobject.
  6847. const SubobjectDesignator &Designator = LVal.Designator;
  6848. // The following is a moderately common idiom in C:
  6849. //
  6850. // struct Foo { int a; char c[1]; };
  6851. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  6852. // strcpy(&F->c[0], Bar);
  6853. //
  6854. // In order to not break too much legacy code, we need to support it.
  6855. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  6856. // If we can resolve this to an alloc_size call, we can hand that back,
  6857. // because we know for certain how many bytes there are to write to.
  6858. llvm::APInt APEndOffset;
  6859. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6860. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  6861. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  6862. // If we cannot determine the size of the initial allocation, then we can't
  6863. // given an accurate upper-bound. However, we are still able to give
  6864. // conservative lower-bounds for Type=3.
  6865. if (Type == 1)
  6866. return false;
  6867. }
  6868. CharUnits BytesPerElem;
  6869. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  6870. return false;
  6871. // According to the GCC documentation, we want the size of the subobject
  6872. // denoted by the pointer. But that's not quite right -- what we actually
  6873. // want is the size of the immediately-enclosing array, if there is one.
  6874. int64_t ElemsRemaining;
  6875. if (Designator.MostDerivedIsArrayElement &&
  6876. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  6877. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  6878. uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
  6879. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  6880. } else {
  6881. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  6882. }
  6883. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  6884. return true;
  6885. }
  6886. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  6887. /// returns true and stores the result in @p Size.
  6888. ///
  6889. /// If @p WasError is non-null, this will report whether the failure to evaluate
  6890. /// is to be treated as an Error in IntExprEvaluator.
  6891. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  6892. EvalInfo &Info, uint64_t &Size) {
  6893. // Determine the denoted object.
  6894. LValue LVal;
  6895. {
  6896. // The operand of __builtin_object_size is never evaluated for side-effects.
  6897. // If there are any, but we can determine the pointed-to object anyway, then
  6898. // ignore the side-effects.
  6899. SpeculativeEvaluationRAII SpeculativeEval(Info);
  6900. FoldOffsetRAII Fold(Info);
  6901. if (E->isGLValue()) {
  6902. // It's possible for us to be given GLValues if we're called via
  6903. // Expr::tryEvaluateObjectSize.
  6904. APValue RVal;
  6905. if (!EvaluateAsRValue(Info, E, RVal))
  6906. return false;
  6907. LVal.setFrom(Info.Ctx, RVal);
  6908. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  6909. /*InvalidBaseOK=*/true))
  6910. return false;
  6911. }
  6912. // If we point to before the start of the object, there are no accessible
  6913. // bytes.
  6914. if (LVal.getLValueOffset().isNegative()) {
  6915. Size = 0;
  6916. return true;
  6917. }
  6918. CharUnits EndOffset;
  6919. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  6920. return false;
  6921. // If we've fallen outside of the end offset, just pretend there's nothing to
  6922. // write to/read from.
  6923. if (EndOffset <= LVal.getLValueOffset())
  6924. Size = 0;
  6925. else
  6926. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  6927. return true;
  6928. }
  6929. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6930. if (unsigned BuiltinOp = E->getBuiltinCallee())
  6931. return VisitBuiltinCallExpr(E, BuiltinOp);
  6932. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  6933. }
  6934. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  6935. unsigned BuiltinOp) {
  6936. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  6937. default:
  6938. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  6939. case Builtin::BI__builtin_object_size: {
  6940. // The type was checked when we built the expression.
  6941. unsigned Type =
  6942. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  6943. assert(Type <= 3 && "unexpected type");
  6944. uint64_t Size;
  6945. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  6946. return Success(Size, E);
  6947. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  6948. return Success((Type & 2) ? 0 : -1, E);
  6949. // Expression had no side effects, but we couldn't statically determine the
  6950. // size of the referenced object.
  6951. switch (Info.EvalMode) {
  6952. case EvalInfo::EM_ConstantExpression:
  6953. case EvalInfo::EM_PotentialConstantExpression:
  6954. case EvalInfo::EM_ConstantFold:
  6955. case EvalInfo::EM_EvaluateForOverflow:
  6956. case EvalInfo::EM_IgnoreSideEffects:
  6957. case EvalInfo::EM_OffsetFold:
  6958. // Leave it to IR generation.
  6959. return Error(E);
  6960. case EvalInfo::EM_ConstantExpressionUnevaluated:
  6961. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  6962. // Reduce it to a constant now.
  6963. return Success((Type & 2) ? 0 : -1, E);
  6964. }
  6965. llvm_unreachable("unexpected EvalMode");
  6966. }
  6967. case Builtin::BI__builtin_bswap16:
  6968. case Builtin::BI__builtin_bswap32:
  6969. case Builtin::BI__builtin_bswap64: {
  6970. APSInt Val;
  6971. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6972. return false;
  6973. return Success(Val.byteSwap(), E);
  6974. }
  6975. case Builtin::BI__builtin_classify_type:
  6976. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  6977. // FIXME: BI__builtin_clrsb
  6978. // FIXME: BI__builtin_clrsbl
  6979. // FIXME: BI__builtin_clrsbll
  6980. case Builtin::BI__builtin_clz:
  6981. case Builtin::BI__builtin_clzl:
  6982. case Builtin::BI__builtin_clzll:
  6983. case Builtin::BI__builtin_clzs: {
  6984. APSInt Val;
  6985. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6986. return false;
  6987. if (!Val)
  6988. return Error(E);
  6989. return Success(Val.countLeadingZeros(), E);
  6990. }
  6991. case Builtin::BI__builtin_constant_p:
  6992. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  6993. case Builtin::BI__builtin_ctz:
  6994. case Builtin::BI__builtin_ctzl:
  6995. case Builtin::BI__builtin_ctzll:
  6996. case Builtin::BI__builtin_ctzs: {
  6997. APSInt Val;
  6998. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6999. return false;
  7000. if (!Val)
  7001. return Error(E);
  7002. return Success(Val.countTrailingZeros(), E);
  7003. }
  7004. case Builtin::BI__builtin_eh_return_data_regno: {
  7005. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7006. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  7007. return Success(Operand, E);
  7008. }
  7009. case Builtin::BI__builtin_expect:
  7010. return Visit(E->getArg(0));
  7011. case Builtin::BI__builtin_ffs:
  7012. case Builtin::BI__builtin_ffsl:
  7013. case Builtin::BI__builtin_ffsll: {
  7014. APSInt Val;
  7015. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7016. return false;
  7017. unsigned N = Val.countTrailingZeros();
  7018. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  7019. }
  7020. case Builtin::BI__builtin_fpclassify: {
  7021. APFloat Val(0.0);
  7022. if (!EvaluateFloat(E->getArg(5), Val, Info))
  7023. return false;
  7024. unsigned Arg;
  7025. switch (Val.getCategory()) {
  7026. case APFloat::fcNaN: Arg = 0; break;
  7027. case APFloat::fcInfinity: Arg = 1; break;
  7028. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  7029. case APFloat::fcZero: Arg = 4; break;
  7030. }
  7031. return Visit(E->getArg(Arg));
  7032. }
  7033. case Builtin::BI__builtin_isinf_sign: {
  7034. APFloat Val(0.0);
  7035. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7036. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  7037. }
  7038. case Builtin::BI__builtin_isinf: {
  7039. APFloat Val(0.0);
  7040. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7041. Success(Val.isInfinity() ? 1 : 0, E);
  7042. }
  7043. case Builtin::BI__builtin_isfinite: {
  7044. APFloat Val(0.0);
  7045. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7046. Success(Val.isFinite() ? 1 : 0, E);
  7047. }
  7048. case Builtin::BI__builtin_isnan: {
  7049. APFloat Val(0.0);
  7050. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7051. Success(Val.isNaN() ? 1 : 0, E);
  7052. }
  7053. case Builtin::BI__builtin_isnormal: {
  7054. APFloat Val(0.0);
  7055. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7056. Success(Val.isNormal() ? 1 : 0, E);
  7057. }
  7058. case Builtin::BI__builtin_parity:
  7059. case Builtin::BI__builtin_parityl:
  7060. case Builtin::BI__builtin_parityll: {
  7061. APSInt Val;
  7062. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7063. return false;
  7064. return Success(Val.countPopulation() % 2, E);
  7065. }
  7066. case Builtin::BI__builtin_popcount:
  7067. case Builtin::BI__builtin_popcountl:
  7068. case Builtin::BI__builtin_popcountll: {
  7069. APSInt Val;
  7070. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7071. return false;
  7072. return Success(Val.countPopulation(), E);
  7073. }
  7074. case Builtin::BIstrlen:
  7075. case Builtin::BIwcslen:
  7076. // A call to strlen is not a constant expression.
  7077. if (Info.getLangOpts().CPlusPlus11)
  7078. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7079. << /*isConstexpr*/0 << /*isConstructor*/0
  7080. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7081. else
  7082. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7083. LLVM_FALLTHROUGH;
  7084. case Builtin::BI__builtin_strlen:
  7085. case Builtin::BI__builtin_wcslen: {
  7086. // As an extension, we support __builtin_strlen() as a constant expression,
  7087. // and support folding strlen() to a constant.
  7088. LValue String;
  7089. if (!EvaluatePointer(E->getArg(0), String, Info))
  7090. return false;
  7091. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7092. // Fast path: if it's a string literal, search the string value.
  7093. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  7094. String.getLValueBase().dyn_cast<const Expr *>())) {
  7095. // The string literal may have embedded null characters. Find the first
  7096. // one and truncate there.
  7097. StringRef Str = S->getBytes();
  7098. int64_t Off = String.Offset.getQuantity();
  7099. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  7100. S->getCharByteWidth() == 1 &&
  7101. // FIXME: Add fast-path for wchar_t too.
  7102. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  7103. Str = Str.substr(Off);
  7104. StringRef::size_type Pos = Str.find(0);
  7105. if (Pos != StringRef::npos)
  7106. Str = Str.substr(0, Pos);
  7107. return Success(Str.size(), E);
  7108. }
  7109. // Fall through to slow path to issue appropriate diagnostic.
  7110. }
  7111. // Slow path: scan the bytes of the string looking for the terminating 0.
  7112. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  7113. APValue Char;
  7114. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  7115. !Char.isInt())
  7116. return false;
  7117. if (!Char.getInt())
  7118. return Success(Strlen, E);
  7119. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  7120. return false;
  7121. }
  7122. }
  7123. case Builtin::BIstrcmp:
  7124. case Builtin::BIwcscmp:
  7125. case Builtin::BIstrncmp:
  7126. case Builtin::BIwcsncmp:
  7127. case Builtin::BImemcmp:
  7128. case Builtin::BIwmemcmp:
  7129. // A call to strlen is not a constant expression.
  7130. if (Info.getLangOpts().CPlusPlus11)
  7131. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7132. << /*isConstexpr*/0 << /*isConstructor*/0
  7133. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7134. else
  7135. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7136. LLVM_FALLTHROUGH;
  7137. case Builtin::BI__builtin_strcmp:
  7138. case Builtin::BI__builtin_wcscmp:
  7139. case Builtin::BI__builtin_strncmp:
  7140. case Builtin::BI__builtin_wcsncmp:
  7141. case Builtin::BI__builtin_memcmp:
  7142. case Builtin::BI__builtin_wmemcmp: {
  7143. LValue String1, String2;
  7144. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  7145. !EvaluatePointer(E->getArg(1), String2, Info))
  7146. return false;
  7147. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7148. uint64_t MaxLength = uint64_t(-1);
  7149. if (BuiltinOp != Builtin::BIstrcmp &&
  7150. BuiltinOp != Builtin::BIwcscmp &&
  7151. BuiltinOp != Builtin::BI__builtin_strcmp &&
  7152. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  7153. APSInt N;
  7154. if (!EvaluateInteger(E->getArg(2), N, Info))
  7155. return false;
  7156. MaxLength = N.getExtValue();
  7157. }
  7158. bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
  7159. BuiltinOp != Builtin::BIwmemcmp &&
  7160. BuiltinOp != Builtin::BI__builtin_memcmp &&
  7161. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  7162. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  7163. BuiltinOp == Builtin::BIwcsncmp ||
  7164. BuiltinOp == Builtin::BIwmemcmp ||
  7165. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  7166. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  7167. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  7168. for (; MaxLength; --MaxLength) {
  7169. APValue Char1, Char2;
  7170. if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
  7171. !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
  7172. !Char1.isInt() || !Char2.isInt())
  7173. return false;
  7174. if (Char1.getInt() != Char2.getInt()) {
  7175. if (IsWide) // wmemcmp compares with wchar_t signedness.
  7176. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  7177. // memcmp always compares unsigned chars.
  7178. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  7179. }
  7180. if (StopAtNull && !Char1.getInt())
  7181. return Success(0, E);
  7182. assert(!(StopAtNull && !Char2.getInt()));
  7183. if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
  7184. !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
  7185. return false;
  7186. }
  7187. // We hit the strncmp / memcmp limit.
  7188. return Success(0, E);
  7189. }
  7190. case Builtin::BI__atomic_always_lock_free:
  7191. case Builtin::BI__atomic_is_lock_free:
  7192. case Builtin::BI__c11_atomic_is_lock_free: {
  7193. APSInt SizeVal;
  7194. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  7195. return false;
  7196. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  7197. // of two less than the maximum inline atomic width, we know it is
  7198. // lock-free. If the size isn't a power of two, or greater than the
  7199. // maximum alignment where we promote atomics, we know it is not lock-free
  7200. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  7201. // the answer can only be determined at runtime; for example, 16-byte
  7202. // atomics have lock-free implementations on some, but not all,
  7203. // x86-64 processors.
  7204. // Check power-of-two.
  7205. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  7206. if (Size.isPowerOfTwo()) {
  7207. // Check against inlining width.
  7208. unsigned InlineWidthBits =
  7209. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  7210. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  7211. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  7212. Size == CharUnits::One() ||
  7213. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  7214. Expr::NPC_NeverValueDependent))
  7215. // OK, we will inline appropriately-aligned operations of this size,
  7216. // and _Atomic(T) is appropriately-aligned.
  7217. return Success(1, E);
  7218. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  7219. castAs<PointerType>()->getPointeeType();
  7220. if (!PointeeType->isIncompleteType() &&
  7221. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  7222. // OK, we will inline operations on this object.
  7223. return Success(1, E);
  7224. }
  7225. }
  7226. }
  7227. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  7228. Success(0, E) : Error(E);
  7229. }
  7230. case Builtin::BIomp_is_initial_device:
  7231. // We can decide statically which value the runtime would return if called.
  7232. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  7233. case Builtin::BI__builtin_add_overflow:
  7234. case Builtin::BI__builtin_sub_overflow:
  7235. case Builtin::BI__builtin_mul_overflow:
  7236. case Builtin::BI__builtin_sadd_overflow:
  7237. case Builtin::BI__builtin_uadd_overflow:
  7238. case Builtin::BI__builtin_uaddl_overflow:
  7239. case Builtin::BI__builtin_uaddll_overflow:
  7240. case Builtin::BI__builtin_usub_overflow:
  7241. case Builtin::BI__builtin_usubl_overflow:
  7242. case Builtin::BI__builtin_usubll_overflow:
  7243. case Builtin::BI__builtin_umul_overflow:
  7244. case Builtin::BI__builtin_umull_overflow:
  7245. case Builtin::BI__builtin_umulll_overflow:
  7246. case Builtin::BI__builtin_saddl_overflow:
  7247. case Builtin::BI__builtin_saddll_overflow:
  7248. case Builtin::BI__builtin_ssub_overflow:
  7249. case Builtin::BI__builtin_ssubl_overflow:
  7250. case Builtin::BI__builtin_ssubll_overflow:
  7251. case Builtin::BI__builtin_smul_overflow:
  7252. case Builtin::BI__builtin_smull_overflow:
  7253. case Builtin::BI__builtin_smulll_overflow: {
  7254. LValue ResultLValue;
  7255. APSInt LHS, RHS;
  7256. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  7257. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  7258. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  7259. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  7260. return false;
  7261. APSInt Result;
  7262. bool DidOverflow = false;
  7263. // If the types don't have to match, enlarge all 3 to the largest of them.
  7264. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7265. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7266. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7267. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  7268. ResultType->isSignedIntegerOrEnumerationType();
  7269. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  7270. ResultType->isSignedIntegerOrEnumerationType();
  7271. uint64_t LHSSize = LHS.getBitWidth();
  7272. uint64_t RHSSize = RHS.getBitWidth();
  7273. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  7274. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  7275. // Add an additional bit if the signedness isn't uniformly agreed to. We
  7276. // could do this ONLY if there is a signed and an unsigned that both have
  7277. // MaxBits, but the code to check that is pretty nasty. The issue will be
  7278. // caught in the shrink-to-result later anyway.
  7279. if (IsSigned && !AllSigned)
  7280. ++MaxBits;
  7281. LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
  7282. !IsSigned);
  7283. RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
  7284. !IsSigned);
  7285. Result = APSInt(MaxBits, !IsSigned);
  7286. }
  7287. // Find largest int.
  7288. switch (BuiltinOp) {
  7289. default:
  7290. llvm_unreachable("Invalid value for BuiltinOp");
  7291. case Builtin::BI__builtin_add_overflow:
  7292. case Builtin::BI__builtin_sadd_overflow:
  7293. case Builtin::BI__builtin_saddl_overflow:
  7294. case Builtin::BI__builtin_saddll_overflow:
  7295. case Builtin::BI__builtin_uadd_overflow:
  7296. case Builtin::BI__builtin_uaddl_overflow:
  7297. case Builtin::BI__builtin_uaddll_overflow:
  7298. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  7299. : LHS.uadd_ov(RHS, DidOverflow);
  7300. break;
  7301. case Builtin::BI__builtin_sub_overflow:
  7302. case Builtin::BI__builtin_ssub_overflow:
  7303. case Builtin::BI__builtin_ssubl_overflow:
  7304. case Builtin::BI__builtin_ssubll_overflow:
  7305. case Builtin::BI__builtin_usub_overflow:
  7306. case Builtin::BI__builtin_usubl_overflow:
  7307. case Builtin::BI__builtin_usubll_overflow:
  7308. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  7309. : LHS.usub_ov(RHS, DidOverflow);
  7310. break;
  7311. case Builtin::BI__builtin_mul_overflow:
  7312. case Builtin::BI__builtin_smul_overflow:
  7313. case Builtin::BI__builtin_smull_overflow:
  7314. case Builtin::BI__builtin_smulll_overflow:
  7315. case Builtin::BI__builtin_umul_overflow:
  7316. case Builtin::BI__builtin_umull_overflow:
  7317. case Builtin::BI__builtin_umulll_overflow:
  7318. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  7319. : LHS.umul_ov(RHS, DidOverflow);
  7320. break;
  7321. }
  7322. // In the case where multiple sizes are allowed, truncate and see if
  7323. // the values are the same.
  7324. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7325. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7326. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7327. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  7328. // since it will give us the behavior of a TruncOrSelf in the case where
  7329. // its parameter <= its size. We previously set Result to be at least the
  7330. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  7331. // will work exactly like TruncOrSelf.
  7332. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  7333. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  7334. if (!APSInt::isSameValue(Temp, Result))
  7335. DidOverflow = true;
  7336. Result = Temp;
  7337. }
  7338. APValue APV{Result};
  7339. handleAssignment(Info, E, ResultLValue, ResultType, APV);
  7340. return Success(DidOverflow, E);
  7341. }
  7342. }
  7343. }
  7344. static bool HasSameBase(const LValue &A, const LValue &B) {
  7345. if (!A.getLValueBase())
  7346. return !B.getLValueBase();
  7347. if (!B.getLValueBase())
  7348. return false;
  7349. if (A.getLValueBase().getOpaqueValue() !=
  7350. B.getLValueBase().getOpaqueValue()) {
  7351. const Decl *ADecl = GetLValueBaseDecl(A);
  7352. if (!ADecl)
  7353. return false;
  7354. const Decl *BDecl = GetLValueBaseDecl(B);
  7355. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  7356. return false;
  7357. }
  7358. return IsGlobalLValue(A.getLValueBase()) ||
  7359. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  7360. A.getLValueVersion() == B.getLValueVersion());
  7361. }
  7362. /// Determine whether this is a pointer past the end of the complete
  7363. /// object referred to by the lvalue.
  7364. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  7365. const LValue &LV) {
  7366. // A null pointer can be viewed as being "past the end" but we don't
  7367. // choose to look at it that way here.
  7368. if (!LV.getLValueBase())
  7369. return false;
  7370. // If the designator is valid and refers to a subobject, we're not pointing
  7371. // past the end.
  7372. if (!LV.getLValueDesignator().Invalid &&
  7373. !LV.getLValueDesignator().isOnePastTheEnd())
  7374. return false;
  7375. // A pointer to an incomplete type might be past-the-end if the type's size is
  7376. // zero. We cannot tell because the type is incomplete.
  7377. QualType Ty = getType(LV.getLValueBase());
  7378. if (Ty->isIncompleteType())
  7379. return true;
  7380. // We're a past-the-end pointer if we point to the byte after the object,
  7381. // no matter what our type or path is.
  7382. auto Size = Ctx.getTypeSizeInChars(Ty);
  7383. return LV.getLValueOffset() == Size;
  7384. }
  7385. namespace {
  7386. /// Data recursive integer evaluator of certain binary operators.
  7387. ///
  7388. /// We use a data recursive algorithm for binary operators so that we are able
  7389. /// to handle extreme cases of chained binary operators without causing stack
  7390. /// overflow.
  7391. class DataRecursiveIntBinOpEvaluator {
  7392. struct EvalResult {
  7393. APValue Val;
  7394. bool Failed;
  7395. EvalResult() : Failed(false) { }
  7396. void swap(EvalResult &RHS) {
  7397. Val.swap(RHS.Val);
  7398. Failed = RHS.Failed;
  7399. RHS.Failed = false;
  7400. }
  7401. };
  7402. struct Job {
  7403. const Expr *E;
  7404. EvalResult LHSResult; // meaningful only for binary operator expression.
  7405. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  7406. Job() = default;
  7407. Job(Job &&) = default;
  7408. void startSpeculativeEval(EvalInfo &Info) {
  7409. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  7410. }
  7411. private:
  7412. SpeculativeEvaluationRAII SpecEvalRAII;
  7413. };
  7414. SmallVector<Job, 16> Queue;
  7415. IntExprEvaluator &IntEval;
  7416. EvalInfo &Info;
  7417. APValue &FinalResult;
  7418. public:
  7419. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  7420. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  7421. /// True if \param E is a binary operator that we are going to handle
  7422. /// data recursively.
  7423. /// We handle binary operators that are comma, logical, or that have operands
  7424. /// with integral or enumeration type.
  7425. static bool shouldEnqueue(const BinaryOperator *E) {
  7426. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  7427. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  7428. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7429. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7430. }
  7431. bool Traverse(const BinaryOperator *E) {
  7432. enqueue(E);
  7433. EvalResult PrevResult;
  7434. while (!Queue.empty())
  7435. process(PrevResult);
  7436. if (PrevResult.Failed) return false;
  7437. FinalResult.swap(PrevResult.Val);
  7438. return true;
  7439. }
  7440. private:
  7441. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  7442. return IntEval.Success(Value, E, Result);
  7443. }
  7444. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  7445. return IntEval.Success(Value, E, Result);
  7446. }
  7447. bool Error(const Expr *E) {
  7448. return IntEval.Error(E);
  7449. }
  7450. bool Error(const Expr *E, diag::kind D) {
  7451. return IntEval.Error(E, D);
  7452. }
  7453. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  7454. return Info.CCEDiag(E, D);
  7455. }
  7456. // Returns true if visiting the RHS is necessary, false otherwise.
  7457. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7458. bool &SuppressRHSDiags);
  7459. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7460. const BinaryOperator *E, APValue &Result);
  7461. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  7462. Result.Failed = !Evaluate(Result.Val, Info, E);
  7463. if (Result.Failed)
  7464. Result.Val = APValue();
  7465. }
  7466. void process(EvalResult &Result);
  7467. void enqueue(const Expr *E) {
  7468. E = E->IgnoreParens();
  7469. Queue.resize(Queue.size()+1);
  7470. Queue.back().E = E;
  7471. Queue.back().Kind = Job::AnyExprKind;
  7472. }
  7473. };
  7474. }
  7475. bool DataRecursiveIntBinOpEvaluator::
  7476. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7477. bool &SuppressRHSDiags) {
  7478. if (E->getOpcode() == BO_Comma) {
  7479. // Ignore LHS but note if we could not evaluate it.
  7480. if (LHSResult.Failed)
  7481. return Info.noteSideEffect();
  7482. return true;
  7483. }
  7484. if (E->isLogicalOp()) {
  7485. bool LHSAsBool;
  7486. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  7487. // We were able to evaluate the LHS, see if we can get away with not
  7488. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  7489. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  7490. Success(LHSAsBool, E, LHSResult.Val);
  7491. return false; // Ignore RHS
  7492. }
  7493. } else {
  7494. LHSResult.Failed = true;
  7495. // Since we weren't able to evaluate the left hand side, it
  7496. // might have had side effects.
  7497. if (!Info.noteSideEffect())
  7498. return false;
  7499. // We can't evaluate the LHS; however, sometimes the result
  7500. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7501. // Don't ignore RHS and suppress diagnostics from this arm.
  7502. SuppressRHSDiags = true;
  7503. }
  7504. return true;
  7505. }
  7506. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7507. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7508. if (LHSResult.Failed && !Info.noteFailure())
  7509. return false; // Ignore RHS;
  7510. return true;
  7511. }
  7512. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  7513. bool IsSub) {
  7514. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  7515. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  7516. // offsets.
  7517. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  7518. CharUnits &Offset = LVal.getLValueOffset();
  7519. uint64_t Offset64 = Offset.getQuantity();
  7520. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  7521. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  7522. : Offset64 + Index64);
  7523. }
  7524. bool DataRecursiveIntBinOpEvaluator::
  7525. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7526. const BinaryOperator *E, APValue &Result) {
  7527. if (E->getOpcode() == BO_Comma) {
  7528. if (RHSResult.Failed)
  7529. return false;
  7530. Result = RHSResult.Val;
  7531. return true;
  7532. }
  7533. if (E->isLogicalOp()) {
  7534. bool lhsResult, rhsResult;
  7535. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  7536. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  7537. if (LHSIsOK) {
  7538. if (RHSIsOK) {
  7539. if (E->getOpcode() == BO_LOr)
  7540. return Success(lhsResult || rhsResult, E, Result);
  7541. else
  7542. return Success(lhsResult && rhsResult, E, Result);
  7543. }
  7544. } else {
  7545. if (RHSIsOK) {
  7546. // We can't evaluate the LHS; however, sometimes the result
  7547. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7548. if (rhsResult == (E->getOpcode() == BO_LOr))
  7549. return Success(rhsResult, E, Result);
  7550. }
  7551. }
  7552. return false;
  7553. }
  7554. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7555. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7556. if (LHSResult.Failed || RHSResult.Failed)
  7557. return false;
  7558. const APValue &LHSVal = LHSResult.Val;
  7559. const APValue &RHSVal = RHSResult.Val;
  7560. // Handle cases like (unsigned long)&a + 4.
  7561. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  7562. Result = LHSVal;
  7563. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  7564. return true;
  7565. }
  7566. // Handle cases like 4 + (unsigned long)&a
  7567. if (E->getOpcode() == BO_Add &&
  7568. RHSVal.isLValue() && LHSVal.isInt()) {
  7569. Result = RHSVal;
  7570. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  7571. return true;
  7572. }
  7573. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  7574. // Handle (intptr_t)&&A - (intptr_t)&&B.
  7575. if (!LHSVal.getLValueOffset().isZero() ||
  7576. !RHSVal.getLValueOffset().isZero())
  7577. return false;
  7578. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  7579. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  7580. if (!LHSExpr || !RHSExpr)
  7581. return false;
  7582. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  7583. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  7584. if (!LHSAddrExpr || !RHSAddrExpr)
  7585. return false;
  7586. // Make sure both labels come from the same function.
  7587. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  7588. RHSAddrExpr->getLabel()->getDeclContext())
  7589. return false;
  7590. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  7591. return true;
  7592. }
  7593. // All the remaining cases expect both operands to be an integer
  7594. if (!LHSVal.isInt() || !RHSVal.isInt())
  7595. return Error(E);
  7596. // Set up the width and signedness manually, in case it can't be deduced
  7597. // from the operation we're performing.
  7598. // FIXME: Don't do this in the cases where we can deduce it.
  7599. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  7600. E->getType()->isUnsignedIntegerOrEnumerationType());
  7601. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  7602. RHSVal.getInt(), Value))
  7603. return false;
  7604. return Success(Value, E, Result);
  7605. }
  7606. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  7607. Job &job = Queue.back();
  7608. switch (job.Kind) {
  7609. case Job::AnyExprKind: {
  7610. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  7611. if (shouldEnqueue(Bop)) {
  7612. job.Kind = Job::BinOpKind;
  7613. enqueue(Bop->getLHS());
  7614. return;
  7615. }
  7616. }
  7617. EvaluateExpr(job.E, Result);
  7618. Queue.pop_back();
  7619. return;
  7620. }
  7621. case Job::BinOpKind: {
  7622. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7623. bool SuppressRHSDiags = false;
  7624. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  7625. Queue.pop_back();
  7626. return;
  7627. }
  7628. if (SuppressRHSDiags)
  7629. job.startSpeculativeEval(Info);
  7630. job.LHSResult.swap(Result);
  7631. job.Kind = Job::BinOpVisitedLHSKind;
  7632. enqueue(Bop->getRHS());
  7633. return;
  7634. }
  7635. case Job::BinOpVisitedLHSKind: {
  7636. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7637. EvalResult RHS;
  7638. RHS.swap(Result);
  7639. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  7640. Queue.pop_back();
  7641. return;
  7642. }
  7643. }
  7644. llvm_unreachable("Invalid Job::Kind!");
  7645. }
  7646. namespace {
  7647. /// Used when we determine that we should fail, but can keep evaluating prior to
  7648. /// noting that we had a failure.
  7649. class DelayedNoteFailureRAII {
  7650. EvalInfo &Info;
  7651. bool NoteFailure;
  7652. public:
  7653. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  7654. : Info(Info), NoteFailure(NoteFailure) {}
  7655. ~DelayedNoteFailureRAII() {
  7656. if (NoteFailure) {
  7657. bool ContinueAfterFailure = Info.noteFailure();
  7658. (void)ContinueAfterFailure;
  7659. assert(ContinueAfterFailure &&
  7660. "Shouldn't have kept evaluating on failure.");
  7661. }
  7662. }
  7663. };
  7664. }
  7665. template <class SuccessCB, class AfterCB>
  7666. static bool
  7667. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  7668. SuccessCB &&Success, AfterCB &&DoAfter) {
  7669. assert(E->isComparisonOp() && "expected comparison operator");
  7670. assert((E->getOpcode() == BO_Cmp ||
  7671. E->getType()->isIntegralOrEnumerationType()) &&
  7672. "unsupported binary expression evaluation");
  7673. auto Error = [&](const Expr *E) {
  7674. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7675. return false;
  7676. };
  7677. using CCR = ComparisonCategoryResult;
  7678. bool IsRelational = E->isRelationalOp();
  7679. bool IsEquality = E->isEqualityOp();
  7680. if (E->getOpcode() == BO_Cmp) {
  7681. const ComparisonCategoryInfo &CmpInfo =
  7682. Info.Ctx.CompCategories.getInfoForType(E->getType());
  7683. IsRelational = CmpInfo.isOrdered();
  7684. IsEquality = CmpInfo.isEquality();
  7685. }
  7686. QualType LHSTy = E->getLHS()->getType();
  7687. QualType RHSTy = E->getRHS()->getType();
  7688. if (LHSTy->isIntegralOrEnumerationType() &&
  7689. RHSTy->isIntegralOrEnumerationType()) {
  7690. APSInt LHS, RHS;
  7691. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  7692. if (!LHSOK && !Info.noteFailure())
  7693. return false;
  7694. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  7695. return false;
  7696. if (LHS < RHS)
  7697. return Success(CCR::Less, E);
  7698. if (LHS > RHS)
  7699. return Success(CCR::Greater, E);
  7700. return Success(CCR::Equal, E);
  7701. }
  7702. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  7703. ComplexValue LHS, RHS;
  7704. bool LHSOK;
  7705. if (E->isAssignmentOp()) {
  7706. LValue LV;
  7707. EvaluateLValue(E->getLHS(), LV, Info);
  7708. LHSOK = false;
  7709. } else if (LHSTy->isRealFloatingType()) {
  7710. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  7711. if (LHSOK) {
  7712. LHS.makeComplexFloat();
  7713. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  7714. }
  7715. } else {
  7716. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  7717. }
  7718. if (!LHSOK && !Info.noteFailure())
  7719. return false;
  7720. if (E->getRHS()->getType()->isRealFloatingType()) {
  7721. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  7722. return false;
  7723. RHS.makeComplexFloat();
  7724. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  7725. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  7726. return false;
  7727. if (LHS.isComplexFloat()) {
  7728. APFloat::cmpResult CR_r =
  7729. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  7730. APFloat::cmpResult CR_i =
  7731. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  7732. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  7733. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7734. } else {
  7735. assert(IsEquality && "invalid complex comparison");
  7736. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  7737. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  7738. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7739. }
  7740. }
  7741. if (LHSTy->isRealFloatingType() &&
  7742. RHSTy->isRealFloatingType()) {
  7743. APFloat RHS(0.0), LHS(0.0);
  7744. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  7745. if (!LHSOK && !Info.noteFailure())
  7746. return false;
  7747. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  7748. return false;
  7749. assert(E->isComparisonOp() && "Invalid binary operator!");
  7750. auto GetCmpRes = [&]() {
  7751. switch (LHS.compare(RHS)) {
  7752. case APFloat::cmpEqual:
  7753. return CCR::Equal;
  7754. case APFloat::cmpLessThan:
  7755. return CCR::Less;
  7756. case APFloat::cmpGreaterThan:
  7757. return CCR::Greater;
  7758. case APFloat::cmpUnordered:
  7759. return CCR::Unordered;
  7760. }
  7761. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  7762. };
  7763. return Success(GetCmpRes(), E);
  7764. }
  7765. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  7766. LValue LHSValue, RHSValue;
  7767. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  7768. if (!LHSOK && !Info.noteFailure())
  7769. return false;
  7770. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  7771. return false;
  7772. // Reject differing bases from the normal codepath; we special-case
  7773. // comparisons to null.
  7774. if (!HasSameBase(LHSValue, RHSValue)) {
  7775. // Inequalities and subtractions between unrelated pointers have
  7776. // unspecified or undefined behavior.
  7777. if (!IsEquality)
  7778. return Error(E);
  7779. // A constant address may compare equal to the address of a symbol.
  7780. // The one exception is that address of an object cannot compare equal
  7781. // to a null pointer constant.
  7782. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  7783. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  7784. return Error(E);
  7785. // It's implementation-defined whether distinct literals will have
  7786. // distinct addresses. In clang, the result of such a comparison is
  7787. // unspecified, so it is not a constant expression. However, we do know
  7788. // that the address of a literal will be non-null.
  7789. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  7790. LHSValue.Base && RHSValue.Base)
  7791. return Error(E);
  7792. // We can't tell whether weak symbols will end up pointing to the same
  7793. // object.
  7794. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  7795. return Error(E);
  7796. // We can't compare the address of the start of one object with the
  7797. // past-the-end address of another object, per C++ DR1652.
  7798. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  7799. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  7800. (RHSValue.Base && RHSValue.Offset.isZero() &&
  7801. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  7802. return Error(E);
  7803. // We can't tell whether an object is at the same address as another
  7804. // zero sized object.
  7805. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  7806. (LHSValue.Base && isZeroSized(RHSValue)))
  7807. return Error(E);
  7808. return Success(CCR::Nonequal, E);
  7809. }
  7810. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  7811. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  7812. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  7813. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  7814. // C++11 [expr.rel]p3:
  7815. // Pointers to void (after pointer conversions) can be compared, with a
  7816. // result defined as follows: If both pointers represent the same
  7817. // address or are both the null pointer value, the result is true if the
  7818. // operator is <= or >= and false otherwise; otherwise the result is
  7819. // unspecified.
  7820. // We interpret this as applying to pointers to *cv* void.
  7821. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  7822. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  7823. // C++11 [expr.rel]p2:
  7824. // - If two pointers point to non-static data members of the same object,
  7825. // or to subobjects or array elements fo such members, recursively, the
  7826. // pointer to the later declared member compares greater provided the
  7827. // two members have the same access control and provided their class is
  7828. // not a union.
  7829. // [...]
  7830. // - Otherwise pointer comparisons are unspecified.
  7831. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  7832. bool WasArrayIndex;
  7833. unsigned Mismatch = FindDesignatorMismatch(
  7834. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  7835. // At the point where the designators diverge, the comparison has a
  7836. // specified value if:
  7837. // - we are comparing array indices
  7838. // - we are comparing fields of a union, or fields with the same access
  7839. // Otherwise, the result is unspecified and thus the comparison is not a
  7840. // constant expression.
  7841. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  7842. Mismatch < RHSDesignator.Entries.size()) {
  7843. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  7844. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  7845. if (!LF && !RF)
  7846. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  7847. else if (!LF)
  7848. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  7849. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  7850. << RF->getParent() << RF;
  7851. else if (!RF)
  7852. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  7853. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  7854. << LF->getParent() << LF;
  7855. else if (!LF->getParent()->isUnion() &&
  7856. LF->getAccess() != RF->getAccess())
  7857. Info.CCEDiag(E,
  7858. diag::note_constexpr_pointer_comparison_differing_access)
  7859. << LF << LF->getAccess() << RF << RF->getAccess()
  7860. << LF->getParent();
  7861. }
  7862. }
  7863. // The comparison here must be unsigned, and performed with the same
  7864. // width as the pointer.
  7865. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  7866. uint64_t CompareLHS = LHSOffset.getQuantity();
  7867. uint64_t CompareRHS = RHSOffset.getQuantity();
  7868. assert(PtrSize <= 64 && "Unexpected pointer width");
  7869. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  7870. CompareLHS &= Mask;
  7871. CompareRHS &= Mask;
  7872. // If there is a base and this is a relational operator, we can only
  7873. // compare pointers within the object in question; otherwise, the result
  7874. // depends on where the object is located in memory.
  7875. if (!LHSValue.Base.isNull() && IsRelational) {
  7876. QualType BaseTy = getType(LHSValue.Base);
  7877. if (BaseTy->isIncompleteType())
  7878. return Error(E);
  7879. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  7880. uint64_t OffsetLimit = Size.getQuantity();
  7881. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  7882. return Error(E);
  7883. }
  7884. if (CompareLHS < CompareRHS)
  7885. return Success(CCR::Less, E);
  7886. if (CompareLHS > CompareRHS)
  7887. return Success(CCR::Greater, E);
  7888. return Success(CCR::Equal, E);
  7889. }
  7890. if (LHSTy->isMemberPointerType()) {
  7891. assert(IsEquality && "unexpected member pointer operation");
  7892. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  7893. MemberPtr LHSValue, RHSValue;
  7894. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  7895. if (!LHSOK && !Info.noteFailure())
  7896. return false;
  7897. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  7898. return false;
  7899. // C++11 [expr.eq]p2:
  7900. // If both operands are null, they compare equal. Otherwise if only one is
  7901. // null, they compare unequal.
  7902. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  7903. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  7904. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  7905. }
  7906. // Otherwise if either is a pointer to a virtual member function, the
  7907. // result is unspecified.
  7908. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  7909. if (MD->isVirtual())
  7910. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  7911. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  7912. if (MD->isVirtual())
  7913. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  7914. // Otherwise they compare equal if and only if they would refer to the
  7915. // same member of the same most derived object or the same subobject if
  7916. // they were dereferenced with a hypothetical object of the associated
  7917. // class type.
  7918. bool Equal = LHSValue == RHSValue;
  7919. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  7920. }
  7921. if (LHSTy->isNullPtrType()) {
  7922. assert(E->isComparisonOp() && "unexpected nullptr operation");
  7923. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  7924. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  7925. // are compared, the result is true of the operator is <=, >= or ==, and
  7926. // false otherwise.
  7927. return Success(CCR::Equal, E);
  7928. }
  7929. return DoAfter();
  7930. }
  7931. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  7932. if (!CheckLiteralType(Info, E))
  7933. return false;
  7934. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  7935. const BinaryOperator *E) {
  7936. // Evaluation succeeded. Lookup the information for the comparison category
  7937. // type and fetch the VarDecl for the result.
  7938. const ComparisonCategoryInfo &CmpInfo =
  7939. Info.Ctx.CompCategories.getInfoForType(E->getType());
  7940. const VarDecl *VD =
  7941. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  7942. // Check and evaluate the result as a constant expression.
  7943. LValue LV;
  7944. LV.set(VD);
  7945. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  7946. return false;
  7947. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  7948. };
  7949. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  7950. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  7951. });
  7952. }
  7953. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  7954. // We don't call noteFailure immediately because the assignment happens after
  7955. // we evaluate LHS and RHS.
  7956. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  7957. return Error(E);
  7958. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  7959. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  7960. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  7961. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  7962. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  7963. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  7964. if (E->isComparisonOp()) {
  7965. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  7966. // comparisons and then translating the result.
  7967. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  7968. const BinaryOperator *E) {
  7969. using CCR = ComparisonCategoryResult;
  7970. bool IsEqual = ResKind == CCR::Equal,
  7971. IsLess = ResKind == CCR::Less,
  7972. IsGreater = ResKind == CCR::Greater;
  7973. auto Op = E->getOpcode();
  7974. switch (Op) {
  7975. default:
  7976. llvm_unreachable("unsupported binary operator");
  7977. case BO_EQ:
  7978. case BO_NE:
  7979. return Success(IsEqual == (Op == BO_EQ), E);
  7980. case BO_LT: return Success(IsLess, E);
  7981. case BO_GT: return Success(IsGreater, E);
  7982. case BO_LE: return Success(IsEqual || IsLess, E);
  7983. case BO_GE: return Success(IsEqual || IsGreater, E);
  7984. }
  7985. };
  7986. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  7987. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7988. });
  7989. }
  7990. QualType LHSTy = E->getLHS()->getType();
  7991. QualType RHSTy = E->getRHS()->getType();
  7992. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  7993. E->getOpcode() == BO_Sub) {
  7994. LValue LHSValue, RHSValue;
  7995. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  7996. if (!LHSOK && !Info.noteFailure())
  7997. return false;
  7998. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  7999. return false;
  8000. // Reject differing bases from the normal codepath; we special-case
  8001. // comparisons to null.
  8002. if (!HasSameBase(LHSValue, RHSValue)) {
  8003. // Handle &&A - &&B.
  8004. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  8005. return Error(E);
  8006. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  8007. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  8008. if (!LHSExpr || !RHSExpr)
  8009. return Error(E);
  8010. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8011. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8012. if (!LHSAddrExpr || !RHSAddrExpr)
  8013. return Error(E);
  8014. // Make sure both labels come from the same function.
  8015. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8016. RHSAddrExpr->getLabel()->getDeclContext())
  8017. return Error(E);
  8018. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  8019. }
  8020. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  8021. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  8022. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  8023. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  8024. // C++11 [expr.add]p6:
  8025. // Unless both pointers point to elements of the same array object, or
  8026. // one past the last element of the array object, the behavior is
  8027. // undefined.
  8028. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  8029. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  8030. RHSDesignator))
  8031. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  8032. QualType Type = E->getLHS()->getType();
  8033. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  8034. CharUnits ElementSize;
  8035. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  8036. return false;
  8037. // As an extension, a type may have zero size (empty struct or union in
  8038. // C, array of zero length). Pointer subtraction in such cases has
  8039. // undefined behavior, so is not constant.
  8040. if (ElementSize.isZero()) {
  8041. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  8042. << ElementType;
  8043. return false;
  8044. }
  8045. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  8046. // and produce incorrect results when it overflows. Such behavior
  8047. // appears to be non-conforming, but is common, so perhaps we should
  8048. // assume the standard intended for such cases to be undefined behavior
  8049. // and check for them.
  8050. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  8051. // overflow in the final conversion to ptrdiff_t.
  8052. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  8053. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  8054. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  8055. false);
  8056. APSInt TrueResult = (LHS - RHS) / ElemSize;
  8057. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  8058. if (Result.extend(65) != TrueResult &&
  8059. !HandleOverflow(Info, E, TrueResult, E->getType()))
  8060. return false;
  8061. return Success(Result, E);
  8062. }
  8063. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8064. }
  8065. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  8066. /// a result as the expression's type.
  8067. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  8068. const UnaryExprOrTypeTraitExpr *E) {
  8069. switch(E->getKind()) {
  8070. case UETT_AlignOf: {
  8071. if (E->isArgumentType())
  8072. return Success(GetAlignOfType(Info, E->getArgumentType()), E);
  8073. else
  8074. return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
  8075. }
  8076. case UETT_VecStep: {
  8077. QualType Ty = E->getTypeOfArgument();
  8078. if (Ty->isVectorType()) {
  8079. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  8080. // The vec_step built-in functions that take a 3-component
  8081. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  8082. if (n == 3)
  8083. n = 4;
  8084. return Success(n, E);
  8085. } else
  8086. return Success(1, E);
  8087. }
  8088. case UETT_SizeOf: {
  8089. QualType SrcTy = E->getTypeOfArgument();
  8090. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  8091. // the result is the size of the referenced type."
  8092. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  8093. SrcTy = Ref->getPointeeType();
  8094. CharUnits Sizeof;
  8095. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  8096. return false;
  8097. return Success(Sizeof, E);
  8098. }
  8099. case UETT_OpenMPRequiredSimdAlign:
  8100. assert(E->isArgumentType());
  8101. return Success(
  8102. Info.Ctx.toCharUnitsFromBits(
  8103. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  8104. .getQuantity(),
  8105. E);
  8106. }
  8107. llvm_unreachable("unknown expr/type trait");
  8108. }
  8109. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  8110. CharUnits Result;
  8111. unsigned n = OOE->getNumComponents();
  8112. if (n == 0)
  8113. return Error(OOE);
  8114. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  8115. for (unsigned i = 0; i != n; ++i) {
  8116. OffsetOfNode ON = OOE->getComponent(i);
  8117. switch (ON.getKind()) {
  8118. case OffsetOfNode::Array: {
  8119. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  8120. APSInt IdxResult;
  8121. if (!EvaluateInteger(Idx, IdxResult, Info))
  8122. return false;
  8123. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  8124. if (!AT)
  8125. return Error(OOE);
  8126. CurrentType = AT->getElementType();
  8127. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  8128. Result += IdxResult.getSExtValue() * ElementSize;
  8129. break;
  8130. }
  8131. case OffsetOfNode::Field: {
  8132. FieldDecl *MemberDecl = ON.getField();
  8133. const RecordType *RT = CurrentType->getAs<RecordType>();
  8134. if (!RT)
  8135. return Error(OOE);
  8136. RecordDecl *RD = RT->getDecl();
  8137. if (RD->isInvalidDecl()) return false;
  8138. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8139. unsigned i = MemberDecl->getFieldIndex();
  8140. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  8141. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  8142. CurrentType = MemberDecl->getType().getNonReferenceType();
  8143. break;
  8144. }
  8145. case OffsetOfNode::Identifier:
  8146. llvm_unreachable("dependent __builtin_offsetof");
  8147. case OffsetOfNode::Base: {
  8148. CXXBaseSpecifier *BaseSpec = ON.getBase();
  8149. if (BaseSpec->isVirtual())
  8150. return Error(OOE);
  8151. // Find the layout of the class whose base we are looking into.
  8152. const RecordType *RT = CurrentType->getAs<RecordType>();
  8153. if (!RT)
  8154. return Error(OOE);
  8155. RecordDecl *RD = RT->getDecl();
  8156. if (RD->isInvalidDecl()) return false;
  8157. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8158. // Find the base class itself.
  8159. CurrentType = BaseSpec->getType();
  8160. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  8161. if (!BaseRT)
  8162. return Error(OOE);
  8163. // Add the offset to the base.
  8164. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  8165. break;
  8166. }
  8167. }
  8168. }
  8169. return Success(Result, OOE);
  8170. }
  8171. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8172. switch (E->getOpcode()) {
  8173. default:
  8174. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  8175. // See C99 6.6p3.
  8176. return Error(E);
  8177. case UO_Extension:
  8178. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  8179. // If so, we could clear the diagnostic ID.
  8180. return Visit(E->getSubExpr());
  8181. case UO_Plus:
  8182. // The result is just the value.
  8183. return Visit(E->getSubExpr());
  8184. case UO_Minus: {
  8185. if (!Visit(E->getSubExpr()))
  8186. return false;
  8187. if (!Result.isInt()) return Error(E);
  8188. const APSInt &Value = Result.getInt();
  8189. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  8190. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  8191. E->getType()))
  8192. return false;
  8193. return Success(-Value, E);
  8194. }
  8195. case UO_Not: {
  8196. if (!Visit(E->getSubExpr()))
  8197. return false;
  8198. if (!Result.isInt()) return Error(E);
  8199. return Success(~Result.getInt(), E);
  8200. }
  8201. case UO_LNot: {
  8202. bool bres;
  8203. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8204. return false;
  8205. return Success(!bres, E);
  8206. }
  8207. }
  8208. }
  8209. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  8210. /// result type is integer.
  8211. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8212. const Expr *SubExpr = E->getSubExpr();
  8213. QualType DestType = E->getType();
  8214. QualType SrcType = SubExpr->getType();
  8215. switch (E->getCastKind()) {
  8216. case CK_BaseToDerived:
  8217. case CK_DerivedToBase:
  8218. case CK_UncheckedDerivedToBase:
  8219. case CK_Dynamic:
  8220. case CK_ToUnion:
  8221. case CK_ArrayToPointerDecay:
  8222. case CK_FunctionToPointerDecay:
  8223. case CK_NullToPointer:
  8224. case CK_NullToMemberPointer:
  8225. case CK_BaseToDerivedMemberPointer:
  8226. case CK_DerivedToBaseMemberPointer:
  8227. case CK_ReinterpretMemberPointer:
  8228. case CK_ConstructorConversion:
  8229. case CK_IntegralToPointer:
  8230. case CK_ToVoid:
  8231. case CK_VectorSplat:
  8232. case CK_IntegralToFloating:
  8233. case CK_FloatingCast:
  8234. case CK_CPointerToObjCPointerCast:
  8235. case CK_BlockPointerToObjCPointerCast:
  8236. case CK_AnyPointerToBlockPointerCast:
  8237. case CK_ObjCObjectLValueCast:
  8238. case CK_FloatingRealToComplex:
  8239. case CK_FloatingComplexToReal:
  8240. case CK_FloatingComplexCast:
  8241. case CK_FloatingComplexToIntegralComplex:
  8242. case CK_IntegralRealToComplex:
  8243. case CK_IntegralComplexCast:
  8244. case CK_IntegralComplexToFloatingComplex:
  8245. case CK_BuiltinFnToFnPtr:
  8246. case CK_ZeroToOCLEvent:
  8247. case CK_ZeroToOCLQueue:
  8248. case CK_NonAtomicToAtomic:
  8249. case CK_AddressSpaceConversion:
  8250. case CK_IntToOCLSampler:
  8251. llvm_unreachable("invalid cast kind for integral value");
  8252. case CK_BitCast:
  8253. case CK_Dependent:
  8254. case CK_LValueBitCast:
  8255. case CK_ARCProduceObject:
  8256. case CK_ARCConsumeObject:
  8257. case CK_ARCReclaimReturnedObject:
  8258. case CK_ARCExtendBlockObject:
  8259. case CK_CopyAndAutoreleaseBlockObject:
  8260. return Error(E);
  8261. case CK_UserDefinedConversion:
  8262. case CK_LValueToRValue:
  8263. case CK_AtomicToNonAtomic:
  8264. case CK_NoOp:
  8265. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8266. case CK_MemberPointerToBoolean:
  8267. case CK_PointerToBoolean:
  8268. case CK_IntegralToBoolean:
  8269. case CK_FloatingToBoolean:
  8270. case CK_BooleanToSignedIntegral:
  8271. case CK_FloatingComplexToBoolean:
  8272. case CK_IntegralComplexToBoolean: {
  8273. bool BoolResult;
  8274. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  8275. return false;
  8276. uint64_t IntResult = BoolResult;
  8277. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  8278. IntResult = (uint64_t)-1;
  8279. return Success(IntResult, E);
  8280. }
  8281. case CK_IntegralCast: {
  8282. if (!Visit(SubExpr))
  8283. return false;
  8284. if (!Result.isInt()) {
  8285. // Allow casts of address-of-label differences if they are no-ops
  8286. // or narrowing. (The narrowing case isn't actually guaranteed to
  8287. // be constant-evaluatable except in some narrow cases which are hard
  8288. // to detect here. We let it through on the assumption the user knows
  8289. // what they are doing.)
  8290. if (Result.isAddrLabelDiff())
  8291. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  8292. // Only allow casts of lvalues if they are lossless.
  8293. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  8294. }
  8295. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  8296. Result.getInt()), E);
  8297. }
  8298. case CK_PointerToIntegral: {
  8299. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  8300. LValue LV;
  8301. if (!EvaluatePointer(SubExpr, LV, Info))
  8302. return false;
  8303. if (LV.getLValueBase()) {
  8304. // Only allow based lvalue casts if they are lossless.
  8305. // FIXME: Allow a larger integer size than the pointer size, and allow
  8306. // narrowing back down to pointer width in subsequent integral casts.
  8307. // FIXME: Check integer type's active bits, not its type size.
  8308. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  8309. return Error(E);
  8310. LV.Designator.setInvalid();
  8311. LV.moveInto(Result);
  8312. return true;
  8313. }
  8314. uint64_t V;
  8315. if (LV.isNullPointer())
  8316. V = Info.Ctx.getTargetNullPointerValue(SrcType);
  8317. else
  8318. V = LV.getLValueOffset().getQuantity();
  8319. APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
  8320. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  8321. }
  8322. case CK_IntegralComplexToReal: {
  8323. ComplexValue C;
  8324. if (!EvaluateComplex(SubExpr, C, Info))
  8325. return false;
  8326. return Success(C.getComplexIntReal(), E);
  8327. }
  8328. case CK_FloatingToIntegral: {
  8329. APFloat F(0.0);
  8330. if (!EvaluateFloat(SubExpr, F, Info))
  8331. return false;
  8332. APSInt Value;
  8333. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  8334. return false;
  8335. return Success(Value, E);
  8336. }
  8337. }
  8338. llvm_unreachable("unknown cast resulting in integral value");
  8339. }
  8340. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8341. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8342. ComplexValue LV;
  8343. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8344. return false;
  8345. if (!LV.isComplexInt())
  8346. return Error(E);
  8347. return Success(LV.getComplexIntReal(), E);
  8348. }
  8349. return Visit(E->getSubExpr());
  8350. }
  8351. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8352. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  8353. ComplexValue LV;
  8354. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8355. return false;
  8356. if (!LV.isComplexInt())
  8357. return Error(E);
  8358. return Success(LV.getComplexIntImag(), E);
  8359. }
  8360. VisitIgnoredValue(E->getSubExpr());
  8361. return Success(0, E);
  8362. }
  8363. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  8364. return Success(E->getPackLength(), E);
  8365. }
  8366. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  8367. return Success(E->getValue(), E);
  8368. }
  8369. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8370. switch (E->getOpcode()) {
  8371. default:
  8372. // Invalid unary operators
  8373. return Error(E);
  8374. case UO_Plus:
  8375. // The result is just the value.
  8376. return Visit(E->getSubExpr());
  8377. case UO_Minus: {
  8378. if (!Visit(E->getSubExpr())) return false;
  8379. if (!Result.isInt()) return Error(E);
  8380. const APSInt &Value = Result.getInt();
  8381. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
  8382. SmallString<64> S;
  8383. FixedPointValueToString(S, Value,
  8384. Info.Ctx.getTypeInfo(E->getType()).Width,
  8385. /*Radix=*/10);
  8386. Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
  8387. if (Info.noteUndefinedBehavior()) return false;
  8388. }
  8389. return Success(-Value, E);
  8390. }
  8391. case UO_LNot: {
  8392. bool bres;
  8393. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8394. return false;
  8395. return Success(!bres, E);
  8396. }
  8397. }
  8398. }
  8399. //===----------------------------------------------------------------------===//
  8400. // Float Evaluation
  8401. //===----------------------------------------------------------------------===//
  8402. namespace {
  8403. class FloatExprEvaluator
  8404. : public ExprEvaluatorBase<FloatExprEvaluator> {
  8405. APFloat &Result;
  8406. public:
  8407. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  8408. : ExprEvaluatorBaseTy(info), Result(result) {}
  8409. bool Success(const APValue &V, const Expr *e) {
  8410. Result = V.getFloat();
  8411. return true;
  8412. }
  8413. bool ZeroInitialization(const Expr *E) {
  8414. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  8415. return true;
  8416. }
  8417. bool VisitCallExpr(const CallExpr *E);
  8418. bool VisitUnaryOperator(const UnaryOperator *E);
  8419. bool VisitBinaryOperator(const BinaryOperator *E);
  8420. bool VisitFloatingLiteral(const FloatingLiteral *E);
  8421. bool VisitCastExpr(const CastExpr *E);
  8422. bool VisitUnaryReal(const UnaryOperator *E);
  8423. bool VisitUnaryImag(const UnaryOperator *E);
  8424. // FIXME: Missing: array subscript of vector, member of vector
  8425. };
  8426. } // end anonymous namespace
  8427. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  8428. assert(E->isRValue() && E->getType()->isRealFloatingType());
  8429. return FloatExprEvaluator(Info, Result).Visit(E);
  8430. }
  8431. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  8432. QualType ResultTy,
  8433. const Expr *Arg,
  8434. bool SNaN,
  8435. llvm::APFloat &Result) {
  8436. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  8437. if (!S) return false;
  8438. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  8439. llvm::APInt fill;
  8440. // Treat empty strings as if they were zero.
  8441. if (S->getString().empty())
  8442. fill = llvm::APInt(32, 0);
  8443. else if (S->getString().getAsInteger(0, fill))
  8444. return false;
  8445. if (Context.getTargetInfo().isNan2008()) {
  8446. if (SNaN)
  8447. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8448. else
  8449. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8450. } else {
  8451. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  8452. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  8453. // a different encoding to what became a standard in 2008, and for pre-
  8454. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  8455. // sNaN. This is now known as "legacy NaN" encoding.
  8456. if (SNaN)
  8457. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8458. else
  8459. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8460. }
  8461. return true;
  8462. }
  8463. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8464. switch (E->getBuiltinCallee()) {
  8465. default:
  8466. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8467. case Builtin::BI__builtin_huge_val:
  8468. case Builtin::BI__builtin_huge_valf:
  8469. case Builtin::BI__builtin_huge_vall:
  8470. case Builtin::BI__builtin_huge_valf128:
  8471. case Builtin::BI__builtin_inf:
  8472. case Builtin::BI__builtin_inff:
  8473. case Builtin::BI__builtin_infl:
  8474. case Builtin::BI__builtin_inff128: {
  8475. const llvm::fltSemantics &Sem =
  8476. Info.Ctx.getFloatTypeSemantics(E->getType());
  8477. Result = llvm::APFloat::getInf(Sem);
  8478. return true;
  8479. }
  8480. case Builtin::BI__builtin_nans:
  8481. case Builtin::BI__builtin_nansf:
  8482. case Builtin::BI__builtin_nansl:
  8483. case Builtin::BI__builtin_nansf128:
  8484. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8485. true, Result))
  8486. return Error(E);
  8487. return true;
  8488. case Builtin::BI__builtin_nan:
  8489. case Builtin::BI__builtin_nanf:
  8490. case Builtin::BI__builtin_nanl:
  8491. case Builtin::BI__builtin_nanf128:
  8492. // If this is __builtin_nan() turn this into a nan, otherwise we
  8493. // can't constant fold it.
  8494. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8495. false, Result))
  8496. return Error(E);
  8497. return true;
  8498. case Builtin::BI__builtin_fabs:
  8499. case Builtin::BI__builtin_fabsf:
  8500. case Builtin::BI__builtin_fabsl:
  8501. case Builtin::BI__builtin_fabsf128:
  8502. if (!EvaluateFloat(E->getArg(0), Result, Info))
  8503. return false;
  8504. if (Result.isNegative())
  8505. Result.changeSign();
  8506. return true;
  8507. // FIXME: Builtin::BI__builtin_powi
  8508. // FIXME: Builtin::BI__builtin_powif
  8509. // FIXME: Builtin::BI__builtin_powil
  8510. case Builtin::BI__builtin_copysign:
  8511. case Builtin::BI__builtin_copysignf:
  8512. case Builtin::BI__builtin_copysignl:
  8513. case Builtin::BI__builtin_copysignf128: {
  8514. APFloat RHS(0.);
  8515. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  8516. !EvaluateFloat(E->getArg(1), RHS, Info))
  8517. return false;
  8518. Result.copySign(RHS);
  8519. return true;
  8520. }
  8521. }
  8522. }
  8523. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8524. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8525. ComplexValue CV;
  8526. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8527. return false;
  8528. Result = CV.FloatReal;
  8529. return true;
  8530. }
  8531. return Visit(E->getSubExpr());
  8532. }
  8533. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8534. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8535. ComplexValue CV;
  8536. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8537. return false;
  8538. Result = CV.FloatImag;
  8539. return true;
  8540. }
  8541. VisitIgnoredValue(E->getSubExpr());
  8542. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  8543. Result = llvm::APFloat::getZero(Sem);
  8544. return true;
  8545. }
  8546. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8547. switch (E->getOpcode()) {
  8548. default: return Error(E);
  8549. case UO_Plus:
  8550. return EvaluateFloat(E->getSubExpr(), Result, Info);
  8551. case UO_Minus:
  8552. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  8553. return false;
  8554. Result.changeSign();
  8555. return true;
  8556. }
  8557. }
  8558. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8559. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8560. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8561. APFloat RHS(0.0);
  8562. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  8563. if (!LHSOK && !Info.noteFailure())
  8564. return false;
  8565. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  8566. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  8567. }
  8568. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  8569. Result = E->getValue();
  8570. return true;
  8571. }
  8572. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8573. const Expr* SubExpr = E->getSubExpr();
  8574. switch (E->getCastKind()) {
  8575. default:
  8576. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8577. case CK_IntegralToFloating: {
  8578. APSInt IntResult;
  8579. return EvaluateInteger(SubExpr, IntResult, Info) &&
  8580. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  8581. E->getType(), Result);
  8582. }
  8583. case CK_FloatingCast: {
  8584. if (!Visit(SubExpr))
  8585. return false;
  8586. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  8587. Result);
  8588. }
  8589. case CK_FloatingComplexToReal: {
  8590. ComplexValue V;
  8591. if (!EvaluateComplex(SubExpr, V, Info))
  8592. return false;
  8593. Result = V.getComplexFloatReal();
  8594. return true;
  8595. }
  8596. }
  8597. }
  8598. //===----------------------------------------------------------------------===//
  8599. // Complex Evaluation (for float and integer)
  8600. //===----------------------------------------------------------------------===//
  8601. namespace {
  8602. class ComplexExprEvaluator
  8603. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  8604. ComplexValue &Result;
  8605. public:
  8606. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  8607. : ExprEvaluatorBaseTy(info), Result(Result) {}
  8608. bool Success(const APValue &V, const Expr *e) {
  8609. Result.setFrom(V);
  8610. return true;
  8611. }
  8612. bool ZeroInitialization(const Expr *E);
  8613. //===--------------------------------------------------------------------===//
  8614. // Visitor Methods
  8615. //===--------------------------------------------------------------------===//
  8616. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  8617. bool VisitCastExpr(const CastExpr *E);
  8618. bool VisitBinaryOperator(const BinaryOperator *E);
  8619. bool VisitUnaryOperator(const UnaryOperator *E);
  8620. bool VisitInitListExpr(const InitListExpr *E);
  8621. };
  8622. } // end anonymous namespace
  8623. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  8624. EvalInfo &Info) {
  8625. assert(E->isRValue() && E->getType()->isAnyComplexType());
  8626. return ComplexExprEvaluator(Info, Result).Visit(E);
  8627. }
  8628. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  8629. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  8630. if (ElemTy->isRealFloatingType()) {
  8631. Result.makeComplexFloat();
  8632. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  8633. Result.FloatReal = Zero;
  8634. Result.FloatImag = Zero;
  8635. } else {
  8636. Result.makeComplexInt();
  8637. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  8638. Result.IntReal = Zero;
  8639. Result.IntImag = Zero;
  8640. }
  8641. return true;
  8642. }
  8643. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  8644. const Expr* SubExpr = E->getSubExpr();
  8645. if (SubExpr->getType()->isRealFloatingType()) {
  8646. Result.makeComplexFloat();
  8647. APFloat &Imag = Result.FloatImag;
  8648. if (!EvaluateFloat(SubExpr, Imag, Info))
  8649. return false;
  8650. Result.FloatReal = APFloat(Imag.getSemantics());
  8651. return true;
  8652. } else {
  8653. assert(SubExpr->getType()->isIntegerType() &&
  8654. "Unexpected imaginary literal.");
  8655. Result.makeComplexInt();
  8656. APSInt &Imag = Result.IntImag;
  8657. if (!EvaluateInteger(SubExpr, Imag, Info))
  8658. return false;
  8659. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  8660. return true;
  8661. }
  8662. }
  8663. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8664. switch (E->getCastKind()) {
  8665. case CK_BitCast:
  8666. case CK_BaseToDerived:
  8667. case CK_DerivedToBase:
  8668. case CK_UncheckedDerivedToBase:
  8669. case CK_Dynamic:
  8670. case CK_ToUnion:
  8671. case CK_ArrayToPointerDecay:
  8672. case CK_FunctionToPointerDecay:
  8673. case CK_NullToPointer:
  8674. case CK_NullToMemberPointer:
  8675. case CK_BaseToDerivedMemberPointer:
  8676. case CK_DerivedToBaseMemberPointer:
  8677. case CK_MemberPointerToBoolean:
  8678. case CK_ReinterpretMemberPointer:
  8679. case CK_ConstructorConversion:
  8680. case CK_IntegralToPointer:
  8681. case CK_PointerToIntegral:
  8682. case CK_PointerToBoolean:
  8683. case CK_ToVoid:
  8684. case CK_VectorSplat:
  8685. case CK_IntegralCast:
  8686. case CK_BooleanToSignedIntegral:
  8687. case CK_IntegralToBoolean:
  8688. case CK_IntegralToFloating:
  8689. case CK_FloatingToIntegral:
  8690. case CK_FloatingToBoolean:
  8691. case CK_FloatingCast:
  8692. case CK_CPointerToObjCPointerCast:
  8693. case CK_BlockPointerToObjCPointerCast:
  8694. case CK_AnyPointerToBlockPointerCast:
  8695. case CK_ObjCObjectLValueCast:
  8696. case CK_FloatingComplexToReal:
  8697. case CK_FloatingComplexToBoolean:
  8698. case CK_IntegralComplexToReal:
  8699. case CK_IntegralComplexToBoolean:
  8700. case CK_ARCProduceObject:
  8701. case CK_ARCConsumeObject:
  8702. case CK_ARCReclaimReturnedObject:
  8703. case CK_ARCExtendBlockObject:
  8704. case CK_CopyAndAutoreleaseBlockObject:
  8705. case CK_BuiltinFnToFnPtr:
  8706. case CK_ZeroToOCLEvent:
  8707. case CK_ZeroToOCLQueue:
  8708. case CK_NonAtomicToAtomic:
  8709. case CK_AddressSpaceConversion:
  8710. case CK_IntToOCLSampler:
  8711. llvm_unreachable("invalid cast kind for complex value");
  8712. case CK_LValueToRValue:
  8713. case CK_AtomicToNonAtomic:
  8714. case CK_NoOp:
  8715. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8716. case CK_Dependent:
  8717. case CK_LValueBitCast:
  8718. case CK_UserDefinedConversion:
  8719. return Error(E);
  8720. case CK_FloatingRealToComplex: {
  8721. APFloat &Real = Result.FloatReal;
  8722. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  8723. return false;
  8724. Result.makeComplexFloat();
  8725. Result.FloatImag = APFloat(Real.getSemantics());
  8726. return true;
  8727. }
  8728. case CK_FloatingComplexCast: {
  8729. if (!Visit(E->getSubExpr()))
  8730. return false;
  8731. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8732. QualType From
  8733. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8734. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  8735. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  8736. }
  8737. case CK_FloatingComplexToIntegralComplex: {
  8738. if (!Visit(E->getSubExpr()))
  8739. return false;
  8740. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8741. QualType From
  8742. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8743. Result.makeComplexInt();
  8744. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  8745. To, Result.IntReal) &&
  8746. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  8747. To, Result.IntImag);
  8748. }
  8749. case CK_IntegralRealToComplex: {
  8750. APSInt &Real = Result.IntReal;
  8751. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  8752. return false;
  8753. Result.makeComplexInt();
  8754. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  8755. return true;
  8756. }
  8757. case CK_IntegralComplexCast: {
  8758. if (!Visit(E->getSubExpr()))
  8759. return false;
  8760. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8761. QualType From
  8762. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8763. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  8764. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  8765. return true;
  8766. }
  8767. case CK_IntegralComplexToFloatingComplex: {
  8768. if (!Visit(E->getSubExpr()))
  8769. return false;
  8770. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  8771. QualType From
  8772. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  8773. Result.makeComplexFloat();
  8774. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  8775. To, Result.FloatReal) &&
  8776. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  8777. To, Result.FloatImag);
  8778. }
  8779. }
  8780. llvm_unreachable("unknown cast resulting in complex value");
  8781. }
  8782. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8783. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8784. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8785. // Track whether the LHS or RHS is real at the type system level. When this is
  8786. // the case we can simplify our evaluation strategy.
  8787. bool LHSReal = false, RHSReal = false;
  8788. bool LHSOK;
  8789. if (E->getLHS()->getType()->isRealFloatingType()) {
  8790. LHSReal = true;
  8791. APFloat &Real = Result.FloatReal;
  8792. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  8793. if (LHSOK) {
  8794. Result.makeComplexFloat();
  8795. Result.FloatImag = APFloat(Real.getSemantics());
  8796. }
  8797. } else {
  8798. LHSOK = Visit(E->getLHS());
  8799. }
  8800. if (!LHSOK && !Info.noteFailure())
  8801. return false;
  8802. ComplexValue RHS;
  8803. if (E->getRHS()->getType()->isRealFloatingType()) {
  8804. RHSReal = true;
  8805. APFloat &Real = RHS.FloatReal;
  8806. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  8807. return false;
  8808. RHS.makeComplexFloat();
  8809. RHS.FloatImag = APFloat(Real.getSemantics());
  8810. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  8811. return false;
  8812. assert(!(LHSReal && RHSReal) &&
  8813. "Cannot have both operands of a complex operation be real.");
  8814. switch (E->getOpcode()) {
  8815. default: return Error(E);
  8816. case BO_Add:
  8817. if (Result.isComplexFloat()) {
  8818. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  8819. APFloat::rmNearestTiesToEven);
  8820. if (LHSReal)
  8821. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  8822. else if (!RHSReal)
  8823. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  8824. APFloat::rmNearestTiesToEven);
  8825. } else {
  8826. Result.getComplexIntReal() += RHS.getComplexIntReal();
  8827. Result.getComplexIntImag() += RHS.getComplexIntImag();
  8828. }
  8829. break;
  8830. case BO_Sub:
  8831. if (Result.isComplexFloat()) {
  8832. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  8833. APFloat::rmNearestTiesToEven);
  8834. if (LHSReal) {
  8835. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  8836. Result.getComplexFloatImag().changeSign();
  8837. } else if (!RHSReal) {
  8838. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  8839. APFloat::rmNearestTiesToEven);
  8840. }
  8841. } else {
  8842. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  8843. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  8844. }
  8845. break;
  8846. case BO_Mul:
  8847. if (Result.isComplexFloat()) {
  8848. // This is an implementation of complex multiplication according to the
  8849. // constraints laid out in C11 Annex G. The implemention uses the
  8850. // following naming scheme:
  8851. // (a + ib) * (c + id)
  8852. ComplexValue LHS = Result;
  8853. APFloat &A = LHS.getComplexFloatReal();
  8854. APFloat &B = LHS.getComplexFloatImag();
  8855. APFloat &C = RHS.getComplexFloatReal();
  8856. APFloat &D = RHS.getComplexFloatImag();
  8857. APFloat &ResR = Result.getComplexFloatReal();
  8858. APFloat &ResI = Result.getComplexFloatImag();
  8859. if (LHSReal) {
  8860. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  8861. ResR = A * C;
  8862. ResI = A * D;
  8863. } else if (RHSReal) {
  8864. ResR = C * A;
  8865. ResI = C * B;
  8866. } else {
  8867. // In the fully general case, we need to handle NaNs and infinities
  8868. // robustly.
  8869. APFloat AC = A * C;
  8870. APFloat BD = B * D;
  8871. APFloat AD = A * D;
  8872. APFloat BC = B * C;
  8873. ResR = AC - BD;
  8874. ResI = AD + BC;
  8875. if (ResR.isNaN() && ResI.isNaN()) {
  8876. bool Recalc = false;
  8877. if (A.isInfinity() || B.isInfinity()) {
  8878. A = APFloat::copySign(
  8879. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  8880. B = APFloat::copySign(
  8881. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  8882. if (C.isNaN())
  8883. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  8884. if (D.isNaN())
  8885. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  8886. Recalc = true;
  8887. }
  8888. if (C.isInfinity() || D.isInfinity()) {
  8889. C = APFloat::copySign(
  8890. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  8891. D = APFloat::copySign(
  8892. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  8893. if (A.isNaN())
  8894. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  8895. if (B.isNaN())
  8896. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  8897. Recalc = true;
  8898. }
  8899. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  8900. AD.isInfinity() || BC.isInfinity())) {
  8901. if (A.isNaN())
  8902. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  8903. if (B.isNaN())
  8904. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  8905. if (C.isNaN())
  8906. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  8907. if (D.isNaN())
  8908. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  8909. Recalc = true;
  8910. }
  8911. if (Recalc) {
  8912. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  8913. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  8914. }
  8915. }
  8916. }
  8917. } else {
  8918. ComplexValue LHS = Result;
  8919. Result.getComplexIntReal() =
  8920. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  8921. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  8922. Result.getComplexIntImag() =
  8923. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  8924. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  8925. }
  8926. break;
  8927. case BO_Div:
  8928. if (Result.isComplexFloat()) {
  8929. // This is an implementation of complex division according to the
  8930. // constraints laid out in C11 Annex G. The implemention uses the
  8931. // following naming scheme:
  8932. // (a + ib) / (c + id)
  8933. ComplexValue LHS = Result;
  8934. APFloat &A = LHS.getComplexFloatReal();
  8935. APFloat &B = LHS.getComplexFloatImag();
  8936. APFloat &C = RHS.getComplexFloatReal();
  8937. APFloat &D = RHS.getComplexFloatImag();
  8938. APFloat &ResR = Result.getComplexFloatReal();
  8939. APFloat &ResI = Result.getComplexFloatImag();
  8940. if (RHSReal) {
  8941. ResR = A / C;
  8942. ResI = B / C;
  8943. } else {
  8944. if (LHSReal) {
  8945. // No real optimizations we can do here, stub out with zero.
  8946. B = APFloat::getZero(A.getSemantics());
  8947. }
  8948. int DenomLogB = 0;
  8949. APFloat MaxCD = maxnum(abs(C), abs(D));
  8950. if (MaxCD.isFinite()) {
  8951. DenomLogB = ilogb(MaxCD);
  8952. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  8953. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  8954. }
  8955. APFloat Denom = C * C + D * D;
  8956. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  8957. APFloat::rmNearestTiesToEven);
  8958. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  8959. APFloat::rmNearestTiesToEven);
  8960. if (ResR.isNaN() && ResI.isNaN()) {
  8961. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  8962. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  8963. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  8964. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  8965. D.isFinite()) {
  8966. A = APFloat::copySign(
  8967. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  8968. B = APFloat::copySign(
  8969. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  8970. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  8971. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  8972. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  8973. C = APFloat::copySign(
  8974. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  8975. D = APFloat::copySign(
  8976. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  8977. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  8978. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  8979. }
  8980. }
  8981. }
  8982. } else {
  8983. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  8984. return Error(E, diag::note_expr_divide_by_zero);
  8985. ComplexValue LHS = Result;
  8986. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  8987. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  8988. Result.getComplexIntReal() =
  8989. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  8990. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  8991. Result.getComplexIntImag() =
  8992. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  8993. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  8994. }
  8995. break;
  8996. }
  8997. return true;
  8998. }
  8999. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9000. // Get the operand value into 'Result'.
  9001. if (!Visit(E->getSubExpr()))
  9002. return false;
  9003. switch (E->getOpcode()) {
  9004. default:
  9005. return Error(E);
  9006. case UO_Extension:
  9007. return true;
  9008. case UO_Plus:
  9009. // The result is always just the subexpr.
  9010. return true;
  9011. case UO_Minus:
  9012. if (Result.isComplexFloat()) {
  9013. Result.getComplexFloatReal().changeSign();
  9014. Result.getComplexFloatImag().changeSign();
  9015. }
  9016. else {
  9017. Result.getComplexIntReal() = -Result.getComplexIntReal();
  9018. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9019. }
  9020. return true;
  9021. case UO_Not:
  9022. if (Result.isComplexFloat())
  9023. Result.getComplexFloatImag().changeSign();
  9024. else
  9025. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9026. return true;
  9027. }
  9028. }
  9029. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  9030. if (E->getNumInits() == 2) {
  9031. if (E->getType()->isComplexType()) {
  9032. Result.makeComplexFloat();
  9033. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  9034. return false;
  9035. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  9036. return false;
  9037. } else {
  9038. Result.makeComplexInt();
  9039. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  9040. return false;
  9041. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  9042. return false;
  9043. }
  9044. return true;
  9045. }
  9046. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  9047. }
  9048. //===----------------------------------------------------------------------===//
  9049. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  9050. // implicit conversion.
  9051. //===----------------------------------------------------------------------===//
  9052. namespace {
  9053. class AtomicExprEvaluator :
  9054. public ExprEvaluatorBase<AtomicExprEvaluator> {
  9055. const LValue *This;
  9056. APValue &Result;
  9057. public:
  9058. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  9059. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  9060. bool Success(const APValue &V, const Expr *E) {
  9061. Result = V;
  9062. return true;
  9063. }
  9064. bool ZeroInitialization(const Expr *E) {
  9065. ImplicitValueInitExpr VIE(
  9066. E->getType()->castAs<AtomicType>()->getValueType());
  9067. // For atomic-qualified class (and array) types in C++, initialize the
  9068. // _Atomic-wrapped subobject directly, in-place.
  9069. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  9070. : Evaluate(Result, Info, &VIE);
  9071. }
  9072. bool VisitCastExpr(const CastExpr *E) {
  9073. switch (E->getCastKind()) {
  9074. default:
  9075. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9076. case CK_NonAtomicToAtomic:
  9077. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  9078. : Evaluate(Result, Info, E->getSubExpr());
  9079. }
  9080. }
  9081. };
  9082. } // end anonymous namespace
  9083. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  9084. EvalInfo &Info) {
  9085. assert(E->isRValue() && E->getType()->isAtomicType());
  9086. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  9087. }
  9088. //===----------------------------------------------------------------------===//
  9089. // Void expression evaluation, primarily for a cast to void on the LHS of a
  9090. // comma operator
  9091. //===----------------------------------------------------------------------===//
  9092. namespace {
  9093. class VoidExprEvaluator
  9094. : public ExprEvaluatorBase<VoidExprEvaluator> {
  9095. public:
  9096. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  9097. bool Success(const APValue &V, const Expr *e) { return true; }
  9098. bool ZeroInitialization(const Expr *E) { return true; }
  9099. bool VisitCastExpr(const CastExpr *E) {
  9100. switch (E->getCastKind()) {
  9101. default:
  9102. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9103. case CK_ToVoid:
  9104. VisitIgnoredValue(E->getSubExpr());
  9105. return true;
  9106. }
  9107. }
  9108. bool VisitCallExpr(const CallExpr *E) {
  9109. switch (E->getBuiltinCallee()) {
  9110. default:
  9111. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9112. case Builtin::BI__assume:
  9113. case Builtin::BI__builtin_assume:
  9114. // The argument is not evaluated!
  9115. return true;
  9116. }
  9117. }
  9118. };
  9119. } // end anonymous namespace
  9120. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  9121. assert(E->isRValue() && E->getType()->isVoidType());
  9122. return VoidExprEvaluator(Info).Visit(E);
  9123. }
  9124. //===----------------------------------------------------------------------===//
  9125. // Top level Expr::EvaluateAsRValue method.
  9126. //===----------------------------------------------------------------------===//
  9127. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  9128. // In C, function designators are not lvalues, but we evaluate them as if they
  9129. // are.
  9130. QualType T = E->getType();
  9131. if (E->isGLValue() || T->isFunctionType()) {
  9132. LValue LV;
  9133. if (!EvaluateLValue(E, LV, Info))
  9134. return false;
  9135. LV.moveInto(Result);
  9136. } else if (T->isVectorType()) {
  9137. if (!EvaluateVector(E, Result, Info))
  9138. return false;
  9139. } else if (T->isIntegralOrEnumerationType()) {
  9140. if (!IntExprEvaluator(Info, Result).Visit(E))
  9141. return false;
  9142. } else if (T->hasPointerRepresentation()) {
  9143. LValue LV;
  9144. if (!EvaluatePointer(E, LV, Info))
  9145. return false;
  9146. LV.moveInto(Result);
  9147. } else if (T->isRealFloatingType()) {
  9148. llvm::APFloat F(0.0);
  9149. if (!EvaluateFloat(E, F, Info))
  9150. return false;
  9151. Result = APValue(F);
  9152. } else if (T->isAnyComplexType()) {
  9153. ComplexValue C;
  9154. if (!EvaluateComplex(E, C, Info))
  9155. return false;
  9156. C.moveInto(Result);
  9157. } else if (T->isFixedPointType()) {
  9158. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  9159. } else if (T->isMemberPointerType()) {
  9160. MemberPtr P;
  9161. if (!EvaluateMemberPointer(E, P, Info))
  9162. return false;
  9163. P.moveInto(Result);
  9164. return true;
  9165. } else if (T->isArrayType()) {
  9166. LValue LV;
  9167. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9168. if (!EvaluateArray(E, LV, Value, Info))
  9169. return false;
  9170. Result = Value;
  9171. } else if (T->isRecordType()) {
  9172. LValue LV;
  9173. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9174. if (!EvaluateRecord(E, LV, Value, Info))
  9175. return false;
  9176. Result = Value;
  9177. } else if (T->isVoidType()) {
  9178. if (!Info.getLangOpts().CPlusPlus11)
  9179. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  9180. << E->getType();
  9181. if (!EvaluateVoid(E, Info))
  9182. return false;
  9183. } else if (T->isAtomicType()) {
  9184. QualType Unqual = T.getAtomicUnqualifiedType();
  9185. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  9186. LValue LV;
  9187. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9188. if (!EvaluateAtomic(E, &LV, Value, Info))
  9189. return false;
  9190. } else {
  9191. if (!EvaluateAtomic(E, nullptr, Result, Info))
  9192. return false;
  9193. }
  9194. } else if (Info.getLangOpts().CPlusPlus11) {
  9195. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  9196. return false;
  9197. } else {
  9198. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9199. return false;
  9200. }
  9201. return true;
  9202. }
  9203. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  9204. /// cases, the in-place evaluation is essential, since later initializers for
  9205. /// an object can indirectly refer to subobjects which were initialized earlier.
  9206. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  9207. const Expr *E, bool AllowNonLiteralTypes) {
  9208. assert(!E->isValueDependent());
  9209. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  9210. return false;
  9211. if (E->isRValue()) {
  9212. // Evaluate arrays and record types in-place, so that later initializers can
  9213. // refer to earlier-initialized members of the object.
  9214. QualType T = E->getType();
  9215. if (T->isArrayType())
  9216. return EvaluateArray(E, This, Result, Info);
  9217. else if (T->isRecordType())
  9218. return EvaluateRecord(E, This, Result, Info);
  9219. else if (T->isAtomicType()) {
  9220. QualType Unqual = T.getAtomicUnqualifiedType();
  9221. if (Unqual->isArrayType() || Unqual->isRecordType())
  9222. return EvaluateAtomic(E, &This, Result, Info);
  9223. }
  9224. }
  9225. // For any other type, in-place evaluation is unimportant.
  9226. return Evaluate(Result, Info, E);
  9227. }
  9228. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  9229. /// lvalue-to-rvalue cast if it is an lvalue.
  9230. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  9231. if (E->getType().isNull())
  9232. return false;
  9233. if (!CheckLiteralType(Info, E))
  9234. return false;
  9235. if (!::Evaluate(Result, Info, E))
  9236. return false;
  9237. if (E->isGLValue()) {
  9238. LValue LV;
  9239. LV.setFrom(Info.Ctx, Result);
  9240. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  9241. return false;
  9242. }
  9243. // Check this core constant expression is a constant expression.
  9244. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  9245. }
  9246. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  9247. const ASTContext &Ctx, bool &IsConst) {
  9248. // Fast-path evaluations of integer literals, since we sometimes see files
  9249. // containing vast quantities of these.
  9250. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  9251. Result.Val = APValue(APSInt(L->getValue(),
  9252. L->getType()->isUnsignedIntegerType()));
  9253. IsConst = true;
  9254. return true;
  9255. }
  9256. // This case should be rare, but we need to check it before we check on
  9257. // the type below.
  9258. if (Exp->getType().isNull()) {
  9259. IsConst = false;
  9260. return true;
  9261. }
  9262. // FIXME: Evaluating values of large array and record types can cause
  9263. // performance problems. Only do so in C++11 for now.
  9264. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  9265. Exp->getType()->isRecordType()) &&
  9266. !Ctx.getLangOpts().CPlusPlus11) {
  9267. IsConst = false;
  9268. return true;
  9269. }
  9270. return false;
  9271. }
  9272. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  9273. /// any crazy technique (that has nothing to do with language standards) that
  9274. /// we want to. If this function returns true, it returns the folded constant
  9275. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  9276. /// will be applied to the result.
  9277. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  9278. bool IsConst;
  9279. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
  9280. return IsConst;
  9281. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  9282. return ::EvaluateAsRValue(Info, this, Result.Val);
  9283. }
  9284. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  9285. const ASTContext &Ctx) const {
  9286. EvalResult Scratch;
  9287. return EvaluateAsRValue(Scratch, Ctx) &&
  9288. HandleConversionToBool(Scratch.Val, Result);
  9289. }
  9290. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  9291. Expr::SideEffectsKind SEK) {
  9292. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  9293. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  9294. }
  9295. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  9296. SideEffectsKind AllowSideEffects) const {
  9297. if (!getType()->isIntegralOrEnumerationType())
  9298. return false;
  9299. EvalResult ExprResult;
  9300. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  9301. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9302. return false;
  9303. Result = ExprResult.Val.getInt();
  9304. return true;
  9305. }
  9306. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  9307. SideEffectsKind AllowSideEffects) const {
  9308. if (!getType()->isRealFloatingType())
  9309. return false;
  9310. EvalResult ExprResult;
  9311. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
  9312. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9313. return false;
  9314. Result = ExprResult.Val.getFloat();
  9315. return true;
  9316. }
  9317. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  9318. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  9319. LValue LV;
  9320. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  9321. !CheckLValueConstantExpression(Info, getExprLoc(),
  9322. Ctx.getLValueReferenceType(getType()), LV,
  9323. Expr::EvaluateForCodeGen))
  9324. return false;
  9325. LV.moveInto(Result.Val);
  9326. return true;
  9327. }
  9328. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  9329. const ASTContext &Ctx) const {
  9330. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  9331. EvalInfo Info(Ctx, Result, EM);
  9332. if (!::Evaluate(Result.Val, Info, this))
  9333. return false;
  9334. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  9335. Usage);
  9336. }
  9337. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  9338. const VarDecl *VD,
  9339. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  9340. // FIXME: Evaluating initializers for large array and record types can cause
  9341. // performance problems. Only do so in C++11 for now.
  9342. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  9343. !Ctx.getLangOpts().CPlusPlus11)
  9344. return false;
  9345. Expr::EvalStatus EStatus;
  9346. EStatus.Diag = &Notes;
  9347. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  9348. ? EvalInfo::EM_ConstantExpression
  9349. : EvalInfo::EM_ConstantFold);
  9350. InitInfo.setEvaluatingDecl(VD, Value);
  9351. LValue LVal;
  9352. LVal.set(VD);
  9353. // C++11 [basic.start.init]p2:
  9354. // Variables with static storage duration or thread storage duration shall be
  9355. // zero-initialized before any other initialization takes place.
  9356. // This behavior is not present in C.
  9357. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  9358. !VD->getType()->isReferenceType()) {
  9359. ImplicitValueInitExpr VIE(VD->getType());
  9360. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  9361. /*AllowNonLiteralTypes=*/true))
  9362. return false;
  9363. }
  9364. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  9365. /*AllowNonLiteralTypes=*/true) ||
  9366. EStatus.HasSideEffects)
  9367. return false;
  9368. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  9369. Value);
  9370. }
  9371. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  9372. /// constant folded, but discard the result.
  9373. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  9374. EvalResult Result;
  9375. return EvaluateAsRValue(Result, Ctx) &&
  9376. !hasUnacceptableSideEffect(Result, SEK);
  9377. }
  9378. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  9379. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  9380. EvalResult EvalResult;
  9381. EvalResult.Diag = Diag;
  9382. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  9383. (void)Result;
  9384. assert(Result && "Could not evaluate expression");
  9385. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  9386. return EvalResult.Val.getInt();
  9387. }
  9388. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  9389. bool IsConst;
  9390. EvalResult EvalResult;
  9391. if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
  9392. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  9393. (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
  9394. }
  9395. }
  9396. bool Expr::EvalResult::isGlobalLValue() const {
  9397. assert(Val.isLValue());
  9398. return IsGlobalLValue(Val.getLValueBase());
  9399. }
  9400. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  9401. /// an integer constant expression.
  9402. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  9403. /// comma, etc
  9404. // CheckICE - This function does the fundamental ICE checking: the returned
  9405. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  9406. // and a (possibly null) SourceLocation indicating the location of the problem.
  9407. //
  9408. // Note that to reduce code duplication, this helper does no evaluation
  9409. // itself; the caller checks whether the expression is evaluatable, and
  9410. // in the rare cases where CheckICE actually cares about the evaluated
  9411. // value, it calls into Evaluate.
  9412. namespace {
  9413. enum ICEKind {
  9414. /// This expression is an ICE.
  9415. IK_ICE,
  9416. /// This expression is not an ICE, but if it isn't evaluated, it's
  9417. /// a legal subexpression for an ICE. This return value is used to handle
  9418. /// the comma operator in C99 mode, and non-constant subexpressions.
  9419. IK_ICEIfUnevaluated,
  9420. /// This expression is not an ICE, and is not a legal subexpression for one.
  9421. IK_NotICE
  9422. };
  9423. struct ICEDiag {
  9424. ICEKind Kind;
  9425. SourceLocation Loc;
  9426. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  9427. };
  9428. }
  9429. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  9430. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  9431. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  9432. Expr::EvalResult EVResult;
  9433. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  9434. !EVResult.Val.isInt())
  9435. return ICEDiag(IK_NotICE, E->getLocStart());
  9436. return NoDiag();
  9437. }
  9438. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  9439. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  9440. if (!E->getType()->isIntegralOrEnumerationType())
  9441. return ICEDiag(IK_NotICE, E->getLocStart());
  9442. switch (E->getStmtClass()) {
  9443. #define ABSTRACT_STMT(Node)
  9444. #define STMT(Node, Base) case Expr::Node##Class:
  9445. #define EXPR(Node, Base)
  9446. #include "clang/AST/StmtNodes.inc"
  9447. case Expr::PredefinedExprClass:
  9448. case Expr::FloatingLiteralClass:
  9449. case Expr::ImaginaryLiteralClass:
  9450. case Expr::StringLiteralClass:
  9451. case Expr::ArraySubscriptExprClass:
  9452. case Expr::OMPArraySectionExprClass:
  9453. case Expr::MemberExprClass:
  9454. case Expr::CompoundAssignOperatorClass:
  9455. case Expr::CompoundLiteralExprClass:
  9456. case Expr::ExtVectorElementExprClass:
  9457. case Expr::DesignatedInitExprClass:
  9458. case Expr::ArrayInitLoopExprClass:
  9459. case Expr::ArrayInitIndexExprClass:
  9460. case Expr::NoInitExprClass:
  9461. case Expr::DesignatedInitUpdateExprClass:
  9462. case Expr::ImplicitValueInitExprClass:
  9463. case Expr::ParenListExprClass:
  9464. case Expr::VAArgExprClass:
  9465. case Expr::AddrLabelExprClass:
  9466. case Expr::StmtExprClass:
  9467. case Expr::CXXMemberCallExprClass:
  9468. case Expr::CUDAKernelCallExprClass:
  9469. case Expr::CXXDynamicCastExprClass:
  9470. case Expr::CXXTypeidExprClass:
  9471. case Expr::CXXUuidofExprClass:
  9472. case Expr::MSPropertyRefExprClass:
  9473. case Expr::MSPropertySubscriptExprClass:
  9474. case Expr::CXXNullPtrLiteralExprClass:
  9475. case Expr::UserDefinedLiteralClass:
  9476. case Expr::CXXThisExprClass:
  9477. case Expr::CXXThrowExprClass:
  9478. case Expr::CXXNewExprClass:
  9479. case Expr::CXXDeleteExprClass:
  9480. case Expr::CXXPseudoDestructorExprClass:
  9481. case Expr::UnresolvedLookupExprClass:
  9482. case Expr::TypoExprClass:
  9483. case Expr::DependentScopeDeclRefExprClass:
  9484. case Expr::CXXConstructExprClass:
  9485. case Expr::CXXInheritedCtorInitExprClass:
  9486. case Expr::CXXStdInitializerListExprClass:
  9487. case Expr::CXXBindTemporaryExprClass:
  9488. case Expr::ExprWithCleanupsClass:
  9489. case Expr::CXXTemporaryObjectExprClass:
  9490. case Expr::CXXUnresolvedConstructExprClass:
  9491. case Expr::CXXDependentScopeMemberExprClass:
  9492. case Expr::UnresolvedMemberExprClass:
  9493. case Expr::ObjCStringLiteralClass:
  9494. case Expr::ObjCBoxedExprClass:
  9495. case Expr::ObjCArrayLiteralClass:
  9496. case Expr::ObjCDictionaryLiteralClass:
  9497. case Expr::ObjCEncodeExprClass:
  9498. case Expr::ObjCMessageExprClass:
  9499. case Expr::ObjCSelectorExprClass:
  9500. case Expr::ObjCProtocolExprClass:
  9501. case Expr::ObjCIvarRefExprClass:
  9502. case Expr::ObjCPropertyRefExprClass:
  9503. case Expr::ObjCSubscriptRefExprClass:
  9504. case Expr::ObjCIsaExprClass:
  9505. case Expr::ObjCAvailabilityCheckExprClass:
  9506. case Expr::ShuffleVectorExprClass:
  9507. case Expr::ConvertVectorExprClass:
  9508. case Expr::BlockExprClass:
  9509. case Expr::NoStmtClass:
  9510. case Expr::OpaqueValueExprClass:
  9511. case Expr::PackExpansionExprClass:
  9512. case Expr::SubstNonTypeTemplateParmPackExprClass:
  9513. case Expr::FunctionParmPackExprClass:
  9514. case Expr::AsTypeExprClass:
  9515. case Expr::ObjCIndirectCopyRestoreExprClass:
  9516. case Expr::MaterializeTemporaryExprClass:
  9517. case Expr::PseudoObjectExprClass:
  9518. case Expr::AtomicExprClass:
  9519. case Expr::LambdaExprClass:
  9520. case Expr::CXXFoldExprClass:
  9521. case Expr::CoawaitExprClass:
  9522. case Expr::DependentCoawaitExprClass:
  9523. case Expr::CoyieldExprClass:
  9524. return ICEDiag(IK_NotICE, E->getLocStart());
  9525. case Expr::InitListExprClass: {
  9526. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  9527. // form "T x = { a };" is equivalent to "T x = a;".
  9528. // Unless we're initializing a reference, T is a scalar as it is known to be
  9529. // of integral or enumeration type.
  9530. if (E->isRValue())
  9531. if (cast<InitListExpr>(E)->getNumInits() == 1)
  9532. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  9533. return ICEDiag(IK_NotICE, E->getLocStart());
  9534. }
  9535. case Expr::SizeOfPackExprClass:
  9536. case Expr::GNUNullExprClass:
  9537. // GCC considers the GNU __null value to be an integral constant expression.
  9538. return NoDiag();
  9539. case Expr::SubstNonTypeTemplateParmExprClass:
  9540. return
  9541. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  9542. case Expr::ParenExprClass:
  9543. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  9544. case Expr::GenericSelectionExprClass:
  9545. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  9546. case Expr::IntegerLiteralClass:
  9547. case Expr::FixedPointLiteralClass:
  9548. case Expr::CharacterLiteralClass:
  9549. case Expr::ObjCBoolLiteralExprClass:
  9550. case Expr::CXXBoolLiteralExprClass:
  9551. case Expr::CXXScalarValueInitExprClass:
  9552. case Expr::TypeTraitExprClass:
  9553. case Expr::ArrayTypeTraitExprClass:
  9554. case Expr::ExpressionTraitExprClass:
  9555. case Expr::CXXNoexceptExprClass:
  9556. return NoDiag();
  9557. case Expr::CallExprClass:
  9558. case Expr::CXXOperatorCallExprClass: {
  9559. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  9560. // constant expressions, but they can never be ICEs because an ICE cannot
  9561. // contain an operand of (pointer to) function type.
  9562. const CallExpr *CE = cast<CallExpr>(E);
  9563. if (CE->getBuiltinCallee())
  9564. return CheckEvalInICE(E, Ctx);
  9565. return ICEDiag(IK_NotICE, E->getLocStart());
  9566. }
  9567. case Expr::DeclRefExprClass: {
  9568. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  9569. return NoDiag();
  9570. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  9571. if (Ctx.getLangOpts().CPlusPlus &&
  9572. D && IsConstNonVolatile(D->getType())) {
  9573. // Parameter variables are never constants. Without this check,
  9574. // getAnyInitializer() can find a default argument, which leads
  9575. // to chaos.
  9576. if (isa<ParmVarDecl>(D))
  9577. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9578. // C++ 7.1.5.1p2
  9579. // A variable of non-volatile const-qualified integral or enumeration
  9580. // type initialized by an ICE can be used in ICEs.
  9581. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  9582. if (!Dcl->getType()->isIntegralOrEnumerationType())
  9583. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9584. const VarDecl *VD;
  9585. // Look for a declaration of this variable that has an initializer, and
  9586. // check whether it is an ICE.
  9587. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  9588. return NoDiag();
  9589. else
  9590. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9591. }
  9592. }
  9593. return ICEDiag(IK_NotICE, E->getLocStart());
  9594. }
  9595. case Expr::UnaryOperatorClass: {
  9596. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  9597. switch (Exp->getOpcode()) {
  9598. case UO_PostInc:
  9599. case UO_PostDec:
  9600. case UO_PreInc:
  9601. case UO_PreDec:
  9602. case UO_AddrOf:
  9603. case UO_Deref:
  9604. case UO_Coawait:
  9605. // C99 6.6/3 allows increment and decrement within unevaluated
  9606. // subexpressions of constant expressions, but they can never be ICEs
  9607. // because an ICE cannot contain an lvalue operand.
  9608. return ICEDiag(IK_NotICE, E->getLocStart());
  9609. case UO_Extension:
  9610. case UO_LNot:
  9611. case UO_Plus:
  9612. case UO_Minus:
  9613. case UO_Not:
  9614. case UO_Real:
  9615. case UO_Imag:
  9616. return CheckICE(Exp->getSubExpr(), Ctx);
  9617. }
  9618. // OffsetOf falls through here.
  9619. LLVM_FALLTHROUGH;
  9620. }
  9621. case Expr::OffsetOfExprClass: {
  9622. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  9623. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  9624. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  9625. // compliance: we should warn earlier for offsetof expressions with
  9626. // array subscripts that aren't ICEs, and if the array subscripts
  9627. // are ICEs, the value of the offsetof must be an integer constant.
  9628. return CheckEvalInICE(E, Ctx);
  9629. }
  9630. case Expr::UnaryExprOrTypeTraitExprClass: {
  9631. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  9632. if ((Exp->getKind() == UETT_SizeOf) &&
  9633. Exp->getTypeOfArgument()->isVariableArrayType())
  9634. return ICEDiag(IK_NotICE, E->getLocStart());
  9635. return NoDiag();
  9636. }
  9637. case Expr::BinaryOperatorClass: {
  9638. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  9639. switch (Exp->getOpcode()) {
  9640. case BO_PtrMemD:
  9641. case BO_PtrMemI:
  9642. case BO_Assign:
  9643. case BO_MulAssign:
  9644. case BO_DivAssign:
  9645. case BO_RemAssign:
  9646. case BO_AddAssign:
  9647. case BO_SubAssign:
  9648. case BO_ShlAssign:
  9649. case BO_ShrAssign:
  9650. case BO_AndAssign:
  9651. case BO_XorAssign:
  9652. case BO_OrAssign:
  9653. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  9654. // constant expressions, but they can never be ICEs because an ICE cannot
  9655. // contain an lvalue operand.
  9656. return ICEDiag(IK_NotICE, E->getLocStart());
  9657. case BO_Mul:
  9658. case BO_Div:
  9659. case BO_Rem:
  9660. case BO_Add:
  9661. case BO_Sub:
  9662. case BO_Shl:
  9663. case BO_Shr:
  9664. case BO_LT:
  9665. case BO_GT:
  9666. case BO_LE:
  9667. case BO_GE:
  9668. case BO_EQ:
  9669. case BO_NE:
  9670. case BO_And:
  9671. case BO_Xor:
  9672. case BO_Or:
  9673. case BO_Comma:
  9674. case BO_Cmp: {
  9675. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9676. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9677. if (Exp->getOpcode() == BO_Div ||
  9678. Exp->getOpcode() == BO_Rem) {
  9679. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  9680. // we don't evaluate one.
  9681. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  9682. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  9683. if (REval == 0)
  9684. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  9685. if (REval.isSigned() && REval.isAllOnesValue()) {
  9686. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  9687. if (LEval.isMinSignedValue())
  9688. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  9689. }
  9690. }
  9691. }
  9692. if (Exp->getOpcode() == BO_Comma) {
  9693. if (Ctx.getLangOpts().C99) {
  9694. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  9695. // if it isn't evaluated.
  9696. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  9697. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  9698. } else {
  9699. // In both C89 and C++, commas in ICEs are illegal.
  9700. return ICEDiag(IK_NotICE, E->getLocStart());
  9701. }
  9702. }
  9703. return Worst(LHSResult, RHSResult);
  9704. }
  9705. case BO_LAnd:
  9706. case BO_LOr: {
  9707. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9708. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9709. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  9710. // Rare case where the RHS has a comma "side-effect"; we need
  9711. // to actually check the condition to see whether the side
  9712. // with the comma is evaluated.
  9713. if ((Exp->getOpcode() == BO_LAnd) !=
  9714. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  9715. return RHSResult;
  9716. return NoDiag();
  9717. }
  9718. return Worst(LHSResult, RHSResult);
  9719. }
  9720. }
  9721. LLVM_FALLTHROUGH;
  9722. }
  9723. case Expr::ImplicitCastExprClass:
  9724. case Expr::CStyleCastExprClass:
  9725. case Expr::CXXFunctionalCastExprClass:
  9726. case Expr::CXXStaticCastExprClass:
  9727. case Expr::CXXReinterpretCastExprClass:
  9728. case Expr::CXXConstCastExprClass:
  9729. case Expr::ObjCBridgedCastExprClass: {
  9730. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  9731. if (isa<ExplicitCastExpr>(E)) {
  9732. if (const FloatingLiteral *FL
  9733. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  9734. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  9735. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  9736. APSInt IgnoredVal(DestWidth, !DestSigned);
  9737. bool Ignored;
  9738. // If the value does not fit in the destination type, the behavior is
  9739. // undefined, so we are not required to treat it as a constant
  9740. // expression.
  9741. if (FL->getValue().convertToInteger(IgnoredVal,
  9742. llvm::APFloat::rmTowardZero,
  9743. &Ignored) & APFloat::opInvalidOp)
  9744. return ICEDiag(IK_NotICE, E->getLocStart());
  9745. return NoDiag();
  9746. }
  9747. }
  9748. switch (cast<CastExpr>(E)->getCastKind()) {
  9749. case CK_LValueToRValue:
  9750. case CK_AtomicToNonAtomic:
  9751. case CK_NonAtomicToAtomic:
  9752. case CK_NoOp:
  9753. case CK_IntegralToBoolean:
  9754. case CK_IntegralCast:
  9755. return CheckICE(SubExpr, Ctx);
  9756. default:
  9757. return ICEDiag(IK_NotICE, E->getLocStart());
  9758. }
  9759. }
  9760. case Expr::BinaryConditionalOperatorClass: {
  9761. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  9762. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  9763. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  9764. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9765. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  9766. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  9767. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  9768. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  9769. return FalseResult;
  9770. }
  9771. case Expr::ConditionalOperatorClass: {
  9772. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  9773. // If the condition (ignoring parens) is a __builtin_constant_p call,
  9774. // then only the true side is actually considered in an integer constant
  9775. // expression, and it is fully evaluated. This is an important GNU
  9776. // extension. See GCC PR38377 for discussion.
  9777. if (const CallExpr *CallCE
  9778. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  9779. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  9780. return CheckEvalInICE(E, Ctx);
  9781. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  9782. if (CondResult.Kind == IK_NotICE)
  9783. return CondResult;
  9784. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  9785. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9786. if (TrueResult.Kind == IK_NotICE)
  9787. return TrueResult;
  9788. if (FalseResult.Kind == IK_NotICE)
  9789. return FalseResult;
  9790. if (CondResult.Kind == IK_ICEIfUnevaluated)
  9791. return CondResult;
  9792. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  9793. return NoDiag();
  9794. // Rare case where the diagnostics depend on which side is evaluated
  9795. // Note that if we get here, CondResult is 0, and at least one of
  9796. // TrueResult and FalseResult is non-zero.
  9797. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  9798. return FalseResult;
  9799. return TrueResult;
  9800. }
  9801. case Expr::CXXDefaultArgExprClass:
  9802. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  9803. case Expr::CXXDefaultInitExprClass:
  9804. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  9805. case Expr::ChooseExprClass: {
  9806. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  9807. }
  9808. }
  9809. llvm_unreachable("Invalid StmtClass!");
  9810. }
  9811. /// Evaluate an expression as a C++11 integral constant expression.
  9812. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  9813. const Expr *E,
  9814. llvm::APSInt *Value,
  9815. SourceLocation *Loc) {
  9816. if (!E->getType()->isIntegralOrEnumerationType()) {
  9817. if (Loc) *Loc = E->getExprLoc();
  9818. return false;
  9819. }
  9820. APValue Result;
  9821. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  9822. return false;
  9823. if (!Result.isInt()) {
  9824. if (Loc) *Loc = E->getExprLoc();
  9825. return false;
  9826. }
  9827. if (Value) *Value = Result.getInt();
  9828. return true;
  9829. }
  9830. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  9831. SourceLocation *Loc) const {
  9832. if (Ctx.getLangOpts().CPlusPlus11)
  9833. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  9834. ICEDiag D = CheckICE(this, Ctx);
  9835. if (D.Kind != IK_ICE) {
  9836. if (Loc) *Loc = D.Loc;
  9837. return false;
  9838. }
  9839. return true;
  9840. }
  9841. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  9842. SourceLocation *Loc, bool isEvaluated) const {
  9843. if (Ctx.getLangOpts().CPlusPlus11)
  9844. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  9845. if (!isIntegerConstantExpr(Ctx, Loc))
  9846. return false;
  9847. // The only possible side-effects here are due to UB discovered in the
  9848. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  9849. // required to treat the expression as an ICE, so we produce the folded
  9850. // value.
  9851. if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
  9852. llvm_unreachable("ICE cannot be evaluated!");
  9853. return true;
  9854. }
  9855. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  9856. return CheckICE(this, Ctx).Kind == IK_ICE;
  9857. }
  9858. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  9859. SourceLocation *Loc) const {
  9860. // We support this checking in C++98 mode in order to diagnose compatibility
  9861. // issues.
  9862. assert(Ctx.getLangOpts().CPlusPlus);
  9863. // Build evaluation settings.
  9864. Expr::EvalStatus Status;
  9865. SmallVector<PartialDiagnosticAt, 8> Diags;
  9866. Status.Diag = &Diags;
  9867. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  9868. APValue Scratch;
  9869. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  9870. if (!Diags.empty()) {
  9871. IsConstExpr = false;
  9872. if (Loc) *Loc = Diags[0].first;
  9873. } else if (!IsConstExpr) {
  9874. // FIXME: This shouldn't happen.
  9875. if (Loc) *Loc = getExprLoc();
  9876. }
  9877. return IsConstExpr;
  9878. }
  9879. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  9880. const FunctionDecl *Callee,
  9881. ArrayRef<const Expr*> Args,
  9882. const Expr *This) const {
  9883. Expr::EvalStatus Status;
  9884. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  9885. LValue ThisVal;
  9886. const LValue *ThisPtr = nullptr;
  9887. if (This) {
  9888. #ifndef NDEBUG
  9889. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  9890. assert(MD && "Don't provide `this` for non-methods.");
  9891. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  9892. #endif
  9893. if (EvaluateObjectArgument(Info, This, ThisVal))
  9894. ThisPtr = &ThisVal;
  9895. if (Info.EvalStatus.HasSideEffects)
  9896. return false;
  9897. }
  9898. ArgVector ArgValues(Args.size());
  9899. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  9900. I != E; ++I) {
  9901. if ((*I)->isValueDependent() ||
  9902. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  9903. // If evaluation fails, throw away the argument entirely.
  9904. ArgValues[I - Args.begin()] = APValue();
  9905. if (Info.EvalStatus.HasSideEffects)
  9906. return false;
  9907. }
  9908. // Build fake call to Callee.
  9909. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  9910. ArgValues.data());
  9911. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  9912. }
  9913. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  9914. SmallVectorImpl<
  9915. PartialDiagnosticAt> &Diags) {
  9916. // FIXME: It would be useful to check constexpr function templates, but at the
  9917. // moment the constant expression evaluator cannot cope with the non-rigorous
  9918. // ASTs which we build for dependent expressions.
  9919. if (FD->isDependentContext())
  9920. return true;
  9921. Expr::EvalStatus Status;
  9922. Status.Diag = &Diags;
  9923. EvalInfo Info(FD->getASTContext(), Status,
  9924. EvalInfo::EM_PotentialConstantExpression);
  9925. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  9926. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  9927. // Fabricate an arbitrary expression on the stack and pretend that it
  9928. // is a temporary being used as the 'this' pointer.
  9929. LValue This;
  9930. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  9931. This.set({&VIE, Info.CurrentCall->Index});
  9932. ArrayRef<const Expr*> Args;
  9933. APValue Scratch;
  9934. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  9935. // Evaluate the call as a constant initializer, to allow the construction
  9936. // of objects of non-literal types.
  9937. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  9938. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  9939. } else {
  9940. SourceLocation Loc = FD->getLocation();
  9941. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  9942. Args, FD->getBody(), Info, Scratch, nullptr);
  9943. }
  9944. return Diags.empty();
  9945. }
  9946. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  9947. const FunctionDecl *FD,
  9948. SmallVectorImpl<
  9949. PartialDiagnosticAt> &Diags) {
  9950. Expr::EvalStatus Status;
  9951. Status.Diag = &Diags;
  9952. EvalInfo Info(FD->getASTContext(), Status,
  9953. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  9954. // Fabricate a call stack frame to give the arguments a plausible cover story.
  9955. ArrayRef<const Expr*> Args;
  9956. ArgVector ArgValues(0);
  9957. bool Success = EvaluateArgs(Args, ArgValues, Info);
  9958. (void)Success;
  9959. assert(Success &&
  9960. "Failed to set up arguments for potential constant evaluation");
  9961. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  9962. APValue ResultScratch;
  9963. Evaluate(ResultScratch, Info, E);
  9964. return Diags.empty();
  9965. }
  9966. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  9967. unsigned Type) const {
  9968. if (!getType()->isPointerType())
  9969. return false;
  9970. Expr::EvalStatus Status;
  9971. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  9972. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  9973. }