ExprConstant.cpp 409 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550
  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/OSLog.h"
  42. #include "clang/AST/RecordLayout.h"
  43. #include "clang/AST/StmtVisitor.h"
  44. #include "clang/AST/TypeLoc.h"
  45. #include "clang/Basic/Builtins.h"
  46. #include "clang/Basic/TargetInfo.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <cstring>
  49. #include <functional>
  50. #define DEBUG_TYPE "exprconstant"
  51. using namespace clang;
  52. using llvm::APSInt;
  53. using llvm::APFloat;
  54. static bool IsGlobalLValue(APValue::LValueBase B);
  55. namespace {
  56. struct LValue;
  57. struct CallStackFrame;
  58. struct EvalInfo;
  59. static QualType getType(APValue::LValueBase B) {
  60. if (!B) return QualType();
  61. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  62. // FIXME: It's unclear where we're supposed to take the type from, and
  63. // this actually matters for arrays of unknown bound. Eg:
  64. //
  65. // extern int arr[]; void f() { extern int arr[3]; };
  66. // constexpr int *p = &arr[1]; // valid?
  67. //
  68. // For now, we take the array bound from the most recent declaration.
  69. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  70. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  71. QualType T = Redecl->getType();
  72. if (!T->isIncompleteArrayType())
  73. return T;
  74. }
  75. return D->getType();
  76. }
  77. const Expr *Base = B.get<const Expr*>();
  78. // For a materialized temporary, the type of the temporary we materialized
  79. // may not be the type of the expression.
  80. if (const MaterializeTemporaryExpr *MTE =
  81. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  82. SmallVector<const Expr *, 2> CommaLHSs;
  83. SmallVector<SubobjectAdjustment, 2> Adjustments;
  84. const Expr *Temp = MTE->GetTemporaryExpr();
  85. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  86. Adjustments);
  87. // Keep any cv-qualifiers from the reference if we generated a temporary
  88. // for it directly. Otherwise use the type after adjustment.
  89. if (!Adjustments.empty())
  90. return Inner->getType();
  91. }
  92. return Base->getType();
  93. }
  94. /// Get an LValue path entry, which is known to not be an array index, as a
  95. /// field or base class.
  96. static
  97. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  98. APValue::BaseOrMemberType Value;
  99. Value.setFromOpaqueValue(E.BaseOrMember);
  100. return Value;
  101. }
  102. /// Get an LValue path entry, which is known to not be an array index, as a
  103. /// field declaration.
  104. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  105. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  106. }
  107. /// Get an LValue path entry, which is known to not be an array index, as a
  108. /// base class declaration.
  109. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  110. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  111. }
  112. /// Determine whether this LValue path entry for a base class names a virtual
  113. /// base class.
  114. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  115. return getAsBaseOrMember(E).getInt();
  116. }
  117. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  118. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  119. const FunctionDecl *Callee = CE->getDirectCallee();
  120. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  121. }
  122. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  123. /// This will look through a single cast.
  124. ///
  125. /// Returns null if we couldn't unwrap a function with alloc_size.
  126. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  127. if (!E->getType()->isPointerType())
  128. return nullptr;
  129. E = E->IgnoreParens();
  130. // If we're doing a variable assignment from e.g. malloc(N), there will
  131. // probably be a cast of some kind. In exotic cases, we might also see a
  132. // top-level ExprWithCleanups. Ignore them either way.
  133. if (const auto *FE = dyn_cast<FullExpr>(E))
  134. E = FE->getSubExpr()->IgnoreParens();
  135. if (const auto *Cast = dyn_cast<CastExpr>(E))
  136. E = Cast->getSubExpr()->IgnoreParens();
  137. if (const auto *CE = dyn_cast<CallExpr>(E))
  138. return getAllocSizeAttr(CE) ? CE : nullptr;
  139. return nullptr;
  140. }
  141. /// Determines whether or not the given Base contains a call to a function
  142. /// with the alloc_size attribute.
  143. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  144. const auto *E = Base.dyn_cast<const Expr *>();
  145. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  146. }
  147. /// The bound to claim that an array of unknown bound has.
  148. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  149. /// to an arbitrary value that's likely to loudly break things if it's used.
  150. static const uint64_t AssumedSizeForUnsizedArray =
  151. std::numeric_limits<uint64_t>::max() / 2;
  152. /// Determines if an LValue with the given LValueBase will have an unsized
  153. /// array in its designator.
  154. /// Find the path length and type of the most-derived subobject in the given
  155. /// path, and find the size of the containing array, if any.
  156. static unsigned
  157. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  158. ArrayRef<APValue::LValuePathEntry> Path,
  159. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  160. bool &FirstEntryIsUnsizedArray) {
  161. // This only accepts LValueBases from APValues, and APValues don't support
  162. // arrays that lack size info.
  163. assert(!isBaseAnAllocSizeCall(Base) &&
  164. "Unsized arrays shouldn't appear here");
  165. unsigned MostDerivedLength = 0;
  166. Type = getType(Base);
  167. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  168. if (Type->isArrayType()) {
  169. const ArrayType *AT = Ctx.getAsArrayType(Type);
  170. Type = AT->getElementType();
  171. MostDerivedLength = I + 1;
  172. IsArray = true;
  173. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  174. ArraySize = CAT->getSize().getZExtValue();
  175. } else {
  176. assert(I == 0 && "unexpected unsized array designator");
  177. FirstEntryIsUnsizedArray = true;
  178. ArraySize = AssumedSizeForUnsizedArray;
  179. }
  180. } else if (Type->isAnyComplexType()) {
  181. const ComplexType *CT = Type->castAs<ComplexType>();
  182. Type = CT->getElementType();
  183. ArraySize = 2;
  184. MostDerivedLength = I + 1;
  185. IsArray = true;
  186. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  187. Type = FD->getType();
  188. ArraySize = 0;
  189. MostDerivedLength = I + 1;
  190. IsArray = false;
  191. } else {
  192. // Path[I] describes a base class.
  193. ArraySize = 0;
  194. IsArray = false;
  195. }
  196. }
  197. return MostDerivedLength;
  198. }
  199. // The order of this enum is important for diagnostics.
  200. enum CheckSubobjectKind {
  201. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  202. CSK_This, CSK_Real, CSK_Imag
  203. };
  204. /// A path from a glvalue to a subobject of that glvalue.
  205. struct SubobjectDesignator {
  206. /// True if the subobject was named in a manner not supported by C++11. Such
  207. /// lvalues can still be folded, but they are not core constant expressions
  208. /// and we cannot perform lvalue-to-rvalue conversions on them.
  209. unsigned Invalid : 1;
  210. /// Is this a pointer one past the end of an object?
  211. unsigned IsOnePastTheEnd : 1;
  212. /// Indicator of whether the first entry is an unsized array.
  213. unsigned FirstEntryIsAnUnsizedArray : 1;
  214. /// Indicator of whether the most-derived object is an array element.
  215. unsigned MostDerivedIsArrayElement : 1;
  216. /// The length of the path to the most-derived object of which this is a
  217. /// subobject.
  218. unsigned MostDerivedPathLength : 28;
  219. /// The size of the array of which the most-derived object is an element.
  220. /// This will always be 0 if the most-derived object is not an array
  221. /// element. 0 is not an indicator of whether or not the most-derived object
  222. /// is an array, however, because 0-length arrays are allowed.
  223. ///
  224. /// If the current array is an unsized array, the value of this is
  225. /// undefined.
  226. uint64_t MostDerivedArraySize;
  227. /// The type of the most derived object referred to by this address.
  228. QualType MostDerivedType;
  229. typedef APValue::LValuePathEntry PathEntry;
  230. /// The entries on the path from the glvalue to the designated subobject.
  231. SmallVector<PathEntry, 8> Entries;
  232. SubobjectDesignator() : Invalid(true) {}
  233. explicit SubobjectDesignator(QualType T)
  234. : Invalid(false), IsOnePastTheEnd(false),
  235. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  236. MostDerivedPathLength(0), MostDerivedArraySize(0),
  237. MostDerivedType(T) {}
  238. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  239. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  240. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  241. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  242. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  243. if (!Invalid) {
  244. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  245. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  246. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  247. if (V.getLValueBase()) {
  248. bool IsArray = false;
  249. bool FirstIsUnsizedArray = false;
  250. MostDerivedPathLength = findMostDerivedSubobject(
  251. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  252. MostDerivedType, IsArray, FirstIsUnsizedArray);
  253. MostDerivedIsArrayElement = IsArray;
  254. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  255. }
  256. }
  257. }
  258. void setInvalid() {
  259. Invalid = true;
  260. Entries.clear();
  261. }
  262. /// Determine whether the most derived subobject is an array without a
  263. /// known bound.
  264. bool isMostDerivedAnUnsizedArray() const {
  265. assert(!Invalid && "Calling this makes no sense on invalid designators");
  266. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  267. }
  268. /// Determine what the most derived array's size is. Results in an assertion
  269. /// failure if the most derived array lacks a size.
  270. uint64_t getMostDerivedArraySize() const {
  271. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  272. return MostDerivedArraySize;
  273. }
  274. /// Determine whether this is a one-past-the-end pointer.
  275. bool isOnePastTheEnd() const {
  276. assert(!Invalid);
  277. if (IsOnePastTheEnd)
  278. return true;
  279. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  280. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  281. return true;
  282. return false;
  283. }
  284. /// Get the range of valid index adjustments in the form
  285. /// {maximum value that can be subtracted from this pointer,
  286. /// maximum value that can be added to this pointer}
  287. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  288. if (Invalid || isMostDerivedAnUnsizedArray())
  289. return {0, 0};
  290. // [expr.add]p4: For the purposes of these operators, a pointer to a
  291. // nonarray object behaves the same as a pointer to the first element of
  292. // an array of length one with the type of the object as its element type.
  293. bool IsArray = MostDerivedPathLength == Entries.size() &&
  294. MostDerivedIsArrayElement;
  295. uint64_t ArrayIndex =
  296. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  297. uint64_t ArraySize =
  298. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  299. return {ArrayIndex, ArraySize - ArrayIndex};
  300. }
  301. /// Check that this refers to a valid subobject.
  302. bool isValidSubobject() const {
  303. if (Invalid)
  304. return false;
  305. return !isOnePastTheEnd();
  306. }
  307. /// Check that this refers to a valid subobject, and if not, produce a
  308. /// relevant diagnostic and set the designator as invalid.
  309. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  310. /// Get the type of the designated object.
  311. QualType getType(ASTContext &Ctx) const {
  312. assert(!Invalid && "invalid designator has no subobject type");
  313. return MostDerivedPathLength == Entries.size()
  314. ? MostDerivedType
  315. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  316. }
  317. /// Update this designator to refer to the first element within this array.
  318. void addArrayUnchecked(const ConstantArrayType *CAT) {
  319. PathEntry Entry;
  320. Entry.ArrayIndex = 0;
  321. Entries.push_back(Entry);
  322. // This is a most-derived object.
  323. MostDerivedType = CAT->getElementType();
  324. MostDerivedIsArrayElement = true;
  325. MostDerivedArraySize = CAT->getSize().getZExtValue();
  326. MostDerivedPathLength = Entries.size();
  327. }
  328. /// Update this designator to refer to the first element within the array of
  329. /// elements of type T. This is an array of unknown size.
  330. void addUnsizedArrayUnchecked(QualType ElemTy) {
  331. PathEntry Entry;
  332. Entry.ArrayIndex = 0;
  333. Entries.push_back(Entry);
  334. MostDerivedType = ElemTy;
  335. MostDerivedIsArrayElement = true;
  336. // The value in MostDerivedArraySize is undefined in this case. So, set it
  337. // to an arbitrary value that's likely to loudly break things if it's
  338. // used.
  339. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  340. MostDerivedPathLength = Entries.size();
  341. }
  342. /// Update this designator to refer to the given base or member of this
  343. /// object.
  344. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  345. PathEntry Entry;
  346. APValue::BaseOrMemberType Value(D, Virtual);
  347. Entry.BaseOrMember = Value.getOpaqueValue();
  348. Entries.push_back(Entry);
  349. // If this isn't a base class, it's a new most-derived object.
  350. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  351. MostDerivedType = FD->getType();
  352. MostDerivedIsArrayElement = false;
  353. MostDerivedArraySize = 0;
  354. MostDerivedPathLength = Entries.size();
  355. }
  356. }
  357. /// Update this designator to refer to the given complex component.
  358. void addComplexUnchecked(QualType EltTy, bool Imag) {
  359. PathEntry Entry;
  360. Entry.ArrayIndex = Imag;
  361. Entries.push_back(Entry);
  362. // This is technically a most-derived object, though in practice this
  363. // is unlikely to matter.
  364. MostDerivedType = EltTy;
  365. MostDerivedIsArrayElement = true;
  366. MostDerivedArraySize = 2;
  367. MostDerivedPathLength = Entries.size();
  368. }
  369. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  370. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  371. const APSInt &N);
  372. /// Add N to the address of this subobject.
  373. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  374. if (Invalid || !N) return;
  375. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  376. if (isMostDerivedAnUnsizedArray()) {
  377. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  378. // Can't verify -- trust that the user is doing the right thing (or if
  379. // not, trust that the caller will catch the bad behavior).
  380. // FIXME: Should we reject if this overflows, at least?
  381. Entries.back().ArrayIndex += TruncatedN;
  382. return;
  383. }
  384. // [expr.add]p4: For the purposes of these operators, a pointer to a
  385. // nonarray object behaves the same as a pointer to the first element of
  386. // an array of length one with the type of the object as its element type.
  387. bool IsArray = MostDerivedPathLength == Entries.size() &&
  388. MostDerivedIsArrayElement;
  389. uint64_t ArrayIndex =
  390. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  391. uint64_t ArraySize =
  392. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  393. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  394. // Calculate the actual index in a wide enough type, so we can include
  395. // it in the note.
  396. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  397. (llvm::APInt&)N += ArrayIndex;
  398. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  399. diagnosePointerArithmetic(Info, E, N);
  400. setInvalid();
  401. return;
  402. }
  403. ArrayIndex += TruncatedN;
  404. assert(ArrayIndex <= ArraySize &&
  405. "bounds check succeeded for out-of-bounds index");
  406. if (IsArray)
  407. Entries.back().ArrayIndex = ArrayIndex;
  408. else
  409. IsOnePastTheEnd = (ArrayIndex != 0);
  410. }
  411. };
  412. /// A stack frame in the constexpr call stack.
  413. struct CallStackFrame {
  414. EvalInfo &Info;
  415. /// Parent - The caller of this stack frame.
  416. CallStackFrame *Caller;
  417. /// Callee - The function which was called.
  418. const FunctionDecl *Callee;
  419. /// This - The binding for the this pointer in this call, if any.
  420. const LValue *This;
  421. /// Arguments - Parameter bindings for this function call, indexed by
  422. /// parameters' function scope indices.
  423. APValue *Arguments;
  424. // Note that we intentionally use std::map here so that references to
  425. // values are stable.
  426. typedef std::pair<const void *, unsigned> MapKeyTy;
  427. typedef std::map<MapKeyTy, APValue> MapTy;
  428. /// Temporaries - Temporary lvalues materialized within this stack frame.
  429. MapTy Temporaries;
  430. /// CallLoc - The location of the call expression for this call.
  431. SourceLocation CallLoc;
  432. /// Index - The call index of this call.
  433. unsigned Index;
  434. /// The stack of integers for tracking version numbers for temporaries.
  435. SmallVector<unsigned, 2> TempVersionStack = {1};
  436. unsigned CurTempVersion = TempVersionStack.back();
  437. unsigned getTempVersion() const { return TempVersionStack.back(); }
  438. void pushTempVersion() {
  439. TempVersionStack.push_back(++CurTempVersion);
  440. }
  441. void popTempVersion() {
  442. TempVersionStack.pop_back();
  443. }
  444. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  445. // on the overall stack usage of deeply-recursing constexpr evaluataions.
  446. // (We should cache this map rather than recomputing it repeatedly.)
  447. // But let's try this and see how it goes; we can look into caching the map
  448. // as a later change.
  449. /// LambdaCaptureFields - Mapping from captured variables/this to
  450. /// corresponding data members in the closure class.
  451. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  452. FieldDecl *LambdaThisCaptureField;
  453. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  454. const FunctionDecl *Callee, const LValue *This,
  455. APValue *Arguments);
  456. ~CallStackFrame();
  457. // Return the temporary for Key whose version number is Version.
  458. APValue *getTemporary(const void *Key, unsigned Version) {
  459. MapKeyTy KV(Key, Version);
  460. auto LB = Temporaries.lower_bound(KV);
  461. if (LB != Temporaries.end() && LB->first == KV)
  462. return &LB->second;
  463. // Pair (Key,Version) wasn't found in the map. Check that no elements
  464. // in the map have 'Key' as their key.
  465. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  466. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  467. "Element with key 'Key' found in map");
  468. return nullptr;
  469. }
  470. // Return the current temporary for Key in the map.
  471. APValue *getCurrentTemporary(const void *Key) {
  472. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  473. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  474. return &std::prev(UB)->second;
  475. return nullptr;
  476. }
  477. // Return the version number of the current temporary for Key.
  478. unsigned getCurrentTemporaryVersion(const void *Key) const {
  479. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  480. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  481. return std::prev(UB)->first.second;
  482. return 0;
  483. }
  484. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  485. };
  486. /// Temporarily override 'this'.
  487. class ThisOverrideRAII {
  488. public:
  489. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  490. : Frame(Frame), OldThis(Frame.This) {
  491. if (Enable)
  492. Frame.This = NewThis;
  493. }
  494. ~ThisOverrideRAII() {
  495. Frame.This = OldThis;
  496. }
  497. private:
  498. CallStackFrame &Frame;
  499. const LValue *OldThis;
  500. };
  501. /// A partial diagnostic which we might know in advance that we are not going
  502. /// to emit.
  503. class OptionalDiagnostic {
  504. PartialDiagnostic *Diag;
  505. public:
  506. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  507. : Diag(Diag) {}
  508. template<typename T>
  509. OptionalDiagnostic &operator<<(const T &v) {
  510. if (Diag)
  511. *Diag << v;
  512. return *this;
  513. }
  514. OptionalDiagnostic &operator<<(const APSInt &I) {
  515. if (Diag) {
  516. SmallVector<char, 32> Buffer;
  517. I.toString(Buffer);
  518. *Diag << StringRef(Buffer.data(), Buffer.size());
  519. }
  520. return *this;
  521. }
  522. OptionalDiagnostic &operator<<(const APFloat &F) {
  523. if (Diag) {
  524. // FIXME: Force the precision of the source value down so we don't
  525. // print digits which are usually useless (we don't really care here if
  526. // we truncate a digit by accident in edge cases). Ideally,
  527. // APFloat::toString would automatically print the shortest
  528. // representation which rounds to the correct value, but it's a bit
  529. // tricky to implement.
  530. unsigned precision =
  531. llvm::APFloat::semanticsPrecision(F.getSemantics());
  532. precision = (precision * 59 + 195) / 196;
  533. SmallVector<char, 32> Buffer;
  534. F.toString(Buffer, precision);
  535. *Diag << StringRef(Buffer.data(), Buffer.size());
  536. }
  537. return *this;
  538. }
  539. };
  540. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  541. class Cleanup {
  542. llvm::PointerIntPair<APValue*, 1, bool> Value;
  543. public:
  544. Cleanup(APValue *Val, bool IsLifetimeExtended)
  545. : Value(Val, IsLifetimeExtended) {}
  546. bool isLifetimeExtended() const { return Value.getInt(); }
  547. void endLifetime() {
  548. *Value.getPointer() = APValue();
  549. }
  550. };
  551. /// EvalInfo - This is a private struct used by the evaluator to capture
  552. /// information about a subexpression as it is folded. It retains information
  553. /// about the AST context, but also maintains information about the folded
  554. /// expression.
  555. ///
  556. /// If an expression could be evaluated, it is still possible it is not a C
  557. /// "integer constant expression" or constant expression. If not, this struct
  558. /// captures information about how and why not.
  559. ///
  560. /// One bit of information passed *into* the request for constant folding
  561. /// indicates whether the subexpression is "evaluated" or not according to C
  562. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  563. /// evaluate the expression regardless of what the RHS is, but C only allows
  564. /// certain things in certain situations.
  565. struct EvalInfo {
  566. ASTContext &Ctx;
  567. /// EvalStatus - Contains information about the evaluation.
  568. Expr::EvalStatus &EvalStatus;
  569. /// CurrentCall - The top of the constexpr call stack.
  570. CallStackFrame *CurrentCall;
  571. /// CallStackDepth - The number of calls in the call stack right now.
  572. unsigned CallStackDepth;
  573. /// NextCallIndex - The next call index to assign.
  574. unsigned NextCallIndex;
  575. /// StepsLeft - The remaining number of evaluation steps we're permitted
  576. /// to perform. This is essentially a limit for the number of statements
  577. /// we will evaluate.
  578. unsigned StepsLeft;
  579. /// BottomFrame - The frame in which evaluation started. This must be
  580. /// initialized after CurrentCall and CallStackDepth.
  581. CallStackFrame BottomFrame;
  582. /// A stack of values whose lifetimes end at the end of some surrounding
  583. /// evaluation frame.
  584. llvm::SmallVector<Cleanup, 16> CleanupStack;
  585. /// EvaluatingDecl - This is the declaration whose initializer is being
  586. /// evaluated, if any.
  587. APValue::LValueBase EvaluatingDecl;
  588. /// EvaluatingDeclValue - This is the value being constructed for the
  589. /// declaration whose initializer is being evaluated, if any.
  590. APValue *EvaluatingDeclValue;
  591. /// EvaluatingObject - Pair of the AST node that an lvalue represents and
  592. /// the call index that that lvalue was allocated in.
  593. typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
  594. EvaluatingObject;
  595. /// EvaluatingConstructors - Set of objects that are currently being
  596. /// constructed.
  597. llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
  598. struct EvaluatingConstructorRAII {
  599. EvalInfo &EI;
  600. EvaluatingObject Object;
  601. bool DidInsert;
  602. EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
  603. : EI(EI), Object(Object) {
  604. DidInsert = EI.EvaluatingConstructors.insert(Object).second;
  605. }
  606. ~EvaluatingConstructorRAII() {
  607. if (DidInsert) EI.EvaluatingConstructors.erase(Object);
  608. }
  609. };
  610. bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
  611. unsigned Version) {
  612. return EvaluatingConstructors.count(
  613. EvaluatingObject(Decl, {CallIndex, Version}));
  614. }
  615. /// The current array initialization index, if we're performing array
  616. /// initialization.
  617. uint64_t ArrayInitIndex = -1;
  618. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  619. /// notes attached to it will also be stored, otherwise they will not be.
  620. bool HasActiveDiagnostic;
  621. /// Have we emitted a diagnostic explaining why we couldn't constant
  622. /// fold (not just why it's not strictly a constant expression)?
  623. bool HasFoldFailureDiagnostic;
  624. /// Whether or not we're currently speculatively evaluating.
  625. bool IsSpeculativelyEvaluating;
  626. enum EvaluationMode {
  627. /// Evaluate as a constant expression. Stop if we find that the expression
  628. /// is not a constant expression.
  629. EM_ConstantExpression,
  630. /// Evaluate as a potential constant expression. Keep going if we hit a
  631. /// construct that we can't evaluate yet (because we don't yet know the
  632. /// value of something) but stop if we hit something that could never be
  633. /// a constant expression.
  634. EM_PotentialConstantExpression,
  635. /// Fold the expression to a constant. Stop if we hit a side-effect that
  636. /// we can't model.
  637. EM_ConstantFold,
  638. /// Evaluate the expression looking for integer overflow and similar
  639. /// issues. Don't worry about side-effects, and try to visit all
  640. /// subexpressions.
  641. EM_EvaluateForOverflow,
  642. /// Evaluate in any way we know how. Don't worry about side-effects that
  643. /// can't be modeled.
  644. EM_IgnoreSideEffects,
  645. /// Evaluate as a constant expression. Stop if we find that the expression
  646. /// is not a constant expression. Some expressions can be retried in the
  647. /// optimizer if we don't constant fold them here, but in an unevaluated
  648. /// context we try to fold them immediately since the optimizer never
  649. /// gets a chance to look at it.
  650. EM_ConstantExpressionUnevaluated,
  651. /// Evaluate as a potential constant expression. Keep going if we hit a
  652. /// construct that we can't evaluate yet (because we don't yet know the
  653. /// value of something) but stop if we hit something that could never be
  654. /// a constant expression. Some expressions can be retried in the
  655. /// optimizer if we don't constant fold them here, but in an unevaluated
  656. /// context we try to fold them immediately since the optimizer never
  657. /// gets a chance to look at it.
  658. EM_PotentialConstantExpressionUnevaluated,
  659. } EvalMode;
  660. /// Are we checking whether the expression is a potential constant
  661. /// expression?
  662. bool checkingPotentialConstantExpression() const {
  663. return EvalMode == EM_PotentialConstantExpression ||
  664. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  665. }
  666. /// Are we checking an expression for overflow?
  667. // FIXME: We should check for any kind of undefined or suspicious behavior
  668. // in such constructs, not just overflow.
  669. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  670. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  671. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  672. CallStackDepth(0), NextCallIndex(1),
  673. StepsLeft(getLangOpts().ConstexprStepLimit),
  674. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  675. EvaluatingDecl((const ValueDecl *)nullptr),
  676. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  677. HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
  678. EvalMode(Mode) {}
  679. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  680. EvaluatingDecl = Base;
  681. EvaluatingDeclValue = &Value;
  682. EvaluatingConstructors.insert({Base, {0, 0}});
  683. }
  684. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  685. bool CheckCallLimit(SourceLocation Loc) {
  686. // Don't perform any constexpr calls (other than the call we're checking)
  687. // when checking a potential constant expression.
  688. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  689. return false;
  690. if (NextCallIndex == 0) {
  691. // NextCallIndex has wrapped around.
  692. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  693. return false;
  694. }
  695. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  696. return true;
  697. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  698. << getLangOpts().ConstexprCallDepth;
  699. return false;
  700. }
  701. CallStackFrame *getCallFrame(unsigned CallIndex) {
  702. assert(CallIndex && "no call index in getCallFrame");
  703. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  704. // be null in this loop.
  705. CallStackFrame *Frame = CurrentCall;
  706. while (Frame->Index > CallIndex)
  707. Frame = Frame->Caller;
  708. return (Frame->Index == CallIndex) ? Frame : nullptr;
  709. }
  710. bool nextStep(const Stmt *S) {
  711. if (!StepsLeft) {
  712. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  713. return false;
  714. }
  715. --StepsLeft;
  716. return true;
  717. }
  718. private:
  719. /// Add a diagnostic to the diagnostics list.
  720. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  721. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  722. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  723. return EvalStatus.Diag->back().second;
  724. }
  725. /// Add notes containing a call stack to the current point of evaluation.
  726. void addCallStack(unsigned Limit);
  727. private:
  728. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  729. unsigned ExtraNotes, bool IsCCEDiag) {
  730. if (EvalStatus.Diag) {
  731. // If we have a prior diagnostic, it will be noting that the expression
  732. // isn't a constant expression. This diagnostic is more important,
  733. // unless we require this evaluation to produce a constant expression.
  734. //
  735. // FIXME: We might want to show both diagnostics to the user in
  736. // EM_ConstantFold mode.
  737. if (!EvalStatus.Diag->empty()) {
  738. switch (EvalMode) {
  739. case EM_ConstantFold:
  740. case EM_IgnoreSideEffects:
  741. case EM_EvaluateForOverflow:
  742. if (!HasFoldFailureDiagnostic)
  743. break;
  744. // We've already failed to fold something. Keep that diagnostic.
  745. LLVM_FALLTHROUGH;
  746. case EM_ConstantExpression:
  747. case EM_PotentialConstantExpression:
  748. case EM_ConstantExpressionUnevaluated:
  749. case EM_PotentialConstantExpressionUnevaluated:
  750. HasActiveDiagnostic = false;
  751. return OptionalDiagnostic();
  752. }
  753. }
  754. unsigned CallStackNotes = CallStackDepth - 1;
  755. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  756. if (Limit)
  757. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  758. if (checkingPotentialConstantExpression())
  759. CallStackNotes = 0;
  760. HasActiveDiagnostic = true;
  761. HasFoldFailureDiagnostic = !IsCCEDiag;
  762. EvalStatus.Diag->clear();
  763. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  764. addDiag(Loc, DiagId);
  765. if (!checkingPotentialConstantExpression())
  766. addCallStack(Limit);
  767. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  768. }
  769. HasActiveDiagnostic = false;
  770. return OptionalDiagnostic();
  771. }
  772. public:
  773. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  774. OptionalDiagnostic
  775. FFDiag(SourceLocation Loc,
  776. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  777. unsigned ExtraNotes = 0) {
  778. return Diag(Loc, DiagId, ExtraNotes, false);
  779. }
  780. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  781. = diag::note_invalid_subexpr_in_const_expr,
  782. unsigned ExtraNotes = 0) {
  783. if (EvalStatus.Diag)
  784. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  785. HasActiveDiagnostic = false;
  786. return OptionalDiagnostic();
  787. }
  788. /// Diagnose that the evaluation does not produce a C++11 core constant
  789. /// expression.
  790. ///
  791. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  792. /// EM_PotentialConstantExpression mode and we produce one of these.
  793. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  794. = diag::note_invalid_subexpr_in_const_expr,
  795. unsigned ExtraNotes = 0) {
  796. // Don't override a previous diagnostic. Don't bother collecting
  797. // diagnostics if we're evaluating for overflow.
  798. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  799. HasActiveDiagnostic = false;
  800. return OptionalDiagnostic();
  801. }
  802. return Diag(Loc, DiagId, ExtraNotes, true);
  803. }
  804. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  805. = diag::note_invalid_subexpr_in_const_expr,
  806. unsigned ExtraNotes = 0) {
  807. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  808. }
  809. /// Add a note to a prior diagnostic.
  810. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  811. if (!HasActiveDiagnostic)
  812. return OptionalDiagnostic();
  813. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  814. }
  815. /// Add a stack of notes to a prior diagnostic.
  816. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  817. if (HasActiveDiagnostic) {
  818. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  819. Diags.begin(), Diags.end());
  820. }
  821. }
  822. /// Should we continue evaluation after encountering a side-effect that we
  823. /// couldn't model?
  824. bool keepEvaluatingAfterSideEffect() {
  825. switch (EvalMode) {
  826. case EM_PotentialConstantExpression:
  827. case EM_PotentialConstantExpressionUnevaluated:
  828. case EM_EvaluateForOverflow:
  829. case EM_IgnoreSideEffects:
  830. return true;
  831. case EM_ConstantExpression:
  832. case EM_ConstantExpressionUnevaluated:
  833. case EM_ConstantFold:
  834. return false;
  835. }
  836. llvm_unreachable("Missed EvalMode case");
  837. }
  838. /// Note that we have had a side-effect, and determine whether we should
  839. /// keep evaluating.
  840. bool noteSideEffect() {
  841. EvalStatus.HasSideEffects = true;
  842. return keepEvaluatingAfterSideEffect();
  843. }
  844. /// Should we continue evaluation after encountering undefined behavior?
  845. bool keepEvaluatingAfterUndefinedBehavior() {
  846. switch (EvalMode) {
  847. case EM_EvaluateForOverflow:
  848. case EM_IgnoreSideEffects:
  849. case EM_ConstantFold:
  850. return true;
  851. case EM_PotentialConstantExpression:
  852. case EM_PotentialConstantExpressionUnevaluated:
  853. case EM_ConstantExpression:
  854. case EM_ConstantExpressionUnevaluated:
  855. return false;
  856. }
  857. llvm_unreachable("Missed EvalMode case");
  858. }
  859. /// Note that we hit something that was technically undefined behavior, but
  860. /// that we can evaluate past it (such as signed overflow or floating-point
  861. /// division by zero.)
  862. bool noteUndefinedBehavior() {
  863. EvalStatus.HasUndefinedBehavior = true;
  864. return keepEvaluatingAfterUndefinedBehavior();
  865. }
  866. /// Should we continue evaluation as much as possible after encountering a
  867. /// construct which can't be reduced to a value?
  868. bool keepEvaluatingAfterFailure() {
  869. if (!StepsLeft)
  870. return false;
  871. switch (EvalMode) {
  872. case EM_PotentialConstantExpression:
  873. case EM_PotentialConstantExpressionUnevaluated:
  874. case EM_EvaluateForOverflow:
  875. return true;
  876. case EM_ConstantExpression:
  877. case EM_ConstantExpressionUnevaluated:
  878. case EM_ConstantFold:
  879. case EM_IgnoreSideEffects:
  880. return false;
  881. }
  882. llvm_unreachable("Missed EvalMode case");
  883. }
  884. /// Notes that we failed to evaluate an expression that other expressions
  885. /// directly depend on, and determine if we should keep evaluating. This
  886. /// should only be called if we actually intend to keep evaluating.
  887. ///
  888. /// Call noteSideEffect() instead if we may be able to ignore the value that
  889. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  890. ///
  891. /// (Foo(), 1) // use noteSideEffect
  892. /// (Foo() || true) // use noteSideEffect
  893. /// Foo() + 1 // use noteFailure
  894. LLVM_NODISCARD bool noteFailure() {
  895. // Failure when evaluating some expression often means there is some
  896. // subexpression whose evaluation was skipped. Therefore, (because we
  897. // don't track whether we skipped an expression when unwinding after an
  898. // evaluation failure) every evaluation failure that bubbles up from a
  899. // subexpression implies that a side-effect has potentially happened. We
  900. // skip setting the HasSideEffects flag to true until we decide to
  901. // continue evaluating after that point, which happens here.
  902. bool KeepGoing = keepEvaluatingAfterFailure();
  903. EvalStatus.HasSideEffects |= KeepGoing;
  904. return KeepGoing;
  905. }
  906. class ArrayInitLoopIndex {
  907. EvalInfo &Info;
  908. uint64_t OuterIndex;
  909. public:
  910. ArrayInitLoopIndex(EvalInfo &Info)
  911. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  912. Info.ArrayInitIndex = 0;
  913. }
  914. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  915. operator uint64_t&() { return Info.ArrayInitIndex; }
  916. };
  917. };
  918. /// Object used to treat all foldable expressions as constant expressions.
  919. struct FoldConstant {
  920. EvalInfo &Info;
  921. bool Enabled;
  922. bool HadNoPriorDiags;
  923. EvalInfo::EvaluationMode OldMode;
  924. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  925. : Info(Info),
  926. Enabled(Enabled),
  927. HadNoPriorDiags(Info.EvalStatus.Diag &&
  928. Info.EvalStatus.Diag->empty() &&
  929. !Info.EvalStatus.HasSideEffects),
  930. OldMode(Info.EvalMode) {
  931. if (Enabled &&
  932. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  933. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  934. Info.EvalMode = EvalInfo::EM_ConstantFold;
  935. }
  936. void keepDiagnostics() { Enabled = false; }
  937. ~FoldConstant() {
  938. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  939. !Info.EvalStatus.HasSideEffects)
  940. Info.EvalStatus.Diag->clear();
  941. Info.EvalMode = OldMode;
  942. }
  943. };
  944. /// RAII object used to set the current evaluation mode to ignore
  945. /// side-effects.
  946. struct IgnoreSideEffectsRAII {
  947. EvalInfo &Info;
  948. EvalInfo::EvaluationMode OldMode;
  949. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  950. : Info(Info), OldMode(Info.EvalMode) {
  951. if (!Info.checkingPotentialConstantExpression())
  952. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  953. }
  954. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  955. };
  956. /// RAII object used to optionally suppress diagnostics and side-effects from
  957. /// a speculative evaluation.
  958. class SpeculativeEvaluationRAII {
  959. EvalInfo *Info = nullptr;
  960. Expr::EvalStatus OldStatus;
  961. bool OldIsSpeculativelyEvaluating;
  962. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  963. Info = Other.Info;
  964. OldStatus = Other.OldStatus;
  965. OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
  966. Other.Info = nullptr;
  967. }
  968. void maybeRestoreState() {
  969. if (!Info)
  970. return;
  971. Info->EvalStatus = OldStatus;
  972. Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
  973. }
  974. public:
  975. SpeculativeEvaluationRAII() = default;
  976. SpeculativeEvaluationRAII(
  977. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  978. : Info(&Info), OldStatus(Info.EvalStatus),
  979. OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
  980. Info.EvalStatus.Diag = NewDiag;
  981. Info.IsSpeculativelyEvaluating = true;
  982. }
  983. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  984. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  985. moveFromAndCancel(std::move(Other));
  986. }
  987. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  988. maybeRestoreState();
  989. moveFromAndCancel(std::move(Other));
  990. return *this;
  991. }
  992. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  993. };
  994. /// RAII object wrapping a full-expression or block scope, and handling
  995. /// the ending of the lifetime of temporaries created within it.
  996. template<bool IsFullExpression>
  997. class ScopeRAII {
  998. EvalInfo &Info;
  999. unsigned OldStackSize;
  1000. public:
  1001. ScopeRAII(EvalInfo &Info)
  1002. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1003. // Push a new temporary version. This is needed to distinguish between
  1004. // temporaries created in different iterations of a loop.
  1005. Info.CurrentCall->pushTempVersion();
  1006. }
  1007. ~ScopeRAII() {
  1008. // Body moved to a static method to encourage the compiler to inline away
  1009. // instances of this class.
  1010. cleanup(Info, OldStackSize);
  1011. Info.CurrentCall->popTempVersion();
  1012. }
  1013. private:
  1014. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  1015. unsigned NewEnd = OldStackSize;
  1016. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  1017. I != N; ++I) {
  1018. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  1019. // Full-expression cleanup of a lifetime-extended temporary: nothing
  1020. // to do, just move this cleanup to the right place in the stack.
  1021. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  1022. ++NewEnd;
  1023. } else {
  1024. // End the lifetime of the object.
  1025. Info.CleanupStack[I].endLifetime();
  1026. }
  1027. }
  1028. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1029. Info.CleanupStack.end());
  1030. }
  1031. };
  1032. typedef ScopeRAII<false> BlockScopeRAII;
  1033. typedef ScopeRAII<true> FullExpressionRAII;
  1034. }
  1035. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1036. CheckSubobjectKind CSK) {
  1037. if (Invalid)
  1038. return false;
  1039. if (isOnePastTheEnd()) {
  1040. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1041. << CSK;
  1042. setInvalid();
  1043. return false;
  1044. }
  1045. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1046. // must actually be at least one array element; even a VLA cannot have a
  1047. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1048. return true;
  1049. }
  1050. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1051. const Expr *E) {
  1052. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1053. // Do not set the designator as invalid: we can represent this situation,
  1054. // and correct handling of __builtin_object_size requires us to do so.
  1055. }
  1056. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1057. const Expr *E,
  1058. const APSInt &N) {
  1059. // If we're complaining, we must be able to statically determine the size of
  1060. // the most derived array.
  1061. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1062. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1063. << N << /*array*/ 0
  1064. << static_cast<unsigned>(getMostDerivedArraySize());
  1065. else
  1066. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1067. << N << /*non-array*/ 1;
  1068. setInvalid();
  1069. }
  1070. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1071. const FunctionDecl *Callee, const LValue *This,
  1072. APValue *Arguments)
  1073. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1074. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1075. Info.CurrentCall = this;
  1076. ++Info.CallStackDepth;
  1077. }
  1078. CallStackFrame::~CallStackFrame() {
  1079. assert(Info.CurrentCall == this && "calls retired out of order");
  1080. --Info.CallStackDepth;
  1081. Info.CurrentCall = Caller;
  1082. }
  1083. APValue &CallStackFrame::createTemporary(const void *Key,
  1084. bool IsLifetimeExtended) {
  1085. unsigned Version = Info.CurrentCall->getTempVersion();
  1086. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1087. assert(Result.isUninit() && "temporary created multiple times");
  1088. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1089. return Result;
  1090. }
  1091. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  1092. void EvalInfo::addCallStack(unsigned Limit) {
  1093. // Determine which calls to skip, if any.
  1094. unsigned ActiveCalls = CallStackDepth - 1;
  1095. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  1096. if (Limit && Limit < ActiveCalls) {
  1097. SkipStart = Limit / 2 + Limit % 2;
  1098. SkipEnd = ActiveCalls - Limit / 2;
  1099. }
  1100. // Walk the call stack and add the diagnostics.
  1101. unsigned CallIdx = 0;
  1102. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  1103. Frame = Frame->Caller, ++CallIdx) {
  1104. // Skip this call?
  1105. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  1106. if (CallIdx == SkipStart) {
  1107. // Note that we're skipping calls.
  1108. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  1109. << unsigned(ActiveCalls - Limit);
  1110. }
  1111. continue;
  1112. }
  1113. // Use a different note for an inheriting constructor, because from the
  1114. // user's perspective it's not really a function at all.
  1115. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  1116. if (CD->isInheritingConstructor()) {
  1117. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  1118. << CD->getParent();
  1119. continue;
  1120. }
  1121. }
  1122. SmallVector<char, 128> Buffer;
  1123. llvm::raw_svector_ostream Out(Buffer);
  1124. describeCall(Frame, Out);
  1125. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  1126. }
  1127. }
  1128. namespace {
  1129. struct ComplexValue {
  1130. private:
  1131. bool IsInt;
  1132. public:
  1133. APSInt IntReal, IntImag;
  1134. APFloat FloatReal, FloatImag;
  1135. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1136. void makeComplexFloat() { IsInt = false; }
  1137. bool isComplexFloat() const { return !IsInt; }
  1138. APFloat &getComplexFloatReal() { return FloatReal; }
  1139. APFloat &getComplexFloatImag() { return FloatImag; }
  1140. void makeComplexInt() { IsInt = true; }
  1141. bool isComplexInt() const { return IsInt; }
  1142. APSInt &getComplexIntReal() { return IntReal; }
  1143. APSInt &getComplexIntImag() { return IntImag; }
  1144. void moveInto(APValue &v) const {
  1145. if (isComplexFloat())
  1146. v = APValue(FloatReal, FloatImag);
  1147. else
  1148. v = APValue(IntReal, IntImag);
  1149. }
  1150. void setFrom(const APValue &v) {
  1151. assert(v.isComplexFloat() || v.isComplexInt());
  1152. if (v.isComplexFloat()) {
  1153. makeComplexFloat();
  1154. FloatReal = v.getComplexFloatReal();
  1155. FloatImag = v.getComplexFloatImag();
  1156. } else {
  1157. makeComplexInt();
  1158. IntReal = v.getComplexIntReal();
  1159. IntImag = v.getComplexIntImag();
  1160. }
  1161. }
  1162. };
  1163. struct LValue {
  1164. APValue::LValueBase Base;
  1165. CharUnits Offset;
  1166. SubobjectDesignator Designator;
  1167. bool IsNullPtr : 1;
  1168. bool InvalidBase : 1;
  1169. const APValue::LValueBase getLValueBase() const { return Base; }
  1170. CharUnits &getLValueOffset() { return Offset; }
  1171. const CharUnits &getLValueOffset() const { return Offset; }
  1172. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1173. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1174. bool isNullPointer() const { return IsNullPtr;}
  1175. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1176. unsigned getLValueVersion() const { return Base.getVersion(); }
  1177. void moveInto(APValue &V) const {
  1178. if (Designator.Invalid)
  1179. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1180. else {
  1181. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1182. V = APValue(Base, Offset, Designator.Entries,
  1183. Designator.IsOnePastTheEnd, IsNullPtr);
  1184. }
  1185. }
  1186. void setFrom(ASTContext &Ctx, const APValue &V) {
  1187. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1188. Base = V.getLValueBase();
  1189. Offset = V.getLValueOffset();
  1190. InvalidBase = false;
  1191. Designator = SubobjectDesignator(Ctx, V);
  1192. IsNullPtr = V.isNullPointer();
  1193. }
  1194. void set(APValue::LValueBase B, bool BInvalid = false) {
  1195. #ifndef NDEBUG
  1196. // We only allow a few types of invalid bases. Enforce that here.
  1197. if (BInvalid) {
  1198. const auto *E = B.get<const Expr *>();
  1199. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1200. "Unexpected type of invalid base");
  1201. }
  1202. #endif
  1203. Base = B;
  1204. Offset = CharUnits::fromQuantity(0);
  1205. InvalidBase = BInvalid;
  1206. Designator = SubobjectDesignator(getType(B));
  1207. IsNullPtr = false;
  1208. }
  1209. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1210. Base = (Expr *)nullptr;
  1211. Offset = CharUnits::fromQuantity(TargetVal);
  1212. InvalidBase = false;
  1213. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1214. IsNullPtr = true;
  1215. }
  1216. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1217. set(B, true);
  1218. }
  1219. // Check that this LValue is not based on a null pointer. If it is, produce
  1220. // a diagnostic and mark the designator as invalid.
  1221. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1222. CheckSubobjectKind CSK) {
  1223. if (Designator.Invalid)
  1224. return false;
  1225. if (IsNullPtr) {
  1226. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  1227. << CSK;
  1228. Designator.setInvalid();
  1229. return false;
  1230. }
  1231. return true;
  1232. }
  1233. // Check this LValue refers to an object. If not, set the designator to be
  1234. // invalid and emit a diagnostic.
  1235. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1236. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1237. Designator.checkSubobject(Info, E, CSK);
  1238. }
  1239. void addDecl(EvalInfo &Info, const Expr *E,
  1240. const Decl *D, bool Virtual = false) {
  1241. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1242. Designator.addDeclUnchecked(D, Virtual);
  1243. }
  1244. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1245. if (!Designator.Entries.empty()) {
  1246. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1247. Designator.setInvalid();
  1248. return;
  1249. }
  1250. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1251. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1252. Designator.FirstEntryIsAnUnsizedArray = true;
  1253. Designator.addUnsizedArrayUnchecked(ElemTy);
  1254. }
  1255. }
  1256. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1257. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1258. Designator.addArrayUnchecked(CAT);
  1259. }
  1260. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1261. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1262. Designator.addComplexUnchecked(EltTy, Imag);
  1263. }
  1264. void clearIsNullPointer() {
  1265. IsNullPtr = false;
  1266. }
  1267. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1268. const APSInt &Index, CharUnits ElementSize) {
  1269. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1270. // but we're not required to diagnose it and it's valid in C++.)
  1271. if (!Index)
  1272. return;
  1273. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1274. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1275. // offsets.
  1276. uint64_t Offset64 = Offset.getQuantity();
  1277. uint64_t ElemSize64 = ElementSize.getQuantity();
  1278. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1279. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1280. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1281. Designator.adjustIndex(Info, E, Index);
  1282. clearIsNullPointer();
  1283. }
  1284. void adjustOffset(CharUnits N) {
  1285. Offset += N;
  1286. if (N.getQuantity())
  1287. clearIsNullPointer();
  1288. }
  1289. };
  1290. struct MemberPtr {
  1291. MemberPtr() {}
  1292. explicit MemberPtr(const ValueDecl *Decl) :
  1293. DeclAndIsDerivedMember(Decl, false), Path() {}
  1294. /// The member or (direct or indirect) field referred to by this member
  1295. /// pointer, or 0 if this is a null member pointer.
  1296. const ValueDecl *getDecl() const {
  1297. return DeclAndIsDerivedMember.getPointer();
  1298. }
  1299. /// Is this actually a member of some type derived from the relevant class?
  1300. bool isDerivedMember() const {
  1301. return DeclAndIsDerivedMember.getInt();
  1302. }
  1303. /// Get the class which the declaration actually lives in.
  1304. const CXXRecordDecl *getContainingRecord() const {
  1305. return cast<CXXRecordDecl>(
  1306. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1307. }
  1308. void moveInto(APValue &V) const {
  1309. V = APValue(getDecl(), isDerivedMember(), Path);
  1310. }
  1311. void setFrom(const APValue &V) {
  1312. assert(V.isMemberPointer());
  1313. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1314. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1315. Path.clear();
  1316. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1317. Path.insert(Path.end(), P.begin(), P.end());
  1318. }
  1319. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1320. /// whether the member is a member of some class derived from the class type
  1321. /// of the member pointer.
  1322. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1323. /// Path - The path of base/derived classes from the member declaration's
  1324. /// class (exclusive) to the class type of the member pointer (inclusive).
  1325. SmallVector<const CXXRecordDecl*, 4> Path;
  1326. /// Perform a cast towards the class of the Decl (either up or down the
  1327. /// hierarchy).
  1328. bool castBack(const CXXRecordDecl *Class) {
  1329. assert(!Path.empty());
  1330. const CXXRecordDecl *Expected;
  1331. if (Path.size() >= 2)
  1332. Expected = Path[Path.size() - 2];
  1333. else
  1334. Expected = getContainingRecord();
  1335. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1336. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1337. // if B does not contain the original member and is not a base or
  1338. // derived class of the class containing the original member, the result
  1339. // of the cast is undefined.
  1340. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1341. // (D::*). We consider that to be a language defect.
  1342. return false;
  1343. }
  1344. Path.pop_back();
  1345. return true;
  1346. }
  1347. /// Perform a base-to-derived member pointer cast.
  1348. bool castToDerived(const CXXRecordDecl *Derived) {
  1349. if (!getDecl())
  1350. return true;
  1351. if (!isDerivedMember()) {
  1352. Path.push_back(Derived);
  1353. return true;
  1354. }
  1355. if (!castBack(Derived))
  1356. return false;
  1357. if (Path.empty())
  1358. DeclAndIsDerivedMember.setInt(false);
  1359. return true;
  1360. }
  1361. /// Perform a derived-to-base member pointer cast.
  1362. bool castToBase(const CXXRecordDecl *Base) {
  1363. if (!getDecl())
  1364. return true;
  1365. if (Path.empty())
  1366. DeclAndIsDerivedMember.setInt(true);
  1367. if (isDerivedMember()) {
  1368. Path.push_back(Base);
  1369. return true;
  1370. }
  1371. return castBack(Base);
  1372. }
  1373. };
  1374. /// Compare two member pointers, which are assumed to be of the same type.
  1375. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1376. if (!LHS.getDecl() || !RHS.getDecl())
  1377. return !LHS.getDecl() && !RHS.getDecl();
  1378. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1379. return false;
  1380. return LHS.Path == RHS.Path;
  1381. }
  1382. }
  1383. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1384. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1385. const LValue &This, const Expr *E,
  1386. bool AllowNonLiteralTypes = false);
  1387. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1388. bool InvalidBaseOK = false);
  1389. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1390. bool InvalidBaseOK = false);
  1391. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1392. EvalInfo &Info);
  1393. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1394. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1395. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1396. EvalInfo &Info);
  1397. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1398. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1399. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1400. EvalInfo &Info);
  1401. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1402. //===----------------------------------------------------------------------===//
  1403. // Misc utilities
  1404. //===----------------------------------------------------------------------===//
  1405. /// A helper function to create a temporary and set an LValue.
  1406. template <class KeyTy>
  1407. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1408. LValue &LV, CallStackFrame &Frame) {
  1409. LV.set({Key, Frame.Info.CurrentCall->Index,
  1410. Frame.Info.CurrentCall->getTempVersion()});
  1411. return Frame.createTemporary(Key, IsLifetimeExtended);
  1412. }
  1413. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1414. /// preserving its value (by extending by up to one bit as needed).
  1415. static void negateAsSigned(APSInt &Int) {
  1416. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1417. Int = Int.extend(Int.getBitWidth() + 1);
  1418. Int.setIsSigned(true);
  1419. }
  1420. Int = -Int;
  1421. }
  1422. /// Produce a string describing the given constexpr call.
  1423. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1424. unsigned ArgIndex = 0;
  1425. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1426. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1427. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1428. if (!IsMemberCall)
  1429. Out << *Frame->Callee << '(';
  1430. if (Frame->This && IsMemberCall) {
  1431. APValue Val;
  1432. Frame->This->moveInto(Val);
  1433. Val.printPretty(Out, Frame->Info.Ctx,
  1434. Frame->This->Designator.MostDerivedType);
  1435. // FIXME: Add parens around Val if needed.
  1436. Out << "->" << *Frame->Callee << '(';
  1437. IsMemberCall = false;
  1438. }
  1439. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1440. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1441. if (ArgIndex > (unsigned)IsMemberCall)
  1442. Out << ", ";
  1443. const ParmVarDecl *Param = *I;
  1444. const APValue &Arg = Frame->Arguments[ArgIndex];
  1445. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1446. if (ArgIndex == 0 && IsMemberCall)
  1447. Out << "->" << *Frame->Callee << '(';
  1448. }
  1449. Out << ')';
  1450. }
  1451. /// Evaluate an expression to see if it had side-effects, and discard its
  1452. /// result.
  1453. /// \return \c true if the caller should keep evaluating.
  1454. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1455. APValue Scratch;
  1456. if (!Evaluate(Scratch, Info, E))
  1457. // We don't need the value, but we might have skipped a side effect here.
  1458. return Info.noteSideEffect();
  1459. return true;
  1460. }
  1461. /// Should this call expression be treated as a string literal?
  1462. static bool IsStringLiteralCall(const CallExpr *E) {
  1463. unsigned Builtin = E->getBuiltinCallee();
  1464. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1465. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1466. }
  1467. static bool IsGlobalLValue(APValue::LValueBase B) {
  1468. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1469. // constant expression of pointer type that evaluates to...
  1470. // ... a null pointer value, or a prvalue core constant expression of type
  1471. // std::nullptr_t.
  1472. if (!B) return true;
  1473. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1474. // ... the address of an object with static storage duration,
  1475. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1476. return VD->hasGlobalStorage();
  1477. // ... the address of a function,
  1478. return isa<FunctionDecl>(D);
  1479. }
  1480. const Expr *E = B.get<const Expr*>();
  1481. switch (E->getStmtClass()) {
  1482. default:
  1483. return false;
  1484. case Expr::CompoundLiteralExprClass: {
  1485. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1486. return CLE->isFileScope() && CLE->isLValue();
  1487. }
  1488. case Expr::MaterializeTemporaryExprClass:
  1489. // A materialized temporary might have been lifetime-extended to static
  1490. // storage duration.
  1491. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1492. // A string literal has static storage duration.
  1493. case Expr::StringLiteralClass:
  1494. case Expr::PredefinedExprClass:
  1495. case Expr::ObjCStringLiteralClass:
  1496. case Expr::ObjCEncodeExprClass:
  1497. case Expr::CXXTypeidExprClass:
  1498. case Expr::CXXUuidofExprClass:
  1499. return true;
  1500. case Expr::CallExprClass:
  1501. return IsStringLiteralCall(cast<CallExpr>(E));
  1502. // For GCC compatibility, &&label has static storage duration.
  1503. case Expr::AddrLabelExprClass:
  1504. return true;
  1505. // A Block literal expression may be used as the initialization value for
  1506. // Block variables at global or local static scope.
  1507. case Expr::BlockExprClass:
  1508. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1509. case Expr::ImplicitValueInitExprClass:
  1510. // FIXME:
  1511. // We can never form an lvalue with an implicit value initialization as its
  1512. // base through expression evaluation, so these only appear in one case: the
  1513. // implicit variable declaration we invent when checking whether a constexpr
  1514. // constructor can produce a constant expression. We must assume that such
  1515. // an expression might be a global lvalue.
  1516. return true;
  1517. }
  1518. }
  1519. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1520. return LVal.Base.dyn_cast<const ValueDecl*>();
  1521. }
  1522. static bool IsLiteralLValue(const LValue &Value) {
  1523. if (Value.getLValueCallIndex())
  1524. return false;
  1525. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1526. return E && !isa<MaterializeTemporaryExpr>(E);
  1527. }
  1528. static bool IsWeakLValue(const LValue &Value) {
  1529. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1530. return Decl && Decl->isWeak();
  1531. }
  1532. static bool isZeroSized(const LValue &Value) {
  1533. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1534. if (Decl && isa<VarDecl>(Decl)) {
  1535. QualType Ty = Decl->getType();
  1536. if (Ty->isArrayType())
  1537. return Ty->isIncompleteType() ||
  1538. Decl->getASTContext().getTypeSize(Ty) == 0;
  1539. }
  1540. return false;
  1541. }
  1542. static bool HasSameBase(const LValue &A, const LValue &B) {
  1543. if (!A.getLValueBase())
  1544. return !B.getLValueBase();
  1545. if (!B.getLValueBase())
  1546. return false;
  1547. if (A.getLValueBase().getOpaqueValue() !=
  1548. B.getLValueBase().getOpaqueValue()) {
  1549. const Decl *ADecl = GetLValueBaseDecl(A);
  1550. if (!ADecl)
  1551. return false;
  1552. const Decl *BDecl = GetLValueBaseDecl(B);
  1553. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1554. return false;
  1555. }
  1556. return IsGlobalLValue(A.getLValueBase()) ||
  1557. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1558. A.getLValueVersion() == B.getLValueVersion());
  1559. }
  1560. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1561. assert(Base && "no location for a null lvalue");
  1562. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1563. if (VD)
  1564. Info.Note(VD->getLocation(), diag::note_declared_at);
  1565. else
  1566. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1567. diag::note_constexpr_temporary_here);
  1568. }
  1569. /// Check that this reference or pointer core constant expression is a valid
  1570. /// value for an address or reference constant expression. Return true if we
  1571. /// can fold this expression, whether or not it's a constant expression.
  1572. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1573. QualType Type, const LValue &LVal,
  1574. Expr::ConstExprUsage Usage) {
  1575. bool IsReferenceType = Type->isReferenceType();
  1576. APValue::LValueBase Base = LVal.getLValueBase();
  1577. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1578. // Check that the object is a global. Note that the fake 'this' object we
  1579. // manufacture when checking potential constant expressions is conservatively
  1580. // assumed to be global here.
  1581. if (!IsGlobalLValue(Base)) {
  1582. if (Info.getLangOpts().CPlusPlus11) {
  1583. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1584. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1585. << IsReferenceType << !Designator.Entries.empty()
  1586. << !!VD << VD;
  1587. NoteLValueLocation(Info, Base);
  1588. } else {
  1589. Info.FFDiag(Loc);
  1590. }
  1591. // Don't allow references to temporaries to escape.
  1592. return false;
  1593. }
  1594. assert((Info.checkingPotentialConstantExpression() ||
  1595. LVal.getLValueCallIndex() == 0) &&
  1596. "have call index for global lvalue");
  1597. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1598. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1599. // Check if this is a thread-local variable.
  1600. if (Var->getTLSKind())
  1601. return false;
  1602. // A dllimport variable never acts like a constant.
  1603. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1604. return false;
  1605. }
  1606. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1607. // __declspec(dllimport) must be handled very carefully:
  1608. // We must never initialize an expression with the thunk in C++.
  1609. // Doing otherwise would allow the same id-expression to yield
  1610. // different addresses for the same function in different translation
  1611. // units. However, this means that we must dynamically initialize the
  1612. // expression with the contents of the import address table at runtime.
  1613. //
  1614. // The C language has no notion of ODR; furthermore, it has no notion of
  1615. // dynamic initialization. This means that we are permitted to
  1616. // perform initialization with the address of the thunk.
  1617. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1618. FD->hasAttr<DLLImportAttr>())
  1619. return false;
  1620. }
  1621. }
  1622. // Allow address constant expressions to be past-the-end pointers. This is
  1623. // an extension: the standard requires them to point to an object.
  1624. if (!IsReferenceType)
  1625. return true;
  1626. // A reference constant expression must refer to an object.
  1627. if (!Base) {
  1628. // FIXME: diagnostic
  1629. Info.CCEDiag(Loc);
  1630. return true;
  1631. }
  1632. // Does this refer one past the end of some object?
  1633. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1634. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1635. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1636. << !Designator.Entries.empty() << !!VD << VD;
  1637. NoteLValueLocation(Info, Base);
  1638. }
  1639. return true;
  1640. }
  1641. /// Member pointers are constant expressions unless they point to a
  1642. /// non-virtual dllimport member function.
  1643. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1644. SourceLocation Loc,
  1645. QualType Type,
  1646. const APValue &Value,
  1647. Expr::ConstExprUsage Usage) {
  1648. const ValueDecl *Member = Value.getMemberPointerDecl();
  1649. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1650. if (!FD)
  1651. return true;
  1652. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1653. !FD->hasAttr<DLLImportAttr>();
  1654. }
  1655. /// Check that this core constant expression is of literal type, and if not,
  1656. /// produce an appropriate diagnostic.
  1657. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1658. const LValue *This = nullptr) {
  1659. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1660. return true;
  1661. // C++1y: A constant initializer for an object o [...] may also invoke
  1662. // constexpr constructors for o and its subobjects even if those objects
  1663. // are of non-literal class types.
  1664. //
  1665. // C++11 missed this detail for aggregates, so classes like this:
  1666. // struct foo_t { union { int i; volatile int j; } u; };
  1667. // are not (obviously) initializable like so:
  1668. // __attribute__((__require_constant_initialization__))
  1669. // static const foo_t x = {{0}};
  1670. // because "i" is a subobject with non-literal initialization (due to the
  1671. // volatile member of the union). See:
  1672. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1673. // Therefore, we use the C++1y behavior.
  1674. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1675. return true;
  1676. // Prvalue constant expressions must be of literal types.
  1677. if (Info.getLangOpts().CPlusPlus11)
  1678. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1679. << E->getType();
  1680. else
  1681. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1682. return false;
  1683. }
  1684. /// Check that this core constant expression value is a valid value for a
  1685. /// constant expression. If not, report an appropriate diagnostic. Does not
  1686. /// check that the expression is of literal type.
  1687. static bool
  1688. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1689. const APValue &Value,
  1690. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1691. if (Value.isUninit()) {
  1692. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1693. << true << Type;
  1694. return false;
  1695. }
  1696. // We allow _Atomic(T) to be initialized from anything that T can be
  1697. // initialized from.
  1698. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1699. Type = AT->getValueType();
  1700. // Core issue 1454: For a literal constant expression of array or class type,
  1701. // each subobject of its value shall have been initialized by a constant
  1702. // expression.
  1703. if (Value.isArray()) {
  1704. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1705. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1706. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1707. Value.getArrayInitializedElt(I), Usage))
  1708. return false;
  1709. }
  1710. if (!Value.hasArrayFiller())
  1711. return true;
  1712. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1713. Usage);
  1714. }
  1715. if (Value.isUnion() && Value.getUnionField()) {
  1716. return CheckConstantExpression(Info, DiagLoc,
  1717. Value.getUnionField()->getType(),
  1718. Value.getUnionValue(), Usage);
  1719. }
  1720. if (Value.isStruct()) {
  1721. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1722. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1723. unsigned BaseIndex = 0;
  1724. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1725. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1726. Value.getStructBase(BaseIndex), Usage))
  1727. return false;
  1728. ++BaseIndex;
  1729. }
  1730. }
  1731. for (const auto *I : RD->fields()) {
  1732. if (I->isUnnamedBitfield())
  1733. continue;
  1734. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1735. Value.getStructField(I->getFieldIndex()),
  1736. Usage))
  1737. return false;
  1738. }
  1739. }
  1740. if (Value.isLValue()) {
  1741. LValue LVal;
  1742. LVal.setFrom(Info.Ctx, Value);
  1743. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1744. }
  1745. if (Value.isMemberPointer())
  1746. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1747. // Everything else is fine.
  1748. return true;
  1749. }
  1750. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1751. // A null base expression indicates a null pointer. These are always
  1752. // evaluatable, and they are false unless the offset is zero.
  1753. if (!Value.getLValueBase()) {
  1754. Result = !Value.getLValueOffset().isZero();
  1755. return true;
  1756. }
  1757. // We have a non-null base. These are generally known to be true, but if it's
  1758. // a weak declaration it can be null at runtime.
  1759. Result = true;
  1760. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1761. return !Decl || !Decl->isWeak();
  1762. }
  1763. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1764. switch (Val.getKind()) {
  1765. case APValue::Uninitialized:
  1766. return false;
  1767. case APValue::Int:
  1768. Result = Val.getInt().getBoolValue();
  1769. return true;
  1770. case APValue::Float:
  1771. Result = !Val.getFloat().isZero();
  1772. return true;
  1773. case APValue::ComplexInt:
  1774. Result = Val.getComplexIntReal().getBoolValue() ||
  1775. Val.getComplexIntImag().getBoolValue();
  1776. return true;
  1777. case APValue::ComplexFloat:
  1778. Result = !Val.getComplexFloatReal().isZero() ||
  1779. !Val.getComplexFloatImag().isZero();
  1780. return true;
  1781. case APValue::LValue:
  1782. return EvalPointerValueAsBool(Val, Result);
  1783. case APValue::MemberPointer:
  1784. Result = Val.getMemberPointerDecl();
  1785. return true;
  1786. case APValue::Vector:
  1787. case APValue::Array:
  1788. case APValue::Struct:
  1789. case APValue::Union:
  1790. case APValue::AddrLabelDiff:
  1791. return false;
  1792. }
  1793. llvm_unreachable("unknown APValue kind");
  1794. }
  1795. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1796. EvalInfo &Info) {
  1797. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1798. APValue Val;
  1799. if (!Evaluate(Val, Info, E))
  1800. return false;
  1801. return HandleConversionToBool(Val, Result);
  1802. }
  1803. template<typename T>
  1804. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1805. const T &SrcValue, QualType DestType) {
  1806. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1807. << SrcValue << DestType;
  1808. return Info.noteUndefinedBehavior();
  1809. }
  1810. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1811. QualType SrcType, const APFloat &Value,
  1812. QualType DestType, APSInt &Result) {
  1813. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1814. // Determine whether we are converting to unsigned or signed.
  1815. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1816. Result = APSInt(DestWidth, !DestSigned);
  1817. bool ignored;
  1818. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1819. & APFloat::opInvalidOp)
  1820. return HandleOverflow(Info, E, Value, DestType);
  1821. return true;
  1822. }
  1823. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1824. QualType SrcType, QualType DestType,
  1825. APFloat &Result) {
  1826. APFloat Value = Result;
  1827. bool ignored;
  1828. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1829. APFloat::rmNearestTiesToEven, &ignored)
  1830. & APFloat::opOverflow)
  1831. return HandleOverflow(Info, E, Value, DestType);
  1832. return true;
  1833. }
  1834. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1835. QualType DestType, QualType SrcType,
  1836. const APSInt &Value) {
  1837. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1838. // Figure out if this is a truncate, extend or noop cast.
  1839. // If the input is signed, do a sign extend, noop, or truncate.
  1840. APSInt Result = Value.extOrTrunc(DestWidth);
  1841. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1842. if (DestType->isBooleanType())
  1843. Result = Value.getBoolValue();
  1844. return Result;
  1845. }
  1846. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1847. QualType SrcType, const APSInt &Value,
  1848. QualType DestType, APFloat &Result) {
  1849. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1850. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1851. APFloat::rmNearestTiesToEven)
  1852. & APFloat::opOverflow)
  1853. return HandleOverflow(Info, E, Value, DestType);
  1854. return true;
  1855. }
  1856. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1857. APValue &Value, const FieldDecl *FD) {
  1858. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1859. if (!Value.isInt()) {
  1860. // Trying to store a pointer-cast-to-integer into a bitfield.
  1861. // FIXME: In this case, we should provide the diagnostic for casting
  1862. // a pointer to an integer.
  1863. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1864. Info.FFDiag(E);
  1865. return false;
  1866. }
  1867. APSInt &Int = Value.getInt();
  1868. unsigned OldBitWidth = Int.getBitWidth();
  1869. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1870. if (NewBitWidth < OldBitWidth)
  1871. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1872. return true;
  1873. }
  1874. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1875. llvm::APInt &Res) {
  1876. APValue SVal;
  1877. if (!Evaluate(SVal, Info, E))
  1878. return false;
  1879. if (SVal.isInt()) {
  1880. Res = SVal.getInt();
  1881. return true;
  1882. }
  1883. if (SVal.isFloat()) {
  1884. Res = SVal.getFloat().bitcastToAPInt();
  1885. return true;
  1886. }
  1887. if (SVal.isVector()) {
  1888. QualType VecTy = E->getType();
  1889. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1890. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1891. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1892. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1893. Res = llvm::APInt::getNullValue(VecSize);
  1894. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1895. APValue &Elt = SVal.getVectorElt(i);
  1896. llvm::APInt EltAsInt;
  1897. if (Elt.isInt()) {
  1898. EltAsInt = Elt.getInt();
  1899. } else if (Elt.isFloat()) {
  1900. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1901. } else {
  1902. // Don't try to handle vectors of anything other than int or float
  1903. // (not sure if it's possible to hit this case).
  1904. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1905. return false;
  1906. }
  1907. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1908. if (BigEndian)
  1909. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1910. else
  1911. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1912. }
  1913. return true;
  1914. }
  1915. // Give up if the input isn't an int, float, or vector. For example, we
  1916. // reject "(v4i16)(intptr_t)&a".
  1917. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1918. return false;
  1919. }
  1920. /// Perform the given integer operation, which is known to need at most BitWidth
  1921. /// bits, and check for overflow in the original type (if that type was not an
  1922. /// unsigned type).
  1923. template<typename Operation>
  1924. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1925. const APSInt &LHS, const APSInt &RHS,
  1926. unsigned BitWidth, Operation Op,
  1927. APSInt &Result) {
  1928. if (LHS.isUnsigned()) {
  1929. Result = Op(LHS, RHS);
  1930. return true;
  1931. }
  1932. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1933. Result = Value.trunc(LHS.getBitWidth());
  1934. if (Result.extend(BitWidth) != Value) {
  1935. if (Info.checkingForOverflow())
  1936. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1937. diag::warn_integer_constant_overflow)
  1938. << Result.toString(10) << E->getType();
  1939. else
  1940. return HandleOverflow(Info, E, Value, E->getType());
  1941. }
  1942. return true;
  1943. }
  1944. /// Perform the given binary integer operation.
  1945. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1946. BinaryOperatorKind Opcode, APSInt RHS,
  1947. APSInt &Result) {
  1948. switch (Opcode) {
  1949. default:
  1950. Info.FFDiag(E);
  1951. return false;
  1952. case BO_Mul:
  1953. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1954. std::multiplies<APSInt>(), Result);
  1955. case BO_Add:
  1956. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1957. std::plus<APSInt>(), Result);
  1958. case BO_Sub:
  1959. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1960. std::minus<APSInt>(), Result);
  1961. case BO_And: Result = LHS & RHS; return true;
  1962. case BO_Xor: Result = LHS ^ RHS; return true;
  1963. case BO_Or: Result = LHS | RHS; return true;
  1964. case BO_Div:
  1965. case BO_Rem:
  1966. if (RHS == 0) {
  1967. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  1968. return false;
  1969. }
  1970. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1971. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  1972. // this operation and gives the two's complement result.
  1973. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1974. LHS.isSigned() && LHS.isMinSignedValue())
  1975. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  1976. E->getType());
  1977. return true;
  1978. case BO_Shl: {
  1979. if (Info.getLangOpts().OpenCL)
  1980. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1981. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1982. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1983. RHS.isUnsigned());
  1984. else if (RHS.isSigned() && RHS.isNegative()) {
  1985. // During constant-folding, a negative shift is an opposite shift. Such
  1986. // a shift is not a constant expression.
  1987. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1988. RHS = -RHS;
  1989. goto shift_right;
  1990. }
  1991. shift_left:
  1992. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  1993. // the shifted type.
  1994. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1995. if (SA != RHS) {
  1996. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1997. << RHS << E->getType() << LHS.getBitWidth();
  1998. } else if (LHS.isSigned()) {
  1999. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2000. // operand, and must not overflow the corresponding unsigned type.
  2001. if (LHS.isNegative())
  2002. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2003. else if (LHS.countLeadingZeros() < SA)
  2004. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2005. }
  2006. Result = LHS << SA;
  2007. return true;
  2008. }
  2009. case BO_Shr: {
  2010. if (Info.getLangOpts().OpenCL)
  2011. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2012. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2013. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2014. RHS.isUnsigned());
  2015. else if (RHS.isSigned() && RHS.isNegative()) {
  2016. // During constant-folding, a negative shift is an opposite shift. Such a
  2017. // shift is not a constant expression.
  2018. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2019. RHS = -RHS;
  2020. goto shift_left;
  2021. }
  2022. shift_right:
  2023. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2024. // shifted type.
  2025. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2026. if (SA != RHS)
  2027. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2028. << RHS << E->getType() << LHS.getBitWidth();
  2029. Result = LHS >> SA;
  2030. return true;
  2031. }
  2032. case BO_LT: Result = LHS < RHS; return true;
  2033. case BO_GT: Result = LHS > RHS; return true;
  2034. case BO_LE: Result = LHS <= RHS; return true;
  2035. case BO_GE: Result = LHS >= RHS; return true;
  2036. case BO_EQ: Result = LHS == RHS; return true;
  2037. case BO_NE: Result = LHS != RHS; return true;
  2038. case BO_Cmp:
  2039. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2040. }
  2041. }
  2042. /// Perform the given binary floating-point operation, in-place, on LHS.
  2043. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2044. APFloat &LHS, BinaryOperatorKind Opcode,
  2045. const APFloat &RHS) {
  2046. switch (Opcode) {
  2047. default:
  2048. Info.FFDiag(E);
  2049. return false;
  2050. case BO_Mul:
  2051. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2052. break;
  2053. case BO_Add:
  2054. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2055. break;
  2056. case BO_Sub:
  2057. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2058. break;
  2059. case BO_Div:
  2060. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2061. break;
  2062. }
  2063. if (LHS.isInfinity() || LHS.isNaN()) {
  2064. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2065. return Info.noteUndefinedBehavior();
  2066. }
  2067. return true;
  2068. }
  2069. /// Cast an lvalue referring to a base subobject to a derived class, by
  2070. /// truncating the lvalue's path to the given length.
  2071. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2072. const RecordDecl *TruncatedType,
  2073. unsigned TruncatedElements) {
  2074. SubobjectDesignator &D = Result.Designator;
  2075. // Check we actually point to a derived class object.
  2076. if (TruncatedElements == D.Entries.size())
  2077. return true;
  2078. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2079. "not casting to a derived class");
  2080. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2081. return false;
  2082. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2083. const RecordDecl *RD = TruncatedType;
  2084. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2085. if (RD->isInvalidDecl()) return false;
  2086. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2087. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2088. if (isVirtualBaseClass(D.Entries[I]))
  2089. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2090. else
  2091. Result.Offset -= Layout.getBaseClassOffset(Base);
  2092. RD = Base;
  2093. }
  2094. D.Entries.resize(TruncatedElements);
  2095. return true;
  2096. }
  2097. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2098. const CXXRecordDecl *Derived,
  2099. const CXXRecordDecl *Base,
  2100. const ASTRecordLayout *RL = nullptr) {
  2101. if (!RL) {
  2102. if (Derived->isInvalidDecl()) return false;
  2103. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2104. }
  2105. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2106. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2107. return true;
  2108. }
  2109. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2110. const CXXRecordDecl *DerivedDecl,
  2111. const CXXBaseSpecifier *Base) {
  2112. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2113. if (!Base->isVirtual())
  2114. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2115. SubobjectDesignator &D = Obj.Designator;
  2116. if (D.Invalid)
  2117. return false;
  2118. // Extract most-derived object and corresponding type.
  2119. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2120. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2121. return false;
  2122. // Find the virtual base class.
  2123. if (DerivedDecl->isInvalidDecl()) return false;
  2124. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2125. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2126. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2127. return true;
  2128. }
  2129. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2130. QualType Type, LValue &Result) {
  2131. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2132. PathE = E->path_end();
  2133. PathI != PathE; ++PathI) {
  2134. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2135. *PathI))
  2136. return false;
  2137. Type = (*PathI)->getType();
  2138. }
  2139. return true;
  2140. }
  2141. /// Update LVal to refer to the given field, which must be a member of the type
  2142. /// currently described by LVal.
  2143. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2144. const FieldDecl *FD,
  2145. const ASTRecordLayout *RL = nullptr) {
  2146. if (!RL) {
  2147. if (FD->getParent()->isInvalidDecl()) return false;
  2148. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2149. }
  2150. unsigned I = FD->getFieldIndex();
  2151. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2152. LVal.addDecl(Info, E, FD);
  2153. return true;
  2154. }
  2155. /// Update LVal to refer to the given indirect field.
  2156. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2157. LValue &LVal,
  2158. const IndirectFieldDecl *IFD) {
  2159. for (const auto *C : IFD->chain())
  2160. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2161. return false;
  2162. return true;
  2163. }
  2164. /// Get the size of the given type in char units.
  2165. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2166. QualType Type, CharUnits &Size) {
  2167. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2168. // extension.
  2169. if (Type->isVoidType() || Type->isFunctionType()) {
  2170. Size = CharUnits::One();
  2171. return true;
  2172. }
  2173. if (Type->isDependentType()) {
  2174. Info.FFDiag(Loc);
  2175. return false;
  2176. }
  2177. if (!Type->isConstantSizeType()) {
  2178. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2179. // FIXME: Better diagnostic.
  2180. Info.FFDiag(Loc);
  2181. return false;
  2182. }
  2183. Size = Info.Ctx.getTypeSizeInChars(Type);
  2184. return true;
  2185. }
  2186. /// Update a pointer value to model pointer arithmetic.
  2187. /// \param Info - Information about the ongoing evaluation.
  2188. /// \param E - The expression being evaluated, for diagnostic purposes.
  2189. /// \param LVal - The pointer value to be updated.
  2190. /// \param EltTy - The pointee type represented by LVal.
  2191. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2192. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2193. LValue &LVal, QualType EltTy,
  2194. APSInt Adjustment) {
  2195. CharUnits SizeOfPointee;
  2196. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2197. return false;
  2198. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2199. return true;
  2200. }
  2201. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2202. LValue &LVal, QualType EltTy,
  2203. int64_t Adjustment) {
  2204. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2205. APSInt::get(Adjustment));
  2206. }
  2207. /// Update an lvalue to refer to a component of a complex number.
  2208. /// \param Info - Information about the ongoing evaluation.
  2209. /// \param LVal - The lvalue to be updated.
  2210. /// \param EltTy - The complex number's component type.
  2211. /// \param Imag - False for the real component, true for the imaginary.
  2212. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2213. LValue &LVal, QualType EltTy,
  2214. bool Imag) {
  2215. if (Imag) {
  2216. CharUnits SizeOfComponent;
  2217. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2218. return false;
  2219. LVal.Offset += SizeOfComponent;
  2220. }
  2221. LVal.addComplex(Info, E, EltTy, Imag);
  2222. return true;
  2223. }
  2224. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2225. QualType Type, const LValue &LVal,
  2226. APValue &RVal);
  2227. /// Try to evaluate the initializer for a variable declaration.
  2228. ///
  2229. /// \param Info Information about the ongoing evaluation.
  2230. /// \param E An expression to be used when printing diagnostics.
  2231. /// \param VD The variable whose initializer should be obtained.
  2232. /// \param Frame The frame in which the variable was created. Must be null
  2233. /// if this variable is not local to the evaluation.
  2234. /// \param Result Filled in with a pointer to the value of the variable.
  2235. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2236. const VarDecl *VD, CallStackFrame *Frame,
  2237. APValue *&Result, const LValue *LVal) {
  2238. // If this is a parameter to an active constexpr function call, perform
  2239. // argument substitution.
  2240. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2241. // Assume arguments of a potential constant expression are unknown
  2242. // constant expressions.
  2243. if (Info.checkingPotentialConstantExpression())
  2244. return false;
  2245. if (!Frame || !Frame->Arguments) {
  2246. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2247. return false;
  2248. }
  2249. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2250. return true;
  2251. }
  2252. // If this is a local variable, dig out its value.
  2253. if (Frame) {
  2254. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2255. : Frame->getCurrentTemporary(VD);
  2256. if (!Result) {
  2257. // Assume variables referenced within a lambda's call operator that were
  2258. // not declared within the call operator are captures and during checking
  2259. // of a potential constant expression, assume they are unknown constant
  2260. // expressions.
  2261. assert(isLambdaCallOperator(Frame->Callee) &&
  2262. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2263. "missing value for local variable");
  2264. if (Info.checkingPotentialConstantExpression())
  2265. return false;
  2266. // FIXME: implement capture evaluation during constant expr evaluation.
  2267. Info.FFDiag(E->getBeginLoc(),
  2268. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2269. << "captures not currently allowed";
  2270. return false;
  2271. }
  2272. return true;
  2273. }
  2274. // Dig out the initializer, and use the declaration which it's attached to.
  2275. const Expr *Init = VD->getAnyInitializer(VD);
  2276. if (!Init || Init->isValueDependent()) {
  2277. // If we're checking a potential constant expression, the variable could be
  2278. // initialized later.
  2279. if (!Info.checkingPotentialConstantExpression())
  2280. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2281. return false;
  2282. }
  2283. // If we're currently evaluating the initializer of this declaration, use that
  2284. // in-flight value.
  2285. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2286. Result = Info.EvaluatingDeclValue;
  2287. return true;
  2288. }
  2289. // Never evaluate the initializer of a weak variable. We can't be sure that
  2290. // this is the definition which will be used.
  2291. if (VD->isWeak()) {
  2292. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2293. return false;
  2294. }
  2295. // Check that we can fold the initializer. In C++, we will have already done
  2296. // this in the cases where it matters for conformance.
  2297. SmallVector<PartialDiagnosticAt, 8> Notes;
  2298. if (!VD->evaluateValue(Notes)) {
  2299. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2300. Notes.size() + 1) << VD;
  2301. Info.Note(VD->getLocation(), diag::note_declared_at);
  2302. Info.addNotes(Notes);
  2303. return false;
  2304. } else if (!VD->checkInitIsICE()) {
  2305. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2306. Notes.size() + 1) << VD;
  2307. Info.Note(VD->getLocation(), diag::note_declared_at);
  2308. Info.addNotes(Notes);
  2309. }
  2310. Result = VD->getEvaluatedValue();
  2311. return true;
  2312. }
  2313. static bool IsConstNonVolatile(QualType T) {
  2314. Qualifiers Quals = T.getQualifiers();
  2315. return Quals.hasConst() && !Quals.hasVolatile();
  2316. }
  2317. /// Get the base index of the given base class within an APValue representing
  2318. /// the given derived class.
  2319. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2320. const CXXRecordDecl *Base) {
  2321. Base = Base->getCanonicalDecl();
  2322. unsigned Index = 0;
  2323. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2324. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2325. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2326. return Index;
  2327. }
  2328. llvm_unreachable("base class missing from derived class's bases list");
  2329. }
  2330. /// Extract the value of a character from a string literal.
  2331. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2332. uint64_t Index) {
  2333. // FIXME: Support MakeStringConstant
  2334. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2335. std::string Str;
  2336. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2337. assert(Index <= Str.size() && "Index too large");
  2338. return APSInt::getUnsigned(Str.c_str()[Index]);
  2339. }
  2340. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2341. Lit = PE->getFunctionName();
  2342. const StringLiteral *S = cast<StringLiteral>(Lit);
  2343. const ConstantArrayType *CAT =
  2344. Info.Ctx.getAsConstantArrayType(S->getType());
  2345. assert(CAT && "string literal isn't an array");
  2346. QualType CharType = CAT->getElementType();
  2347. assert(CharType->isIntegerType() && "unexpected character type");
  2348. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2349. CharType->isUnsignedIntegerType());
  2350. if (Index < S->getLength())
  2351. Value = S->getCodeUnit(Index);
  2352. return Value;
  2353. }
  2354. // Expand a string literal into an array of characters.
  2355. static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
  2356. APValue &Result) {
  2357. const StringLiteral *S = cast<StringLiteral>(Lit);
  2358. const ConstantArrayType *CAT =
  2359. Info.Ctx.getAsConstantArrayType(S->getType());
  2360. assert(CAT && "string literal isn't an array");
  2361. QualType CharType = CAT->getElementType();
  2362. assert(CharType->isIntegerType() && "unexpected character type");
  2363. unsigned Elts = CAT->getSize().getZExtValue();
  2364. Result = APValue(APValue::UninitArray(),
  2365. std::min(S->getLength(), Elts), Elts);
  2366. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2367. CharType->isUnsignedIntegerType());
  2368. if (Result.hasArrayFiller())
  2369. Result.getArrayFiller() = APValue(Value);
  2370. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2371. Value = S->getCodeUnit(I);
  2372. Result.getArrayInitializedElt(I) = APValue(Value);
  2373. }
  2374. }
  2375. // Expand an array so that it has more than Index filled elements.
  2376. static void expandArray(APValue &Array, unsigned Index) {
  2377. unsigned Size = Array.getArraySize();
  2378. assert(Index < Size);
  2379. // Always at least double the number of elements for which we store a value.
  2380. unsigned OldElts = Array.getArrayInitializedElts();
  2381. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2382. NewElts = std::min(Size, std::max(NewElts, 8u));
  2383. // Copy the data across.
  2384. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2385. for (unsigned I = 0; I != OldElts; ++I)
  2386. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2387. for (unsigned I = OldElts; I != NewElts; ++I)
  2388. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2389. if (NewValue.hasArrayFiller())
  2390. NewValue.getArrayFiller() = Array.getArrayFiller();
  2391. Array.swap(NewValue);
  2392. }
  2393. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2394. /// conversion. If it's of class type, we may assume that the copy operation
  2395. /// is trivial. Note that this is never true for a union type with fields
  2396. /// (because the copy always "reads" the active member) and always true for
  2397. /// a non-class type.
  2398. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2399. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2400. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2401. return true;
  2402. if (RD->isEmpty())
  2403. return false;
  2404. for (auto *Field : RD->fields())
  2405. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2406. return true;
  2407. for (auto &BaseSpec : RD->bases())
  2408. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2409. return true;
  2410. return false;
  2411. }
  2412. /// Diagnose an attempt to read from any unreadable field within the specified
  2413. /// type, which might be a class type.
  2414. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2415. QualType T) {
  2416. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2417. if (!RD)
  2418. return false;
  2419. if (!RD->hasMutableFields())
  2420. return false;
  2421. for (auto *Field : RD->fields()) {
  2422. // If we're actually going to read this field in some way, then it can't
  2423. // be mutable. If we're in a union, then assigning to a mutable field
  2424. // (even an empty one) can change the active member, so that's not OK.
  2425. // FIXME: Add core issue number for the union case.
  2426. if (Field->isMutable() &&
  2427. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2428. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2429. Info.Note(Field->getLocation(), diag::note_declared_at);
  2430. return true;
  2431. }
  2432. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2433. return true;
  2434. }
  2435. for (auto &BaseSpec : RD->bases())
  2436. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2437. return true;
  2438. // All mutable fields were empty, and thus not actually read.
  2439. return false;
  2440. }
  2441. /// Kinds of access we can perform on an object, for diagnostics.
  2442. enum AccessKinds {
  2443. AK_Read,
  2444. AK_Assign,
  2445. AK_Increment,
  2446. AK_Decrement
  2447. };
  2448. namespace {
  2449. /// A handle to a complete object (an object that is not a subobject of
  2450. /// another object).
  2451. struct CompleteObject {
  2452. /// The value of the complete object.
  2453. APValue *Value;
  2454. /// The type of the complete object.
  2455. QualType Type;
  2456. bool LifetimeStartedInEvaluation;
  2457. CompleteObject() : Value(nullptr) {}
  2458. CompleteObject(APValue *Value, QualType Type,
  2459. bool LifetimeStartedInEvaluation)
  2460. : Value(Value), Type(Type),
  2461. LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
  2462. assert(Value && "missing value for complete object");
  2463. }
  2464. explicit operator bool() const { return Value; }
  2465. };
  2466. } // end anonymous namespace
  2467. /// Find the designated sub-object of an rvalue.
  2468. template<typename SubobjectHandler>
  2469. typename SubobjectHandler::result_type
  2470. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2471. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2472. if (Sub.Invalid)
  2473. // A diagnostic will have already been produced.
  2474. return handler.failed();
  2475. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2476. if (Info.getLangOpts().CPlusPlus11)
  2477. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2478. ? diag::note_constexpr_access_past_end
  2479. : diag::note_constexpr_access_unsized_array)
  2480. << handler.AccessKind;
  2481. else
  2482. Info.FFDiag(E);
  2483. return handler.failed();
  2484. }
  2485. APValue *O = Obj.Value;
  2486. QualType ObjType = Obj.Type;
  2487. const FieldDecl *LastField = nullptr;
  2488. const bool MayReadMutableMembers =
  2489. Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
  2490. // Walk the designator's path to find the subobject.
  2491. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2492. if (O->isUninit()) {
  2493. if (!Info.checkingPotentialConstantExpression())
  2494. Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
  2495. return handler.failed();
  2496. }
  2497. if (I == N) {
  2498. // If we are reading an object of class type, there may still be more
  2499. // things we need to check: if there are any mutable subobjects, we
  2500. // cannot perform this read. (This only happens when performing a trivial
  2501. // copy or assignment.)
  2502. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2503. !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
  2504. return handler.failed();
  2505. if (!handler.found(*O, ObjType))
  2506. return false;
  2507. // If we modified a bit-field, truncate it to the right width.
  2508. if (handler.AccessKind != AK_Read &&
  2509. LastField && LastField->isBitField() &&
  2510. !truncateBitfieldValue(Info, E, *O, LastField))
  2511. return false;
  2512. return true;
  2513. }
  2514. LastField = nullptr;
  2515. if (ObjType->isArrayType()) {
  2516. // Next subobject is an array element.
  2517. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2518. assert(CAT && "vla in literal type?");
  2519. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2520. if (CAT->getSize().ule(Index)) {
  2521. // Note, it should not be possible to form a pointer with a valid
  2522. // designator which points more than one past the end of the array.
  2523. if (Info.getLangOpts().CPlusPlus11)
  2524. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2525. << handler.AccessKind;
  2526. else
  2527. Info.FFDiag(E);
  2528. return handler.failed();
  2529. }
  2530. ObjType = CAT->getElementType();
  2531. // An array object is represented as either an Array APValue or as an
  2532. // LValue which refers to a string literal.
  2533. if (O->isLValue()) {
  2534. assert(I == N - 1 && "extracting subobject of character?");
  2535. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  2536. if (handler.AccessKind != AK_Read)
  2537. expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
  2538. *O);
  2539. else
  2540. return handler.foundString(*O, ObjType, Index);
  2541. }
  2542. if (O->getArrayInitializedElts() > Index)
  2543. O = &O->getArrayInitializedElt(Index);
  2544. else if (handler.AccessKind != AK_Read) {
  2545. expandArray(*O, Index);
  2546. O = &O->getArrayInitializedElt(Index);
  2547. } else
  2548. O = &O->getArrayFiller();
  2549. } else if (ObjType->isAnyComplexType()) {
  2550. // Next subobject is a complex number.
  2551. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2552. if (Index > 1) {
  2553. if (Info.getLangOpts().CPlusPlus11)
  2554. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2555. << handler.AccessKind;
  2556. else
  2557. Info.FFDiag(E);
  2558. return handler.failed();
  2559. }
  2560. bool WasConstQualified = ObjType.isConstQualified();
  2561. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2562. if (WasConstQualified)
  2563. ObjType.addConst();
  2564. assert(I == N - 1 && "extracting subobject of scalar?");
  2565. if (O->isComplexInt()) {
  2566. return handler.found(Index ? O->getComplexIntImag()
  2567. : O->getComplexIntReal(), ObjType);
  2568. } else {
  2569. assert(O->isComplexFloat());
  2570. return handler.found(Index ? O->getComplexFloatImag()
  2571. : O->getComplexFloatReal(), ObjType);
  2572. }
  2573. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2574. // In C++14 onwards, it is permitted to read a mutable member whose
  2575. // lifetime began within the evaluation.
  2576. // FIXME: Should we also allow this in C++11?
  2577. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2578. !MayReadMutableMembers) {
  2579. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2580. << Field;
  2581. Info.Note(Field->getLocation(), diag::note_declared_at);
  2582. return handler.failed();
  2583. }
  2584. // Next subobject is a class, struct or union field.
  2585. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2586. if (RD->isUnion()) {
  2587. const FieldDecl *UnionField = O->getUnionField();
  2588. if (!UnionField ||
  2589. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2590. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2591. << handler.AccessKind << Field << !UnionField << UnionField;
  2592. return handler.failed();
  2593. }
  2594. O = &O->getUnionValue();
  2595. } else
  2596. O = &O->getStructField(Field->getFieldIndex());
  2597. bool WasConstQualified = ObjType.isConstQualified();
  2598. ObjType = Field->getType();
  2599. if (WasConstQualified && !Field->isMutable())
  2600. ObjType.addConst();
  2601. if (ObjType.isVolatileQualified()) {
  2602. if (Info.getLangOpts().CPlusPlus) {
  2603. // FIXME: Include a description of the path to the volatile subobject.
  2604. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2605. << handler.AccessKind << 2 << Field;
  2606. Info.Note(Field->getLocation(), diag::note_declared_at);
  2607. } else {
  2608. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2609. }
  2610. return handler.failed();
  2611. }
  2612. LastField = Field;
  2613. } else {
  2614. // Next subobject is a base class.
  2615. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2616. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2617. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2618. bool WasConstQualified = ObjType.isConstQualified();
  2619. ObjType = Info.Ctx.getRecordType(Base);
  2620. if (WasConstQualified)
  2621. ObjType.addConst();
  2622. }
  2623. }
  2624. }
  2625. namespace {
  2626. struct ExtractSubobjectHandler {
  2627. EvalInfo &Info;
  2628. APValue &Result;
  2629. static const AccessKinds AccessKind = AK_Read;
  2630. typedef bool result_type;
  2631. bool failed() { return false; }
  2632. bool found(APValue &Subobj, QualType SubobjType) {
  2633. Result = Subobj;
  2634. return true;
  2635. }
  2636. bool found(APSInt &Value, QualType SubobjType) {
  2637. Result = APValue(Value);
  2638. return true;
  2639. }
  2640. bool found(APFloat &Value, QualType SubobjType) {
  2641. Result = APValue(Value);
  2642. return true;
  2643. }
  2644. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2645. Result = APValue(extractStringLiteralCharacter(
  2646. Info, Subobj.getLValueBase().get<const Expr *>(), Character));
  2647. return true;
  2648. }
  2649. };
  2650. } // end anonymous namespace
  2651. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2652. /// Extract the designated sub-object of an rvalue.
  2653. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2654. const CompleteObject &Obj,
  2655. const SubobjectDesignator &Sub,
  2656. APValue &Result) {
  2657. ExtractSubobjectHandler Handler = { Info, Result };
  2658. return findSubobject(Info, E, Obj, Sub, Handler);
  2659. }
  2660. namespace {
  2661. struct ModifySubobjectHandler {
  2662. EvalInfo &Info;
  2663. APValue &NewVal;
  2664. const Expr *E;
  2665. typedef bool result_type;
  2666. static const AccessKinds AccessKind = AK_Assign;
  2667. bool checkConst(QualType QT) {
  2668. // Assigning to a const object has undefined behavior.
  2669. if (QT.isConstQualified()) {
  2670. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2671. return false;
  2672. }
  2673. return true;
  2674. }
  2675. bool failed() { return false; }
  2676. bool found(APValue &Subobj, QualType SubobjType) {
  2677. if (!checkConst(SubobjType))
  2678. return false;
  2679. // We've been given ownership of NewVal, so just swap it in.
  2680. Subobj.swap(NewVal);
  2681. return true;
  2682. }
  2683. bool found(APSInt &Value, QualType SubobjType) {
  2684. if (!checkConst(SubobjType))
  2685. return false;
  2686. if (!NewVal.isInt()) {
  2687. // Maybe trying to write a cast pointer value into a complex?
  2688. Info.FFDiag(E);
  2689. return false;
  2690. }
  2691. Value = NewVal.getInt();
  2692. return true;
  2693. }
  2694. bool found(APFloat &Value, QualType SubobjType) {
  2695. if (!checkConst(SubobjType))
  2696. return false;
  2697. Value = NewVal.getFloat();
  2698. return true;
  2699. }
  2700. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2701. llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
  2702. }
  2703. };
  2704. } // end anonymous namespace
  2705. const AccessKinds ModifySubobjectHandler::AccessKind;
  2706. /// Update the designated sub-object of an rvalue to the given value.
  2707. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2708. const CompleteObject &Obj,
  2709. const SubobjectDesignator &Sub,
  2710. APValue &NewVal) {
  2711. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2712. return findSubobject(Info, E, Obj, Sub, Handler);
  2713. }
  2714. /// Find the position where two subobject designators diverge, or equivalently
  2715. /// the length of the common initial subsequence.
  2716. static unsigned FindDesignatorMismatch(QualType ObjType,
  2717. const SubobjectDesignator &A,
  2718. const SubobjectDesignator &B,
  2719. bool &WasArrayIndex) {
  2720. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2721. for (/**/; I != N; ++I) {
  2722. if (!ObjType.isNull() &&
  2723. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2724. // Next subobject is an array element.
  2725. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  2726. WasArrayIndex = true;
  2727. return I;
  2728. }
  2729. if (ObjType->isAnyComplexType())
  2730. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2731. else
  2732. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2733. } else {
  2734. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  2735. WasArrayIndex = false;
  2736. return I;
  2737. }
  2738. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2739. // Next subobject is a field.
  2740. ObjType = FD->getType();
  2741. else
  2742. // Next subobject is a base class.
  2743. ObjType = QualType();
  2744. }
  2745. }
  2746. WasArrayIndex = false;
  2747. return I;
  2748. }
  2749. /// Determine whether the given subobject designators refer to elements of the
  2750. /// same array object.
  2751. static bool AreElementsOfSameArray(QualType ObjType,
  2752. const SubobjectDesignator &A,
  2753. const SubobjectDesignator &B) {
  2754. if (A.Entries.size() != B.Entries.size())
  2755. return false;
  2756. bool IsArray = A.MostDerivedIsArrayElement;
  2757. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2758. // A is a subobject of the array element.
  2759. return false;
  2760. // If A (and B) designates an array element, the last entry will be the array
  2761. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2762. // of length 1' case, and the entire path must match.
  2763. bool WasArrayIndex;
  2764. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2765. return CommonLength >= A.Entries.size() - IsArray;
  2766. }
  2767. /// Find the complete object to which an LValue refers.
  2768. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2769. AccessKinds AK, const LValue &LVal,
  2770. QualType LValType) {
  2771. if (!LVal.Base) {
  2772. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2773. return CompleteObject();
  2774. }
  2775. CallStackFrame *Frame = nullptr;
  2776. if (LVal.getLValueCallIndex()) {
  2777. Frame = Info.getCallFrame(LVal.getLValueCallIndex());
  2778. if (!Frame) {
  2779. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2780. << AK << LVal.Base.is<const ValueDecl*>();
  2781. NoteLValueLocation(Info, LVal.Base);
  2782. return CompleteObject();
  2783. }
  2784. }
  2785. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2786. // is not a constant expression (even if the object is non-volatile). We also
  2787. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2788. // semantics.
  2789. if (LValType.isVolatileQualified()) {
  2790. if (Info.getLangOpts().CPlusPlus)
  2791. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2792. << AK << LValType;
  2793. else
  2794. Info.FFDiag(E);
  2795. return CompleteObject();
  2796. }
  2797. // Compute value storage location and type of base object.
  2798. APValue *BaseVal = nullptr;
  2799. QualType BaseType = getType(LVal.Base);
  2800. bool LifetimeStartedInEvaluation = Frame;
  2801. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2802. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2803. // In C++11, constexpr, non-volatile variables initialized with constant
  2804. // expressions are constant expressions too. Inside constexpr functions,
  2805. // parameters are constant expressions even if they're non-const.
  2806. // In C++1y, objects local to a constant expression (those with a Frame) are
  2807. // both readable and writable inside constant expressions.
  2808. // In C, such things can also be folded, although they are not ICEs.
  2809. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2810. if (VD) {
  2811. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2812. VD = VDef;
  2813. }
  2814. if (!VD || VD->isInvalidDecl()) {
  2815. Info.FFDiag(E);
  2816. return CompleteObject();
  2817. }
  2818. // Accesses of volatile-qualified objects are not allowed.
  2819. if (BaseType.isVolatileQualified()) {
  2820. if (Info.getLangOpts().CPlusPlus) {
  2821. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2822. << AK << 1 << VD;
  2823. Info.Note(VD->getLocation(), diag::note_declared_at);
  2824. } else {
  2825. Info.FFDiag(E);
  2826. }
  2827. return CompleteObject();
  2828. }
  2829. // Unless we're looking at a local variable or argument in a constexpr call,
  2830. // the variable we're reading must be const.
  2831. if (!Frame) {
  2832. if (Info.getLangOpts().CPlusPlus14 &&
  2833. VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
  2834. // OK, we can read and modify an object if we're in the process of
  2835. // evaluating its initializer, because its lifetime began in this
  2836. // evaluation.
  2837. } else if (AK != AK_Read) {
  2838. // All the remaining cases only permit reading.
  2839. Info.FFDiag(E, diag::note_constexpr_modify_global);
  2840. return CompleteObject();
  2841. } else if (VD->isConstexpr()) {
  2842. // OK, we can read this variable.
  2843. } else if (BaseType->isIntegralOrEnumerationType()) {
  2844. // In OpenCL if a variable is in constant address space it is a const value.
  2845. if (!(BaseType.isConstQualified() ||
  2846. (Info.getLangOpts().OpenCL &&
  2847. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  2848. if (Info.getLangOpts().CPlusPlus) {
  2849. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2850. Info.Note(VD->getLocation(), diag::note_declared_at);
  2851. } else {
  2852. Info.FFDiag(E);
  2853. }
  2854. return CompleteObject();
  2855. }
  2856. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2857. // We support folding of const floating-point types, in order to make
  2858. // static const data members of such types (supported as an extension)
  2859. // more useful.
  2860. if (Info.getLangOpts().CPlusPlus11) {
  2861. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2862. Info.Note(VD->getLocation(), diag::note_declared_at);
  2863. } else {
  2864. Info.CCEDiag(E);
  2865. }
  2866. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  2867. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  2868. // Keep evaluating to see what we can do.
  2869. } else {
  2870. // FIXME: Allow folding of values of any literal type in all languages.
  2871. if (Info.checkingPotentialConstantExpression() &&
  2872. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  2873. // The definition of this variable could be constexpr. We can't
  2874. // access it right now, but may be able to in future.
  2875. } else if (Info.getLangOpts().CPlusPlus11) {
  2876. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2877. Info.Note(VD->getLocation(), diag::note_declared_at);
  2878. } else {
  2879. Info.FFDiag(E);
  2880. }
  2881. return CompleteObject();
  2882. }
  2883. }
  2884. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  2885. return CompleteObject();
  2886. } else {
  2887. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2888. if (!Frame) {
  2889. if (const MaterializeTemporaryExpr *MTE =
  2890. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  2891. assert(MTE->getStorageDuration() == SD_Static &&
  2892. "should have a frame for a non-global materialized temporary");
  2893. // Per C++1y [expr.const]p2:
  2894. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2895. // - a [...] glvalue of integral or enumeration type that refers to
  2896. // a non-volatile const object [...]
  2897. // [...]
  2898. // - a [...] glvalue of literal type that refers to a non-volatile
  2899. // object whose lifetime began within the evaluation of e.
  2900. //
  2901. // C++11 misses the 'began within the evaluation of e' check and
  2902. // instead allows all temporaries, including things like:
  2903. // int &&r = 1;
  2904. // int x = ++r;
  2905. // constexpr int k = r;
  2906. // Therefore we use the C++14 rules in C++11 too.
  2907. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2908. const ValueDecl *ED = MTE->getExtendingDecl();
  2909. if (!(BaseType.isConstQualified() &&
  2910. BaseType->isIntegralOrEnumerationType()) &&
  2911. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2912. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2913. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2914. return CompleteObject();
  2915. }
  2916. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2917. assert(BaseVal && "got reference to unevaluated temporary");
  2918. LifetimeStartedInEvaluation = true;
  2919. } else {
  2920. Info.FFDiag(E);
  2921. return CompleteObject();
  2922. }
  2923. } else {
  2924. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  2925. assert(BaseVal && "missing value for temporary");
  2926. }
  2927. // Volatile temporary objects cannot be accessed in constant expressions.
  2928. if (BaseType.isVolatileQualified()) {
  2929. if (Info.getLangOpts().CPlusPlus) {
  2930. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2931. << AK << 0;
  2932. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  2933. } else {
  2934. Info.FFDiag(E);
  2935. }
  2936. return CompleteObject();
  2937. }
  2938. }
  2939. // During the construction of an object, it is not yet 'const'.
  2940. // FIXME: This doesn't do quite the right thing for const subobjects of the
  2941. // object under construction.
  2942. if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
  2943. LVal.getLValueCallIndex(),
  2944. LVal.getLValueVersion())) {
  2945. BaseType = Info.Ctx.getCanonicalType(BaseType);
  2946. BaseType.removeLocalConst();
  2947. LifetimeStartedInEvaluation = true;
  2948. }
  2949. // In C++14, we can't safely access any mutable state when we might be
  2950. // evaluating after an unmodeled side effect.
  2951. //
  2952. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2953. // to be read here (but take care with 'mutable' fields).
  2954. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  2955. Info.EvalStatus.HasSideEffects) ||
  2956. (AK != AK_Read && Info.IsSpeculativelyEvaluating))
  2957. return CompleteObject();
  2958. return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
  2959. }
  2960. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2961. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2962. /// glvalue referred to by an entity of reference type.
  2963. ///
  2964. /// \param Info - Information about the ongoing evaluation.
  2965. /// \param Conv - The expression for which we are performing the conversion.
  2966. /// Used for diagnostics.
  2967. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  2968. /// case of a non-class type).
  2969. /// \param LVal - The glvalue on which we are attempting to perform this action.
  2970. /// \param RVal - The produced value will be placed here.
  2971. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2972. QualType Type,
  2973. const LValue &LVal, APValue &RVal) {
  2974. if (LVal.Designator.Invalid)
  2975. return false;
  2976. // Check for special cases where there is no existing APValue to look at.
  2977. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2978. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  2979. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  2980. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  2981. // initializer until now for such expressions. Such an expression can't be
  2982. // an ICE in C, so this only matters for fold.
  2983. if (Type.isVolatileQualified()) {
  2984. Info.FFDiag(Conv);
  2985. return false;
  2986. }
  2987. APValue Lit;
  2988. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  2989. return false;
  2990. CompleteObject LitObj(&Lit, Base->getType(), false);
  2991. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  2992. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  2993. // We represent a string literal array as an lvalue pointing at the
  2994. // corresponding expression, rather than building an array of chars.
  2995. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  2996. APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  2997. CompleteObject StrObj(&Str, Base->getType(), false);
  2998. return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
  2999. }
  3000. }
  3001. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  3002. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  3003. }
  3004. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3005. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3006. QualType LValType, APValue &Val) {
  3007. if (LVal.Designator.Invalid)
  3008. return false;
  3009. if (!Info.getLangOpts().CPlusPlus14) {
  3010. Info.FFDiag(E);
  3011. return false;
  3012. }
  3013. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3014. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3015. }
  3016. namespace {
  3017. struct CompoundAssignSubobjectHandler {
  3018. EvalInfo &Info;
  3019. const Expr *E;
  3020. QualType PromotedLHSType;
  3021. BinaryOperatorKind Opcode;
  3022. const APValue &RHS;
  3023. static const AccessKinds AccessKind = AK_Assign;
  3024. typedef bool result_type;
  3025. bool checkConst(QualType QT) {
  3026. // Assigning to a const object has undefined behavior.
  3027. if (QT.isConstQualified()) {
  3028. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3029. return false;
  3030. }
  3031. return true;
  3032. }
  3033. bool failed() { return false; }
  3034. bool found(APValue &Subobj, QualType SubobjType) {
  3035. switch (Subobj.getKind()) {
  3036. case APValue::Int:
  3037. return found(Subobj.getInt(), SubobjType);
  3038. case APValue::Float:
  3039. return found(Subobj.getFloat(), SubobjType);
  3040. case APValue::ComplexInt:
  3041. case APValue::ComplexFloat:
  3042. // FIXME: Implement complex compound assignment.
  3043. Info.FFDiag(E);
  3044. return false;
  3045. case APValue::LValue:
  3046. return foundPointer(Subobj, SubobjType);
  3047. default:
  3048. // FIXME: can this happen?
  3049. Info.FFDiag(E);
  3050. return false;
  3051. }
  3052. }
  3053. bool found(APSInt &Value, QualType SubobjType) {
  3054. if (!checkConst(SubobjType))
  3055. return false;
  3056. if (!SubobjType->isIntegerType() || !RHS.isInt()) {
  3057. // We don't support compound assignment on integer-cast-to-pointer
  3058. // values.
  3059. Info.FFDiag(E);
  3060. return false;
  3061. }
  3062. APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
  3063. SubobjType, Value);
  3064. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3065. return false;
  3066. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3067. return true;
  3068. }
  3069. bool found(APFloat &Value, QualType SubobjType) {
  3070. return checkConst(SubobjType) &&
  3071. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3072. Value) &&
  3073. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3074. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3075. }
  3076. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3077. if (!checkConst(SubobjType))
  3078. return false;
  3079. QualType PointeeType;
  3080. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3081. PointeeType = PT->getPointeeType();
  3082. if (PointeeType.isNull() || !RHS.isInt() ||
  3083. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3084. Info.FFDiag(E);
  3085. return false;
  3086. }
  3087. APSInt Offset = RHS.getInt();
  3088. if (Opcode == BO_Sub)
  3089. negateAsSigned(Offset);
  3090. LValue LVal;
  3091. LVal.setFrom(Info.Ctx, Subobj);
  3092. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3093. return false;
  3094. LVal.moveInto(Subobj);
  3095. return true;
  3096. }
  3097. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3098. llvm_unreachable("shouldn't encounter string elements here");
  3099. }
  3100. };
  3101. } // end anonymous namespace
  3102. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3103. /// Perform a compound assignment of LVal <op>= RVal.
  3104. static bool handleCompoundAssignment(
  3105. EvalInfo &Info, const Expr *E,
  3106. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3107. BinaryOperatorKind Opcode, const APValue &RVal) {
  3108. if (LVal.Designator.Invalid)
  3109. return false;
  3110. if (!Info.getLangOpts().CPlusPlus14) {
  3111. Info.FFDiag(E);
  3112. return false;
  3113. }
  3114. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3115. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3116. RVal };
  3117. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3118. }
  3119. namespace {
  3120. struct IncDecSubobjectHandler {
  3121. EvalInfo &Info;
  3122. const UnaryOperator *E;
  3123. AccessKinds AccessKind;
  3124. APValue *Old;
  3125. typedef bool result_type;
  3126. bool checkConst(QualType QT) {
  3127. // Assigning to a const object has undefined behavior.
  3128. if (QT.isConstQualified()) {
  3129. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3130. return false;
  3131. }
  3132. return true;
  3133. }
  3134. bool failed() { return false; }
  3135. bool found(APValue &Subobj, QualType SubobjType) {
  3136. // Stash the old value. Also clear Old, so we don't clobber it later
  3137. // if we're post-incrementing a complex.
  3138. if (Old) {
  3139. *Old = Subobj;
  3140. Old = nullptr;
  3141. }
  3142. switch (Subobj.getKind()) {
  3143. case APValue::Int:
  3144. return found(Subobj.getInt(), SubobjType);
  3145. case APValue::Float:
  3146. return found(Subobj.getFloat(), SubobjType);
  3147. case APValue::ComplexInt:
  3148. return found(Subobj.getComplexIntReal(),
  3149. SubobjType->castAs<ComplexType>()->getElementType()
  3150. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3151. case APValue::ComplexFloat:
  3152. return found(Subobj.getComplexFloatReal(),
  3153. SubobjType->castAs<ComplexType>()->getElementType()
  3154. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3155. case APValue::LValue:
  3156. return foundPointer(Subobj, SubobjType);
  3157. default:
  3158. // FIXME: can this happen?
  3159. Info.FFDiag(E);
  3160. return false;
  3161. }
  3162. }
  3163. bool found(APSInt &Value, QualType SubobjType) {
  3164. if (!checkConst(SubobjType))
  3165. return false;
  3166. if (!SubobjType->isIntegerType()) {
  3167. // We don't support increment / decrement on integer-cast-to-pointer
  3168. // values.
  3169. Info.FFDiag(E);
  3170. return false;
  3171. }
  3172. if (Old) *Old = APValue(Value);
  3173. // bool arithmetic promotes to int, and the conversion back to bool
  3174. // doesn't reduce mod 2^n, so special-case it.
  3175. if (SubobjType->isBooleanType()) {
  3176. if (AccessKind == AK_Increment)
  3177. Value = 1;
  3178. else
  3179. Value = !Value;
  3180. return true;
  3181. }
  3182. bool WasNegative = Value.isNegative();
  3183. if (AccessKind == AK_Increment) {
  3184. ++Value;
  3185. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3186. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3187. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3188. }
  3189. } else {
  3190. --Value;
  3191. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3192. unsigned BitWidth = Value.getBitWidth();
  3193. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3194. ActualValue.setBit(BitWidth);
  3195. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3196. }
  3197. }
  3198. return true;
  3199. }
  3200. bool found(APFloat &Value, QualType SubobjType) {
  3201. if (!checkConst(SubobjType))
  3202. return false;
  3203. if (Old) *Old = APValue(Value);
  3204. APFloat One(Value.getSemantics(), 1);
  3205. if (AccessKind == AK_Increment)
  3206. Value.add(One, APFloat::rmNearestTiesToEven);
  3207. else
  3208. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3209. return true;
  3210. }
  3211. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3212. if (!checkConst(SubobjType))
  3213. return false;
  3214. QualType PointeeType;
  3215. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3216. PointeeType = PT->getPointeeType();
  3217. else {
  3218. Info.FFDiag(E);
  3219. return false;
  3220. }
  3221. LValue LVal;
  3222. LVal.setFrom(Info.Ctx, Subobj);
  3223. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3224. AccessKind == AK_Increment ? 1 : -1))
  3225. return false;
  3226. LVal.moveInto(Subobj);
  3227. return true;
  3228. }
  3229. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3230. llvm_unreachable("shouldn't encounter string elements here");
  3231. }
  3232. };
  3233. } // end anonymous namespace
  3234. /// Perform an increment or decrement on LVal.
  3235. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3236. QualType LValType, bool IsIncrement, APValue *Old) {
  3237. if (LVal.Designator.Invalid)
  3238. return false;
  3239. if (!Info.getLangOpts().CPlusPlus14) {
  3240. Info.FFDiag(E);
  3241. return false;
  3242. }
  3243. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3244. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3245. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3246. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3247. }
  3248. /// Build an lvalue for the object argument of a member function call.
  3249. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3250. LValue &This) {
  3251. if (Object->getType()->isPointerType())
  3252. return EvaluatePointer(Object, This, Info);
  3253. if (Object->isGLValue())
  3254. return EvaluateLValue(Object, This, Info);
  3255. if (Object->getType()->isLiteralType(Info.Ctx))
  3256. return EvaluateTemporary(Object, This, Info);
  3257. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3258. return false;
  3259. }
  3260. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3261. /// lvalue referring to the result.
  3262. ///
  3263. /// \param Info - Information about the ongoing evaluation.
  3264. /// \param LV - An lvalue referring to the base of the member pointer.
  3265. /// \param RHS - The member pointer expression.
  3266. /// \param IncludeMember - Specifies whether the member itself is included in
  3267. /// the resulting LValue subobject designator. This is not possible when
  3268. /// creating a bound member function.
  3269. /// \return The field or method declaration to which the member pointer refers,
  3270. /// or 0 if evaluation fails.
  3271. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3272. QualType LVType,
  3273. LValue &LV,
  3274. const Expr *RHS,
  3275. bool IncludeMember = true) {
  3276. MemberPtr MemPtr;
  3277. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3278. return nullptr;
  3279. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3280. // member value, the behavior is undefined.
  3281. if (!MemPtr.getDecl()) {
  3282. // FIXME: Specific diagnostic.
  3283. Info.FFDiag(RHS);
  3284. return nullptr;
  3285. }
  3286. if (MemPtr.isDerivedMember()) {
  3287. // This is a member of some derived class. Truncate LV appropriately.
  3288. // The end of the derived-to-base path for the base object must match the
  3289. // derived-to-base path for the member pointer.
  3290. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3291. LV.Designator.Entries.size()) {
  3292. Info.FFDiag(RHS);
  3293. return nullptr;
  3294. }
  3295. unsigned PathLengthToMember =
  3296. LV.Designator.Entries.size() - MemPtr.Path.size();
  3297. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3298. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3299. LV.Designator.Entries[PathLengthToMember + I]);
  3300. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3301. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3302. Info.FFDiag(RHS);
  3303. return nullptr;
  3304. }
  3305. }
  3306. // Truncate the lvalue to the appropriate derived class.
  3307. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3308. PathLengthToMember))
  3309. return nullptr;
  3310. } else if (!MemPtr.Path.empty()) {
  3311. // Extend the LValue path with the member pointer's path.
  3312. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3313. MemPtr.Path.size() + IncludeMember);
  3314. // Walk down to the appropriate base class.
  3315. if (const PointerType *PT = LVType->getAs<PointerType>())
  3316. LVType = PT->getPointeeType();
  3317. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3318. assert(RD && "member pointer access on non-class-type expression");
  3319. // The first class in the path is that of the lvalue.
  3320. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3321. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3322. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3323. return nullptr;
  3324. RD = Base;
  3325. }
  3326. // Finally cast to the class containing the member.
  3327. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3328. MemPtr.getContainingRecord()))
  3329. return nullptr;
  3330. }
  3331. // Add the member. Note that we cannot build bound member functions here.
  3332. if (IncludeMember) {
  3333. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3334. if (!HandleLValueMember(Info, RHS, LV, FD))
  3335. return nullptr;
  3336. } else if (const IndirectFieldDecl *IFD =
  3337. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3338. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3339. return nullptr;
  3340. } else {
  3341. llvm_unreachable("can't construct reference to bound member function");
  3342. }
  3343. }
  3344. return MemPtr.getDecl();
  3345. }
  3346. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3347. const BinaryOperator *BO,
  3348. LValue &LV,
  3349. bool IncludeMember = true) {
  3350. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3351. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3352. if (Info.noteFailure()) {
  3353. MemberPtr MemPtr;
  3354. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3355. }
  3356. return nullptr;
  3357. }
  3358. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3359. BO->getRHS(), IncludeMember);
  3360. }
  3361. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3362. /// the provided lvalue, which currently refers to the base object.
  3363. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3364. LValue &Result) {
  3365. SubobjectDesignator &D = Result.Designator;
  3366. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3367. return false;
  3368. QualType TargetQT = E->getType();
  3369. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3370. TargetQT = PT->getPointeeType();
  3371. // Check this cast lands within the final derived-to-base subobject path.
  3372. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3373. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3374. << D.MostDerivedType << TargetQT;
  3375. return false;
  3376. }
  3377. // Check the type of the final cast. We don't need to check the path,
  3378. // since a cast can only be formed if the path is unique.
  3379. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3380. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3381. const CXXRecordDecl *FinalType;
  3382. if (NewEntriesSize == D.MostDerivedPathLength)
  3383. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3384. else
  3385. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3386. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3387. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3388. << D.MostDerivedType << TargetQT;
  3389. return false;
  3390. }
  3391. // Truncate the lvalue to the appropriate derived class.
  3392. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3393. }
  3394. namespace {
  3395. enum EvalStmtResult {
  3396. /// Evaluation failed.
  3397. ESR_Failed,
  3398. /// Hit a 'return' statement.
  3399. ESR_Returned,
  3400. /// Evaluation succeeded.
  3401. ESR_Succeeded,
  3402. /// Hit a 'continue' statement.
  3403. ESR_Continue,
  3404. /// Hit a 'break' statement.
  3405. ESR_Break,
  3406. /// Still scanning for 'case' or 'default' statement.
  3407. ESR_CaseNotFound
  3408. };
  3409. }
  3410. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3411. // We don't need to evaluate the initializer for a static local.
  3412. if (!VD->hasLocalStorage())
  3413. return true;
  3414. LValue Result;
  3415. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3416. const Expr *InitE = VD->getInit();
  3417. if (!InitE) {
  3418. Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
  3419. << false << VD->getType();
  3420. Val = APValue();
  3421. return false;
  3422. }
  3423. if (InitE->isValueDependent())
  3424. return false;
  3425. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3426. // Wipe out any partially-computed value, to allow tracking that this
  3427. // evaluation failed.
  3428. Val = APValue();
  3429. return false;
  3430. }
  3431. return true;
  3432. }
  3433. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3434. bool OK = true;
  3435. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3436. OK &= EvaluateVarDecl(Info, VD);
  3437. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3438. for (auto *BD : DD->bindings())
  3439. if (auto *VD = BD->getHoldingVar())
  3440. OK &= EvaluateDecl(Info, VD);
  3441. return OK;
  3442. }
  3443. /// Evaluate a condition (either a variable declaration or an expression).
  3444. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3445. const Expr *Cond, bool &Result) {
  3446. FullExpressionRAII Scope(Info);
  3447. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3448. return false;
  3449. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3450. }
  3451. namespace {
  3452. /// A location where the result (returned value) of evaluating a
  3453. /// statement should be stored.
  3454. struct StmtResult {
  3455. /// The APValue that should be filled in with the returned value.
  3456. APValue &Value;
  3457. /// The location containing the result, if any (used to support RVO).
  3458. const LValue *Slot;
  3459. };
  3460. struct TempVersionRAII {
  3461. CallStackFrame &Frame;
  3462. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3463. Frame.pushTempVersion();
  3464. }
  3465. ~TempVersionRAII() {
  3466. Frame.popTempVersion();
  3467. }
  3468. };
  3469. }
  3470. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3471. const Stmt *S,
  3472. const SwitchCase *SC = nullptr);
  3473. /// Evaluate the body of a loop, and translate the result as appropriate.
  3474. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3475. const Stmt *Body,
  3476. const SwitchCase *Case = nullptr) {
  3477. BlockScopeRAII Scope(Info);
  3478. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3479. case ESR_Break:
  3480. return ESR_Succeeded;
  3481. case ESR_Succeeded:
  3482. case ESR_Continue:
  3483. return ESR_Continue;
  3484. case ESR_Failed:
  3485. case ESR_Returned:
  3486. case ESR_CaseNotFound:
  3487. return ESR;
  3488. }
  3489. llvm_unreachable("Invalid EvalStmtResult!");
  3490. }
  3491. /// Evaluate a switch statement.
  3492. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3493. const SwitchStmt *SS) {
  3494. BlockScopeRAII Scope(Info);
  3495. // Evaluate the switch condition.
  3496. APSInt Value;
  3497. {
  3498. FullExpressionRAII Scope(Info);
  3499. if (const Stmt *Init = SS->getInit()) {
  3500. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3501. if (ESR != ESR_Succeeded)
  3502. return ESR;
  3503. }
  3504. if (SS->getConditionVariable() &&
  3505. !EvaluateDecl(Info, SS->getConditionVariable()))
  3506. return ESR_Failed;
  3507. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3508. return ESR_Failed;
  3509. }
  3510. // Find the switch case corresponding to the value of the condition.
  3511. // FIXME: Cache this lookup.
  3512. const SwitchCase *Found = nullptr;
  3513. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3514. SC = SC->getNextSwitchCase()) {
  3515. if (isa<DefaultStmt>(SC)) {
  3516. Found = SC;
  3517. continue;
  3518. }
  3519. const CaseStmt *CS = cast<CaseStmt>(SC);
  3520. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3521. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3522. : LHS;
  3523. if (LHS <= Value && Value <= RHS) {
  3524. Found = SC;
  3525. break;
  3526. }
  3527. }
  3528. if (!Found)
  3529. return ESR_Succeeded;
  3530. // Search the switch body for the switch case and evaluate it from there.
  3531. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3532. case ESR_Break:
  3533. return ESR_Succeeded;
  3534. case ESR_Succeeded:
  3535. case ESR_Continue:
  3536. case ESR_Failed:
  3537. case ESR_Returned:
  3538. return ESR;
  3539. case ESR_CaseNotFound:
  3540. // This can only happen if the switch case is nested within a statement
  3541. // expression. We have no intention of supporting that.
  3542. Info.FFDiag(Found->getBeginLoc(),
  3543. diag::note_constexpr_stmt_expr_unsupported);
  3544. return ESR_Failed;
  3545. }
  3546. llvm_unreachable("Invalid EvalStmtResult!");
  3547. }
  3548. // Evaluate a statement.
  3549. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3550. const Stmt *S, const SwitchCase *Case) {
  3551. if (!Info.nextStep(S))
  3552. return ESR_Failed;
  3553. // If we're hunting down a 'case' or 'default' label, recurse through
  3554. // substatements until we hit the label.
  3555. if (Case) {
  3556. // FIXME: We don't start the lifetime of objects whose initialization we
  3557. // jump over. However, such objects must be of class type with a trivial
  3558. // default constructor that initialize all subobjects, so must be empty,
  3559. // so this almost never matters.
  3560. switch (S->getStmtClass()) {
  3561. case Stmt::CompoundStmtClass:
  3562. // FIXME: Precompute which substatement of a compound statement we
  3563. // would jump to, and go straight there rather than performing a
  3564. // linear scan each time.
  3565. case Stmt::LabelStmtClass:
  3566. case Stmt::AttributedStmtClass:
  3567. case Stmt::DoStmtClass:
  3568. break;
  3569. case Stmt::CaseStmtClass:
  3570. case Stmt::DefaultStmtClass:
  3571. if (Case == S)
  3572. Case = nullptr;
  3573. break;
  3574. case Stmt::IfStmtClass: {
  3575. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3576. // straight there rather than scanning both sides.
  3577. const IfStmt *IS = cast<IfStmt>(S);
  3578. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3579. // preceded by our switch label.
  3580. BlockScopeRAII Scope(Info);
  3581. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3582. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3583. return ESR;
  3584. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3585. }
  3586. case Stmt::WhileStmtClass: {
  3587. EvalStmtResult ESR =
  3588. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3589. if (ESR != ESR_Continue)
  3590. return ESR;
  3591. break;
  3592. }
  3593. case Stmt::ForStmtClass: {
  3594. const ForStmt *FS = cast<ForStmt>(S);
  3595. EvalStmtResult ESR =
  3596. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3597. if (ESR != ESR_Continue)
  3598. return ESR;
  3599. if (FS->getInc()) {
  3600. FullExpressionRAII IncScope(Info);
  3601. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3602. return ESR_Failed;
  3603. }
  3604. break;
  3605. }
  3606. case Stmt::DeclStmtClass:
  3607. // FIXME: If the variable has initialization that can't be jumped over,
  3608. // bail out of any immediately-surrounding compound-statement too.
  3609. default:
  3610. return ESR_CaseNotFound;
  3611. }
  3612. }
  3613. switch (S->getStmtClass()) {
  3614. default:
  3615. if (const Expr *E = dyn_cast<Expr>(S)) {
  3616. // Don't bother evaluating beyond an expression-statement which couldn't
  3617. // be evaluated.
  3618. FullExpressionRAII Scope(Info);
  3619. if (!EvaluateIgnoredValue(Info, E))
  3620. return ESR_Failed;
  3621. return ESR_Succeeded;
  3622. }
  3623. Info.FFDiag(S->getBeginLoc());
  3624. return ESR_Failed;
  3625. case Stmt::NullStmtClass:
  3626. return ESR_Succeeded;
  3627. case Stmt::DeclStmtClass: {
  3628. const DeclStmt *DS = cast<DeclStmt>(S);
  3629. for (const auto *DclIt : DS->decls()) {
  3630. // Each declaration initialization is its own full-expression.
  3631. // FIXME: This isn't quite right; if we're performing aggregate
  3632. // initialization, each braced subexpression is its own full-expression.
  3633. FullExpressionRAII Scope(Info);
  3634. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3635. return ESR_Failed;
  3636. }
  3637. return ESR_Succeeded;
  3638. }
  3639. case Stmt::ReturnStmtClass: {
  3640. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3641. FullExpressionRAII Scope(Info);
  3642. if (RetExpr &&
  3643. !(Result.Slot
  3644. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3645. : Evaluate(Result.Value, Info, RetExpr)))
  3646. return ESR_Failed;
  3647. return ESR_Returned;
  3648. }
  3649. case Stmt::CompoundStmtClass: {
  3650. BlockScopeRAII Scope(Info);
  3651. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3652. for (const auto *BI : CS->body()) {
  3653. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3654. if (ESR == ESR_Succeeded)
  3655. Case = nullptr;
  3656. else if (ESR != ESR_CaseNotFound)
  3657. return ESR;
  3658. }
  3659. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3660. }
  3661. case Stmt::IfStmtClass: {
  3662. const IfStmt *IS = cast<IfStmt>(S);
  3663. // Evaluate the condition, as either a var decl or as an expression.
  3664. BlockScopeRAII Scope(Info);
  3665. if (const Stmt *Init = IS->getInit()) {
  3666. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3667. if (ESR != ESR_Succeeded)
  3668. return ESR;
  3669. }
  3670. bool Cond;
  3671. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3672. return ESR_Failed;
  3673. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3674. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3675. if (ESR != ESR_Succeeded)
  3676. return ESR;
  3677. }
  3678. return ESR_Succeeded;
  3679. }
  3680. case Stmt::WhileStmtClass: {
  3681. const WhileStmt *WS = cast<WhileStmt>(S);
  3682. while (true) {
  3683. BlockScopeRAII Scope(Info);
  3684. bool Continue;
  3685. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3686. Continue))
  3687. return ESR_Failed;
  3688. if (!Continue)
  3689. break;
  3690. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3691. if (ESR != ESR_Continue)
  3692. return ESR;
  3693. }
  3694. return ESR_Succeeded;
  3695. }
  3696. case Stmt::DoStmtClass: {
  3697. const DoStmt *DS = cast<DoStmt>(S);
  3698. bool Continue;
  3699. do {
  3700. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3701. if (ESR != ESR_Continue)
  3702. return ESR;
  3703. Case = nullptr;
  3704. FullExpressionRAII CondScope(Info);
  3705. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3706. return ESR_Failed;
  3707. } while (Continue);
  3708. return ESR_Succeeded;
  3709. }
  3710. case Stmt::ForStmtClass: {
  3711. const ForStmt *FS = cast<ForStmt>(S);
  3712. BlockScopeRAII Scope(Info);
  3713. if (FS->getInit()) {
  3714. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3715. if (ESR != ESR_Succeeded)
  3716. return ESR;
  3717. }
  3718. while (true) {
  3719. BlockScopeRAII Scope(Info);
  3720. bool Continue = true;
  3721. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3722. FS->getCond(), Continue))
  3723. return ESR_Failed;
  3724. if (!Continue)
  3725. break;
  3726. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3727. if (ESR != ESR_Continue)
  3728. return ESR;
  3729. if (FS->getInc()) {
  3730. FullExpressionRAII IncScope(Info);
  3731. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3732. return ESR_Failed;
  3733. }
  3734. }
  3735. return ESR_Succeeded;
  3736. }
  3737. case Stmt::CXXForRangeStmtClass: {
  3738. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3739. BlockScopeRAII Scope(Info);
  3740. // Evaluate the init-statement if present.
  3741. if (FS->getInit()) {
  3742. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3743. if (ESR != ESR_Succeeded)
  3744. return ESR;
  3745. }
  3746. // Initialize the __range variable.
  3747. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3748. if (ESR != ESR_Succeeded)
  3749. return ESR;
  3750. // Create the __begin and __end iterators.
  3751. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3752. if (ESR != ESR_Succeeded)
  3753. return ESR;
  3754. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3755. if (ESR != ESR_Succeeded)
  3756. return ESR;
  3757. while (true) {
  3758. // Condition: __begin != __end.
  3759. {
  3760. bool Continue = true;
  3761. FullExpressionRAII CondExpr(Info);
  3762. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3763. return ESR_Failed;
  3764. if (!Continue)
  3765. break;
  3766. }
  3767. // User's variable declaration, initialized by *__begin.
  3768. BlockScopeRAII InnerScope(Info);
  3769. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3770. if (ESR != ESR_Succeeded)
  3771. return ESR;
  3772. // Loop body.
  3773. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3774. if (ESR != ESR_Continue)
  3775. return ESR;
  3776. // Increment: ++__begin
  3777. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3778. return ESR_Failed;
  3779. }
  3780. return ESR_Succeeded;
  3781. }
  3782. case Stmt::SwitchStmtClass:
  3783. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3784. case Stmt::ContinueStmtClass:
  3785. return ESR_Continue;
  3786. case Stmt::BreakStmtClass:
  3787. return ESR_Break;
  3788. case Stmt::LabelStmtClass:
  3789. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3790. case Stmt::AttributedStmtClass:
  3791. // As a general principle, C++11 attributes can be ignored without
  3792. // any semantic impact.
  3793. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3794. Case);
  3795. case Stmt::CaseStmtClass:
  3796. case Stmt::DefaultStmtClass:
  3797. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3798. }
  3799. }
  3800. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3801. /// default constructor. If so, we'll fold it whether or not it's marked as
  3802. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3803. /// so we need special handling.
  3804. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3805. const CXXConstructorDecl *CD,
  3806. bool IsValueInitialization) {
  3807. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3808. return false;
  3809. // Value-initialization does not call a trivial default constructor, so such a
  3810. // call is a core constant expression whether or not the constructor is
  3811. // constexpr.
  3812. if (!CD->isConstexpr() && !IsValueInitialization) {
  3813. if (Info.getLangOpts().CPlusPlus11) {
  3814. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3815. // we should be much more explicit about why it's not constexpr.
  3816. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3817. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3818. Info.Note(CD->getLocation(), diag::note_declared_at);
  3819. } else {
  3820. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3821. }
  3822. }
  3823. return true;
  3824. }
  3825. /// CheckConstexprFunction - Check that a function can be called in a constant
  3826. /// expression.
  3827. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3828. const FunctionDecl *Declaration,
  3829. const FunctionDecl *Definition,
  3830. const Stmt *Body) {
  3831. // Potential constant expressions can contain calls to declared, but not yet
  3832. // defined, constexpr functions.
  3833. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3834. Declaration->isConstexpr())
  3835. return false;
  3836. // Bail out if the function declaration itself is invalid. We will
  3837. // have produced a relevant diagnostic while parsing it, so just
  3838. // note the problematic sub-expression.
  3839. if (Declaration->isInvalidDecl()) {
  3840. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3841. return false;
  3842. }
  3843. // Can we evaluate this function call?
  3844. if (Definition && Definition->isConstexpr() &&
  3845. !Definition->isInvalidDecl() && Body)
  3846. return true;
  3847. if (Info.getLangOpts().CPlusPlus11) {
  3848. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3849. // If this function is not constexpr because it is an inherited
  3850. // non-constexpr constructor, diagnose that directly.
  3851. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  3852. if (CD && CD->isInheritingConstructor()) {
  3853. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  3854. if (!Inherited->isConstexpr())
  3855. DiagDecl = CD = Inherited;
  3856. }
  3857. // FIXME: If DiagDecl is an implicitly-declared special member function
  3858. // or an inheriting constructor, we should be much more explicit about why
  3859. // it's not constexpr.
  3860. if (CD && CD->isInheritingConstructor())
  3861. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  3862. << CD->getInheritedConstructor().getConstructor()->getParent();
  3863. else
  3864. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3865. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  3866. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3867. } else {
  3868. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3869. }
  3870. return false;
  3871. }
  3872. /// Determine if a class has any fields that might need to be copied by a
  3873. /// trivial copy or move operation.
  3874. static bool hasFields(const CXXRecordDecl *RD) {
  3875. if (!RD || RD->isEmpty())
  3876. return false;
  3877. for (auto *FD : RD->fields()) {
  3878. if (FD->isUnnamedBitfield())
  3879. continue;
  3880. return true;
  3881. }
  3882. for (auto &Base : RD->bases())
  3883. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  3884. return true;
  3885. return false;
  3886. }
  3887. namespace {
  3888. typedef SmallVector<APValue, 8> ArgVector;
  3889. }
  3890. /// EvaluateArgs - Evaluate the arguments to a function call.
  3891. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  3892. EvalInfo &Info) {
  3893. bool Success = true;
  3894. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  3895. I != E; ++I) {
  3896. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  3897. // If we're checking for a potential constant expression, evaluate all
  3898. // initializers even if some of them fail.
  3899. if (!Info.noteFailure())
  3900. return false;
  3901. Success = false;
  3902. }
  3903. }
  3904. return Success;
  3905. }
  3906. /// Evaluate a function call.
  3907. static bool HandleFunctionCall(SourceLocation CallLoc,
  3908. const FunctionDecl *Callee, const LValue *This,
  3909. ArrayRef<const Expr*> Args, const Stmt *Body,
  3910. EvalInfo &Info, APValue &Result,
  3911. const LValue *ResultSlot) {
  3912. ArgVector ArgValues(Args.size());
  3913. if (!EvaluateArgs(Args, ArgValues, Info))
  3914. return false;
  3915. if (!Info.CheckCallLimit(CallLoc))
  3916. return false;
  3917. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  3918. // For a trivial copy or move assignment, perform an APValue copy. This is
  3919. // essential for unions, where the operations performed by the assignment
  3920. // operator cannot be represented as statements.
  3921. //
  3922. // Skip this for non-union classes with no fields; in that case, the defaulted
  3923. // copy/move does not actually read the object.
  3924. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  3925. if (MD && MD->isDefaulted() &&
  3926. (MD->getParent()->isUnion() ||
  3927. (MD->isTrivial() && hasFields(MD->getParent())))) {
  3928. assert(This &&
  3929. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  3930. LValue RHS;
  3931. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3932. APValue RHSValue;
  3933. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3934. RHS, RHSValue))
  3935. return false;
  3936. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
  3937. RHSValue))
  3938. return false;
  3939. This->moveInto(Result);
  3940. return true;
  3941. } else if (MD && isLambdaCallOperator(MD)) {
  3942. // We're in a lambda; determine the lambda capture field maps unless we're
  3943. // just constexpr checking a lambda's call operator. constexpr checking is
  3944. // done before the captures have been added to the closure object (unless
  3945. // we're inferring constexpr-ness), so we don't have access to them in this
  3946. // case. But since we don't need the captures to constexpr check, we can
  3947. // just ignore them.
  3948. if (!Info.checkingPotentialConstantExpression())
  3949. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  3950. Frame.LambdaThisCaptureField);
  3951. }
  3952. StmtResult Ret = {Result, ResultSlot};
  3953. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  3954. if (ESR == ESR_Succeeded) {
  3955. if (Callee->getReturnType()->isVoidType())
  3956. return true;
  3957. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  3958. }
  3959. return ESR == ESR_Returned;
  3960. }
  3961. /// Evaluate a constructor call.
  3962. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  3963. APValue *ArgValues,
  3964. const CXXConstructorDecl *Definition,
  3965. EvalInfo &Info, APValue &Result) {
  3966. SourceLocation CallLoc = E->getExprLoc();
  3967. if (!Info.CheckCallLimit(CallLoc))
  3968. return false;
  3969. const CXXRecordDecl *RD = Definition->getParent();
  3970. if (RD->getNumVBases()) {
  3971. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  3972. return false;
  3973. }
  3974. EvalInfo::EvaluatingConstructorRAII EvalObj(
  3975. Info, {This.getLValueBase(),
  3976. {This.getLValueCallIndex(), This.getLValueVersion()}});
  3977. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  3978. // FIXME: Creating an APValue just to hold a nonexistent return value is
  3979. // wasteful.
  3980. APValue RetVal;
  3981. StmtResult Ret = {RetVal, nullptr};
  3982. // If it's a delegating constructor, delegate.
  3983. if (Definition->isDelegatingConstructor()) {
  3984. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  3985. {
  3986. FullExpressionRAII InitScope(Info);
  3987. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  3988. return false;
  3989. }
  3990. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  3991. }
  3992. // For a trivial copy or move constructor, perform an APValue copy. This is
  3993. // essential for unions (or classes with anonymous union members), where the
  3994. // operations performed by the constructor cannot be represented by
  3995. // ctor-initializers.
  3996. //
  3997. // Skip this for empty non-union classes; we should not perform an
  3998. // lvalue-to-rvalue conversion on them because their copy constructor does not
  3999. // actually read them.
  4000. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4001. (Definition->getParent()->isUnion() ||
  4002. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4003. LValue RHS;
  4004. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4005. return handleLValueToRValueConversion(
  4006. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4007. RHS, Result);
  4008. }
  4009. // Reserve space for the struct members.
  4010. if (!RD->isUnion() && Result.isUninit())
  4011. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4012. std::distance(RD->field_begin(), RD->field_end()));
  4013. if (RD->isInvalidDecl()) return false;
  4014. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4015. // A scope for temporaries lifetime-extended by reference members.
  4016. BlockScopeRAII LifetimeExtendedScope(Info);
  4017. bool Success = true;
  4018. unsigned BasesSeen = 0;
  4019. #ifndef NDEBUG
  4020. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4021. #endif
  4022. for (const auto *I : Definition->inits()) {
  4023. LValue Subobject = This;
  4024. LValue SubobjectParent = This;
  4025. APValue *Value = &Result;
  4026. // Determine the subobject to initialize.
  4027. FieldDecl *FD = nullptr;
  4028. if (I->isBaseInitializer()) {
  4029. QualType BaseType(I->getBaseClass(), 0);
  4030. #ifndef NDEBUG
  4031. // Non-virtual base classes are initialized in the order in the class
  4032. // definition. We have already checked for virtual base classes.
  4033. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4034. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4035. "base class initializers not in expected order");
  4036. ++BaseIt;
  4037. #endif
  4038. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4039. BaseType->getAsCXXRecordDecl(), &Layout))
  4040. return false;
  4041. Value = &Result.getStructBase(BasesSeen++);
  4042. } else if ((FD = I->getMember())) {
  4043. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4044. return false;
  4045. if (RD->isUnion()) {
  4046. Result = APValue(FD);
  4047. Value = &Result.getUnionValue();
  4048. } else {
  4049. Value = &Result.getStructField(FD->getFieldIndex());
  4050. }
  4051. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4052. // Walk the indirect field decl's chain to find the object to initialize,
  4053. // and make sure we've initialized every step along it.
  4054. auto IndirectFieldChain = IFD->chain();
  4055. for (auto *C : IndirectFieldChain) {
  4056. FD = cast<FieldDecl>(C);
  4057. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4058. // Switch the union field if it differs. This happens if we had
  4059. // preceding zero-initialization, and we're now initializing a union
  4060. // subobject other than the first.
  4061. // FIXME: In this case, the values of the other subobjects are
  4062. // specified, since zero-initialization sets all padding bits to zero.
  4063. if (Value->isUninit() ||
  4064. (Value->isUnion() && Value->getUnionField() != FD)) {
  4065. if (CD->isUnion())
  4066. *Value = APValue(FD);
  4067. else
  4068. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4069. std::distance(CD->field_begin(), CD->field_end()));
  4070. }
  4071. // Store Subobject as its parent before updating it for the last element
  4072. // in the chain.
  4073. if (C == IndirectFieldChain.back())
  4074. SubobjectParent = Subobject;
  4075. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4076. return false;
  4077. if (CD->isUnion())
  4078. Value = &Value->getUnionValue();
  4079. else
  4080. Value = &Value->getStructField(FD->getFieldIndex());
  4081. }
  4082. } else {
  4083. llvm_unreachable("unknown base initializer kind");
  4084. }
  4085. // Need to override This for implicit field initializers as in this case
  4086. // This refers to innermost anonymous struct/union containing initializer,
  4087. // not to currently constructed class.
  4088. const Expr *Init = I->getInit();
  4089. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4090. isa<CXXDefaultInitExpr>(Init));
  4091. FullExpressionRAII InitScope(Info);
  4092. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4093. (FD && FD->isBitField() &&
  4094. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4095. // If we're checking for a potential constant expression, evaluate all
  4096. // initializers even if some of them fail.
  4097. if (!Info.noteFailure())
  4098. return false;
  4099. Success = false;
  4100. }
  4101. }
  4102. return Success &&
  4103. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4104. }
  4105. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4106. ArrayRef<const Expr*> Args,
  4107. const CXXConstructorDecl *Definition,
  4108. EvalInfo &Info, APValue &Result) {
  4109. ArgVector ArgValues(Args.size());
  4110. if (!EvaluateArgs(Args, ArgValues, Info))
  4111. return false;
  4112. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4113. Info, Result);
  4114. }
  4115. //===----------------------------------------------------------------------===//
  4116. // Generic Evaluation
  4117. //===----------------------------------------------------------------------===//
  4118. namespace {
  4119. template <class Derived>
  4120. class ExprEvaluatorBase
  4121. : public ConstStmtVisitor<Derived, bool> {
  4122. private:
  4123. Derived &getDerived() { return static_cast<Derived&>(*this); }
  4124. bool DerivedSuccess(const APValue &V, const Expr *E) {
  4125. return getDerived().Success(V, E);
  4126. }
  4127. bool DerivedZeroInitialization(const Expr *E) {
  4128. return getDerived().ZeroInitialization(E);
  4129. }
  4130. // Check whether a conditional operator with a non-constant condition is a
  4131. // potential constant expression. If neither arm is a potential constant
  4132. // expression, then the conditional operator is not either.
  4133. template<typename ConditionalOperator>
  4134. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  4135. assert(Info.checkingPotentialConstantExpression());
  4136. // Speculatively evaluate both arms.
  4137. SmallVector<PartialDiagnosticAt, 8> Diag;
  4138. {
  4139. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4140. StmtVisitorTy::Visit(E->getFalseExpr());
  4141. if (Diag.empty())
  4142. return;
  4143. }
  4144. {
  4145. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4146. Diag.clear();
  4147. StmtVisitorTy::Visit(E->getTrueExpr());
  4148. if (Diag.empty())
  4149. return;
  4150. }
  4151. Error(E, diag::note_constexpr_conditional_never_const);
  4152. }
  4153. template<typename ConditionalOperator>
  4154. bool HandleConditionalOperator(const ConditionalOperator *E) {
  4155. bool BoolResult;
  4156. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  4157. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  4158. CheckPotentialConstantConditional(E);
  4159. return false;
  4160. }
  4161. if (Info.noteFailure()) {
  4162. StmtVisitorTy::Visit(E->getTrueExpr());
  4163. StmtVisitorTy::Visit(E->getFalseExpr());
  4164. }
  4165. return false;
  4166. }
  4167. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  4168. return StmtVisitorTy::Visit(EvalExpr);
  4169. }
  4170. protected:
  4171. EvalInfo &Info;
  4172. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  4173. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  4174. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  4175. return Info.CCEDiag(E, D);
  4176. }
  4177. bool ZeroInitialization(const Expr *E) { return Error(E); }
  4178. public:
  4179. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  4180. EvalInfo &getEvalInfo() { return Info; }
  4181. /// Report an evaluation error. This should only be called when an error is
  4182. /// first discovered. When propagating an error, just return false.
  4183. bool Error(const Expr *E, diag::kind D) {
  4184. Info.FFDiag(E, D);
  4185. return false;
  4186. }
  4187. bool Error(const Expr *E) {
  4188. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  4189. }
  4190. bool VisitStmt(const Stmt *) {
  4191. llvm_unreachable("Expression evaluator should not be called on stmts");
  4192. }
  4193. bool VisitExpr(const Expr *E) {
  4194. return Error(E);
  4195. }
  4196. bool VisitConstantExpr(const ConstantExpr *E)
  4197. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4198. bool VisitParenExpr(const ParenExpr *E)
  4199. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4200. bool VisitUnaryExtension(const UnaryOperator *E)
  4201. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4202. bool VisitUnaryPlus(const UnaryOperator *E)
  4203. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4204. bool VisitChooseExpr(const ChooseExpr *E)
  4205. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  4206. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  4207. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  4208. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  4209. { return StmtVisitorTy::Visit(E->getReplacement()); }
  4210. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  4211. TempVersionRAII RAII(*Info.CurrentCall);
  4212. return StmtVisitorTy::Visit(E->getExpr());
  4213. }
  4214. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  4215. TempVersionRAII RAII(*Info.CurrentCall);
  4216. // The initializer may not have been parsed yet, or might be erroneous.
  4217. if (!E->getExpr())
  4218. return Error(E);
  4219. return StmtVisitorTy::Visit(E->getExpr());
  4220. }
  4221. // We cannot create any objects for which cleanups are required, so there is
  4222. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  4223. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  4224. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4225. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  4226. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  4227. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4228. }
  4229. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  4230. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  4231. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4232. }
  4233. bool VisitBinaryOperator(const BinaryOperator *E) {
  4234. switch (E->getOpcode()) {
  4235. default:
  4236. return Error(E);
  4237. case BO_Comma:
  4238. VisitIgnoredValue(E->getLHS());
  4239. return StmtVisitorTy::Visit(E->getRHS());
  4240. case BO_PtrMemD:
  4241. case BO_PtrMemI: {
  4242. LValue Obj;
  4243. if (!HandleMemberPointerAccess(Info, E, Obj))
  4244. return false;
  4245. APValue Result;
  4246. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  4247. return false;
  4248. return DerivedSuccess(Result, E);
  4249. }
  4250. }
  4251. }
  4252. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  4253. // Evaluate and cache the common expression. We treat it as a temporary,
  4254. // even though it's not quite the same thing.
  4255. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  4256. Info, E->getCommon()))
  4257. return false;
  4258. return HandleConditionalOperator(E);
  4259. }
  4260. bool VisitConditionalOperator(const ConditionalOperator *E) {
  4261. bool IsBcpCall = false;
  4262. // If the condition (ignoring parens) is a __builtin_constant_p call,
  4263. // the result is a constant expression if it can be folded without
  4264. // side-effects. This is an important GNU extension. See GCC PR38377
  4265. // for discussion.
  4266. if (const CallExpr *CallCE =
  4267. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  4268. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  4269. IsBcpCall = true;
  4270. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  4271. // constant expression; we can't check whether it's potentially foldable.
  4272. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  4273. return false;
  4274. FoldConstant Fold(Info, IsBcpCall);
  4275. if (!HandleConditionalOperator(E)) {
  4276. Fold.keepDiagnostics();
  4277. return false;
  4278. }
  4279. return true;
  4280. }
  4281. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  4282. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  4283. return DerivedSuccess(*Value, E);
  4284. const Expr *Source = E->getSourceExpr();
  4285. if (!Source)
  4286. return Error(E);
  4287. if (Source == E) { // sanity checking.
  4288. assert(0 && "OpaqueValueExpr recursively refers to itself");
  4289. return Error(E);
  4290. }
  4291. return StmtVisitorTy::Visit(Source);
  4292. }
  4293. bool VisitCallExpr(const CallExpr *E) {
  4294. APValue Result;
  4295. if (!handleCallExpr(E, Result, nullptr))
  4296. return false;
  4297. return DerivedSuccess(Result, E);
  4298. }
  4299. bool handleCallExpr(const CallExpr *E, APValue &Result,
  4300. const LValue *ResultSlot) {
  4301. const Expr *Callee = E->getCallee()->IgnoreParens();
  4302. QualType CalleeType = Callee->getType();
  4303. const FunctionDecl *FD = nullptr;
  4304. LValue *This = nullptr, ThisVal;
  4305. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4306. bool HasQualifier = false;
  4307. // Extract function decl and 'this' pointer from the callee.
  4308. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  4309. const ValueDecl *Member = nullptr;
  4310. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  4311. // Explicit bound member calls, such as x.f() or p->g();
  4312. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  4313. return false;
  4314. Member = ME->getMemberDecl();
  4315. This = &ThisVal;
  4316. HasQualifier = ME->hasQualifier();
  4317. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  4318. // Indirect bound member calls ('.*' or '->*').
  4319. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  4320. if (!Member) return false;
  4321. This = &ThisVal;
  4322. } else
  4323. return Error(Callee);
  4324. FD = dyn_cast<FunctionDecl>(Member);
  4325. if (!FD)
  4326. return Error(Callee);
  4327. } else if (CalleeType->isFunctionPointerType()) {
  4328. LValue Call;
  4329. if (!EvaluatePointer(Callee, Call, Info))
  4330. return false;
  4331. if (!Call.getLValueOffset().isZero())
  4332. return Error(Callee);
  4333. FD = dyn_cast_or_null<FunctionDecl>(
  4334. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  4335. if (!FD)
  4336. return Error(Callee);
  4337. // Don't call function pointers which have been cast to some other type.
  4338. // Per DR (no number yet), the caller and callee can differ in noexcept.
  4339. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  4340. CalleeType->getPointeeType(), FD->getType())) {
  4341. return Error(E);
  4342. }
  4343. // Overloaded operator calls to member functions are represented as normal
  4344. // calls with '*this' as the first argument.
  4345. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  4346. if (MD && !MD->isStatic()) {
  4347. // FIXME: When selecting an implicit conversion for an overloaded
  4348. // operator delete, we sometimes try to evaluate calls to conversion
  4349. // operators without a 'this' parameter!
  4350. if (Args.empty())
  4351. return Error(E);
  4352. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  4353. return false;
  4354. This = &ThisVal;
  4355. Args = Args.slice(1);
  4356. } else if (MD && MD->isLambdaStaticInvoker()) {
  4357. // Map the static invoker for the lambda back to the call operator.
  4358. // Conveniently, we don't have to slice out the 'this' argument (as is
  4359. // being done for the non-static case), since a static member function
  4360. // doesn't have an implicit argument passed in.
  4361. const CXXRecordDecl *ClosureClass = MD->getParent();
  4362. assert(
  4363. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  4364. "Number of captures must be zero for conversion to function-ptr");
  4365. const CXXMethodDecl *LambdaCallOp =
  4366. ClosureClass->getLambdaCallOperator();
  4367. // Set 'FD', the function that will be called below, to the call
  4368. // operator. If the closure object represents a generic lambda, find
  4369. // the corresponding specialization of the call operator.
  4370. if (ClosureClass->isGenericLambda()) {
  4371. assert(MD->isFunctionTemplateSpecialization() &&
  4372. "A generic lambda's static-invoker function must be a "
  4373. "template specialization");
  4374. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  4375. FunctionTemplateDecl *CallOpTemplate =
  4376. LambdaCallOp->getDescribedFunctionTemplate();
  4377. void *InsertPos = nullptr;
  4378. FunctionDecl *CorrespondingCallOpSpecialization =
  4379. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  4380. assert(CorrespondingCallOpSpecialization &&
  4381. "We must always have a function call operator specialization "
  4382. "that corresponds to our static invoker specialization");
  4383. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  4384. } else
  4385. FD = LambdaCallOp;
  4386. }
  4387. } else
  4388. return Error(E);
  4389. if (This && !This->checkSubobject(Info, E, CSK_This))
  4390. return false;
  4391. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  4392. // calls to such functions in constant expressions.
  4393. if (This && !HasQualifier &&
  4394. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  4395. return Error(E, diag::note_constexpr_virtual_call);
  4396. const FunctionDecl *Definition = nullptr;
  4397. Stmt *Body = FD->getBody(Definition);
  4398. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  4399. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  4400. Result, ResultSlot))
  4401. return false;
  4402. return true;
  4403. }
  4404. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4405. return StmtVisitorTy::Visit(E->getInitializer());
  4406. }
  4407. bool VisitInitListExpr(const InitListExpr *E) {
  4408. if (E->getNumInits() == 0)
  4409. return DerivedZeroInitialization(E);
  4410. if (E->getNumInits() == 1)
  4411. return StmtVisitorTy::Visit(E->getInit(0));
  4412. return Error(E);
  4413. }
  4414. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  4415. return DerivedZeroInitialization(E);
  4416. }
  4417. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  4418. return DerivedZeroInitialization(E);
  4419. }
  4420. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  4421. return DerivedZeroInitialization(E);
  4422. }
  4423. /// A member expression where the object is a prvalue is itself a prvalue.
  4424. bool VisitMemberExpr(const MemberExpr *E) {
  4425. assert(!E->isArrow() && "missing call to bound member function?");
  4426. APValue Val;
  4427. if (!Evaluate(Val, Info, E->getBase()))
  4428. return false;
  4429. QualType BaseTy = E->getBase()->getType();
  4430. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  4431. if (!FD) return Error(E);
  4432. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  4433. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4434. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4435. CompleteObject Obj(&Val, BaseTy, true);
  4436. SubobjectDesignator Designator(BaseTy);
  4437. Designator.addDeclUnchecked(FD);
  4438. APValue Result;
  4439. return extractSubobject(Info, E, Obj, Designator, Result) &&
  4440. DerivedSuccess(Result, E);
  4441. }
  4442. bool VisitCastExpr(const CastExpr *E) {
  4443. switch (E->getCastKind()) {
  4444. default:
  4445. break;
  4446. case CK_AtomicToNonAtomic: {
  4447. APValue AtomicVal;
  4448. // This does not need to be done in place even for class/array types:
  4449. // atomic-to-non-atomic conversion implies copying the object
  4450. // representation.
  4451. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  4452. return false;
  4453. return DerivedSuccess(AtomicVal, E);
  4454. }
  4455. case CK_NoOp:
  4456. case CK_UserDefinedConversion:
  4457. return StmtVisitorTy::Visit(E->getSubExpr());
  4458. case CK_LValueToRValue: {
  4459. LValue LVal;
  4460. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  4461. return false;
  4462. APValue RVal;
  4463. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  4464. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  4465. LVal, RVal))
  4466. return false;
  4467. return DerivedSuccess(RVal, E);
  4468. }
  4469. }
  4470. return Error(E);
  4471. }
  4472. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  4473. return VisitUnaryPostIncDec(UO);
  4474. }
  4475. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  4476. return VisitUnaryPostIncDec(UO);
  4477. }
  4478. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  4479. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4480. return Error(UO);
  4481. LValue LVal;
  4482. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  4483. return false;
  4484. APValue RVal;
  4485. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  4486. UO->isIncrementOp(), &RVal))
  4487. return false;
  4488. return DerivedSuccess(RVal, UO);
  4489. }
  4490. bool VisitStmtExpr(const StmtExpr *E) {
  4491. // We will have checked the full-expressions inside the statement expression
  4492. // when they were completed, and don't need to check them again now.
  4493. if (Info.checkingForOverflow())
  4494. return Error(E);
  4495. BlockScopeRAII Scope(Info);
  4496. const CompoundStmt *CS = E->getSubStmt();
  4497. if (CS->body_empty())
  4498. return true;
  4499. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  4500. BE = CS->body_end();
  4501. /**/; ++BI) {
  4502. if (BI + 1 == BE) {
  4503. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  4504. if (!FinalExpr) {
  4505. Info.FFDiag((*BI)->getBeginLoc(),
  4506. diag::note_constexpr_stmt_expr_unsupported);
  4507. return false;
  4508. }
  4509. return this->Visit(FinalExpr);
  4510. }
  4511. APValue ReturnValue;
  4512. StmtResult Result = { ReturnValue, nullptr };
  4513. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  4514. if (ESR != ESR_Succeeded) {
  4515. // FIXME: If the statement-expression terminated due to 'return',
  4516. // 'break', or 'continue', it would be nice to propagate that to
  4517. // the outer statement evaluation rather than bailing out.
  4518. if (ESR != ESR_Failed)
  4519. Info.FFDiag((*BI)->getBeginLoc(),
  4520. diag::note_constexpr_stmt_expr_unsupported);
  4521. return false;
  4522. }
  4523. }
  4524. llvm_unreachable("Return from function from the loop above.");
  4525. }
  4526. /// Visit a value which is evaluated, but whose value is ignored.
  4527. void VisitIgnoredValue(const Expr *E) {
  4528. EvaluateIgnoredValue(Info, E);
  4529. }
  4530. /// Potentially visit a MemberExpr's base expression.
  4531. void VisitIgnoredBaseExpression(const Expr *E) {
  4532. // While MSVC doesn't evaluate the base expression, it does diagnose the
  4533. // presence of side-effecting behavior.
  4534. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  4535. return;
  4536. VisitIgnoredValue(E);
  4537. }
  4538. };
  4539. } // namespace
  4540. //===----------------------------------------------------------------------===//
  4541. // Common base class for lvalue and temporary evaluation.
  4542. //===----------------------------------------------------------------------===//
  4543. namespace {
  4544. template<class Derived>
  4545. class LValueExprEvaluatorBase
  4546. : public ExprEvaluatorBase<Derived> {
  4547. protected:
  4548. LValue &Result;
  4549. bool InvalidBaseOK;
  4550. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  4551. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  4552. bool Success(APValue::LValueBase B) {
  4553. Result.set(B);
  4554. return true;
  4555. }
  4556. bool evaluatePointer(const Expr *E, LValue &Result) {
  4557. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  4558. }
  4559. public:
  4560. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  4561. : ExprEvaluatorBaseTy(Info), Result(Result),
  4562. InvalidBaseOK(InvalidBaseOK) {}
  4563. bool Success(const APValue &V, const Expr *E) {
  4564. Result.setFrom(this->Info.Ctx, V);
  4565. return true;
  4566. }
  4567. bool VisitMemberExpr(const MemberExpr *E) {
  4568. // Handle non-static data members.
  4569. QualType BaseTy;
  4570. bool EvalOK;
  4571. if (E->isArrow()) {
  4572. EvalOK = evaluatePointer(E->getBase(), Result);
  4573. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  4574. } else if (E->getBase()->isRValue()) {
  4575. assert(E->getBase()->getType()->isRecordType());
  4576. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  4577. BaseTy = E->getBase()->getType();
  4578. } else {
  4579. EvalOK = this->Visit(E->getBase());
  4580. BaseTy = E->getBase()->getType();
  4581. }
  4582. if (!EvalOK) {
  4583. if (!InvalidBaseOK)
  4584. return false;
  4585. Result.setInvalid(E);
  4586. return true;
  4587. }
  4588. const ValueDecl *MD = E->getMemberDecl();
  4589. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  4590. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4591. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4592. (void)BaseTy;
  4593. if (!HandleLValueMember(this->Info, E, Result, FD))
  4594. return false;
  4595. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  4596. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  4597. return false;
  4598. } else
  4599. return this->Error(E);
  4600. if (MD->getType()->isReferenceType()) {
  4601. APValue RefValue;
  4602. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  4603. RefValue))
  4604. return false;
  4605. return Success(RefValue, E);
  4606. }
  4607. return true;
  4608. }
  4609. bool VisitBinaryOperator(const BinaryOperator *E) {
  4610. switch (E->getOpcode()) {
  4611. default:
  4612. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4613. case BO_PtrMemD:
  4614. case BO_PtrMemI:
  4615. return HandleMemberPointerAccess(this->Info, E, Result);
  4616. }
  4617. }
  4618. bool VisitCastExpr(const CastExpr *E) {
  4619. switch (E->getCastKind()) {
  4620. default:
  4621. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4622. case CK_DerivedToBase:
  4623. case CK_UncheckedDerivedToBase:
  4624. if (!this->Visit(E->getSubExpr()))
  4625. return false;
  4626. // Now figure out the necessary offset to add to the base LV to get from
  4627. // the derived class to the base class.
  4628. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  4629. Result);
  4630. }
  4631. }
  4632. };
  4633. }
  4634. //===----------------------------------------------------------------------===//
  4635. // LValue Evaluation
  4636. //
  4637. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  4638. // function designators (in C), decl references to void objects (in C), and
  4639. // temporaries (if building with -Wno-address-of-temporary).
  4640. //
  4641. // LValue evaluation produces values comprising a base expression of one of the
  4642. // following types:
  4643. // - Declarations
  4644. // * VarDecl
  4645. // * FunctionDecl
  4646. // - Literals
  4647. // * CompoundLiteralExpr in C (and in global scope in C++)
  4648. // * StringLiteral
  4649. // * CXXTypeidExpr
  4650. // * PredefinedExpr
  4651. // * ObjCStringLiteralExpr
  4652. // * ObjCEncodeExpr
  4653. // * AddrLabelExpr
  4654. // * BlockExpr
  4655. // * CallExpr for a MakeStringConstant builtin
  4656. // - Locals and temporaries
  4657. // * MaterializeTemporaryExpr
  4658. // * Any Expr, with a CallIndex indicating the function in which the temporary
  4659. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  4660. // from the AST (FIXME).
  4661. // * A MaterializeTemporaryExpr that has static storage duration, with no
  4662. // CallIndex, for a lifetime-extended temporary.
  4663. // plus an offset in bytes.
  4664. //===----------------------------------------------------------------------===//
  4665. namespace {
  4666. class LValueExprEvaluator
  4667. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  4668. public:
  4669. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  4670. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  4671. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  4672. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  4673. bool VisitDeclRefExpr(const DeclRefExpr *E);
  4674. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  4675. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  4676. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  4677. bool VisitMemberExpr(const MemberExpr *E);
  4678. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  4679. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  4680. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  4681. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  4682. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  4683. bool VisitUnaryDeref(const UnaryOperator *E);
  4684. bool VisitUnaryReal(const UnaryOperator *E);
  4685. bool VisitUnaryImag(const UnaryOperator *E);
  4686. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  4687. return VisitUnaryPreIncDec(UO);
  4688. }
  4689. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  4690. return VisitUnaryPreIncDec(UO);
  4691. }
  4692. bool VisitBinAssign(const BinaryOperator *BO);
  4693. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  4694. bool VisitCastExpr(const CastExpr *E) {
  4695. switch (E->getCastKind()) {
  4696. default:
  4697. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4698. case CK_LValueBitCast:
  4699. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4700. if (!Visit(E->getSubExpr()))
  4701. return false;
  4702. Result.Designator.setInvalid();
  4703. return true;
  4704. case CK_BaseToDerived:
  4705. if (!Visit(E->getSubExpr()))
  4706. return false;
  4707. return HandleBaseToDerivedCast(Info, E, Result);
  4708. }
  4709. }
  4710. };
  4711. } // end anonymous namespace
  4712. /// Evaluate an expression as an lvalue. This can be legitimately called on
  4713. /// expressions which are not glvalues, in three cases:
  4714. /// * function designators in C, and
  4715. /// * "extern void" objects
  4716. /// * @selector() expressions in Objective-C
  4717. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  4718. bool InvalidBaseOK) {
  4719. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  4720. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  4721. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  4722. }
  4723. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  4724. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  4725. return Success(FD);
  4726. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  4727. return VisitVarDecl(E, VD);
  4728. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  4729. return Visit(BD->getBinding());
  4730. return Error(E);
  4731. }
  4732. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  4733. // If we are within a lambda's call operator, check whether the 'VD' referred
  4734. // to within 'E' actually represents a lambda-capture that maps to a
  4735. // data-member/field within the closure object, and if so, evaluate to the
  4736. // field or what the field refers to.
  4737. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  4738. isa<DeclRefExpr>(E) &&
  4739. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  4740. // We don't always have a complete capture-map when checking or inferring if
  4741. // the function call operator meets the requirements of a constexpr function
  4742. // - but we don't need to evaluate the captures to determine constexprness
  4743. // (dcl.constexpr C++17).
  4744. if (Info.checkingPotentialConstantExpression())
  4745. return false;
  4746. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  4747. // Start with 'Result' referring to the complete closure object...
  4748. Result = *Info.CurrentCall->This;
  4749. // ... then update it to refer to the field of the closure object
  4750. // that represents the capture.
  4751. if (!HandleLValueMember(Info, E, Result, FD))
  4752. return false;
  4753. // And if the field is of reference type, update 'Result' to refer to what
  4754. // the field refers to.
  4755. if (FD->getType()->isReferenceType()) {
  4756. APValue RVal;
  4757. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  4758. RVal))
  4759. return false;
  4760. Result.setFrom(Info.Ctx, RVal);
  4761. }
  4762. return true;
  4763. }
  4764. }
  4765. CallStackFrame *Frame = nullptr;
  4766. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  4767. // Only if a local variable was declared in the function currently being
  4768. // evaluated, do we expect to be able to find its value in the current
  4769. // frame. (Otherwise it was likely declared in an enclosing context and
  4770. // could either have a valid evaluatable value (for e.g. a constexpr
  4771. // variable) or be ill-formed (and trigger an appropriate evaluation
  4772. // diagnostic)).
  4773. if (Info.CurrentCall->Callee &&
  4774. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  4775. Frame = Info.CurrentCall;
  4776. }
  4777. }
  4778. if (!VD->getType()->isReferenceType()) {
  4779. if (Frame) {
  4780. Result.set({VD, Frame->Index,
  4781. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  4782. return true;
  4783. }
  4784. return Success(VD);
  4785. }
  4786. APValue *V;
  4787. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  4788. return false;
  4789. if (V->isUninit()) {
  4790. if (!Info.checkingPotentialConstantExpression())
  4791. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  4792. return false;
  4793. }
  4794. return Success(*V, E);
  4795. }
  4796. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  4797. const MaterializeTemporaryExpr *E) {
  4798. // Walk through the expression to find the materialized temporary itself.
  4799. SmallVector<const Expr *, 2> CommaLHSs;
  4800. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4801. const Expr *Inner = E->GetTemporaryExpr()->
  4802. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  4803. // If we passed any comma operators, evaluate their LHSs.
  4804. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  4805. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  4806. return false;
  4807. // A materialized temporary with static storage duration can appear within the
  4808. // result of a constant expression evaluation, so we need to preserve its
  4809. // value for use outside this evaluation.
  4810. APValue *Value;
  4811. if (E->getStorageDuration() == SD_Static) {
  4812. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  4813. *Value = APValue();
  4814. Result.set(E);
  4815. } else {
  4816. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  4817. *Info.CurrentCall);
  4818. }
  4819. QualType Type = Inner->getType();
  4820. // Materialize the temporary itself.
  4821. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  4822. (E->getStorageDuration() == SD_Static &&
  4823. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  4824. *Value = APValue();
  4825. return false;
  4826. }
  4827. // Adjust our lvalue to refer to the desired subobject.
  4828. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  4829. --I;
  4830. switch (Adjustments[I].Kind) {
  4831. case SubobjectAdjustment::DerivedToBaseAdjustment:
  4832. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  4833. Type, Result))
  4834. return false;
  4835. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  4836. break;
  4837. case SubobjectAdjustment::FieldAdjustment:
  4838. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  4839. return false;
  4840. Type = Adjustments[I].Field->getType();
  4841. break;
  4842. case SubobjectAdjustment::MemberPointerAdjustment:
  4843. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  4844. Adjustments[I].Ptr.RHS))
  4845. return false;
  4846. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  4847. break;
  4848. }
  4849. }
  4850. return true;
  4851. }
  4852. bool
  4853. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4854. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  4855. "lvalue compound literal in c++?");
  4856. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  4857. // only see this when folding in C, so there's no standard to follow here.
  4858. return Success(E);
  4859. }
  4860. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  4861. if (!E->isPotentiallyEvaluated())
  4862. return Success(E);
  4863. Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
  4864. << E->getExprOperand()->getType()
  4865. << E->getExprOperand()->getSourceRange();
  4866. return false;
  4867. }
  4868. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4869. return Success(E);
  4870. }
  4871. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  4872. // Handle static data members.
  4873. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  4874. VisitIgnoredBaseExpression(E->getBase());
  4875. return VisitVarDecl(E, VD);
  4876. }
  4877. // Handle static member functions.
  4878. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  4879. if (MD->isStatic()) {
  4880. VisitIgnoredBaseExpression(E->getBase());
  4881. return Success(MD);
  4882. }
  4883. }
  4884. // Handle non-static data members.
  4885. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  4886. }
  4887. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  4888. // FIXME: Deal with vectors as array subscript bases.
  4889. if (E->getBase()->getType()->isVectorType())
  4890. return Error(E);
  4891. bool Success = true;
  4892. if (!evaluatePointer(E->getBase(), Result)) {
  4893. if (!Info.noteFailure())
  4894. return false;
  4895. Success = false;
  4896. }
  4897. APSInt Index;
  4898. if (!EvaluateInteger(E->getIdx(), Index, Info))
  4899. return false;
  4900. return Success &&
  4901. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  4902. }
  4903. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  4904. return evaluatePointer(E->getSubExpr(), Result);
  4905. }
  4906. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4907. if (!Visit(E->getSubExpr()))
  4908. return false;
  4909. // __real is a no-op on scalar lvalues.
  4910. if (E->getSubExpr()->getType()->isAnyComplexType())
  4911. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  4912. return true;
  4913. }
  4914. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4915. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  4916. "lvalue __imag__ on scalar?");
  4917. if (!Visit(E->getSubExpr()))
  4918. return false;
  4919. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  4920. return true;
  4921. }
  4922. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  4923. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4924. return Error(UO);
  4925. if (!this->Visit(UO->getSubExpr()))
  4926. return false;
  4927. return handleIncDec(
  4928. this->Info, UO, Result, UO->getSubExpr()->getType(),
  4929. UO->isIncrementOp(), nullptr);
  4930. }
  4931. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  4932. const CompoundAssignOperator *CAO) {
  4933. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4934. return Error(CAO);
  4935. APValue RHS;
  4936. // The overall lvalue result is the result of evaluating the LHS.
  4937. if (!this->Visit(CAO->getLHS())) {
  4938. if (Info.noteFailure())
  4939. Evaluate(RHS, this->Info, CAO->getRHS());
  4940. return false;
  4941. }
  4942. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  4943. return false;
  4944. return handleCompoundAssignment(
  4945. this->Info, CAO,
  4946. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  4947. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  4948. }
  4949. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  4950. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4951. return Error(E);
  4952. APValue NewVal;
  4953. if (!this->Visit(E->getLHS())) {
  4954. if (Info.noteFailure())
  4955. Evaluate(NewVal, this->Info, E->getRHS());
  4956. return false;
  4957. }
  4958. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  4959. return false;
  4960. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  4961. NewVal);
  4962. }
  4963. //===----------------------------------------------------------------------===//
  4964. // Pointer Evaluation
  4965. //===----------------------------------------------------------------------===//
  4966. /// Attempts to compute the number of bytes available at the pointer
  4967. /// returned by a function with the alloc_size attribute. Returns true if we
  4968. /// were successful. Places an unsigned number into `Result`.
  4969. ///
  4970. /// This expects the given CallExpr to be a call to a function with an
  4971. /// alloc_size attribute.
  4972. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  4973. const CallExpr *Call,
  4974. llvm::APInt &Result) {
  4975. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  4976. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  4977. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  4978. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  4979. if (Call->getNumArgs() <= SizeArgNo)
  4980. return false;
  4981. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  4982. if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
  4983. return false;
  4984. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  4985. return false;
  4986. Into = Into.zextOrSelf(BitsInSizeT);
  4987. return true;
  4988. };
  4989. APSInt SizeOfElem;
  4990. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  4991. return false;
  4992. if (!AllocSize->getNumElemsParam().isValid()) {
  4993. Result = std::move(SizeOfElem);
  4994. return true;
  4995. }
  4996. APSInt NumberOfElems;
  4997. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  4998. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  4999. return false;
  5000. bool Overflow;
  5001. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  5002. if (Overflow)
  5003. return false;
  5004. Result = std::move(BytesAvailable);
  5005. return true;
  5006. }
  5007. /// Convenience function. LVal's base must be a call to an alloc_size
  5008. /// function.
  5009. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5010. const LValue &LVal,
  5011. llvm::APInt &Result) {
  5012. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  5013. "Can't get the size of a non alloc_size function");
  5014. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  5015. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  5016. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  5017. }
  5018. /// Attempts to evaluate the given LValueBase as the result of a call to
  5019. /// a function with the alloc_size attribute. If it was possible to do so, this
  5020. /// function will return true, make Result's Base point to said function call,
  5021. /// and mark Result's Base as invalid.
  5022. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  5023. LValue &Result) {
  5024. if (Base.isNull())
  5025. return false;
  5026. // Because we do no form of static analysis, we only support const variables.
  5027. //
  5028. // Additionally, we can't support parameters, nor can we support static
  5029. // variables (in the latter case, use-before-assign isn't UB; in the former,
  5030. // we have no clue what they'll be assigned to).
  5031. const auto *VD =
  5032. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  5033. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  5034. return false;
  5035. const Expr *Init = VD->getAnyInitializer();
  5036. if (!Init)
  5037. return false;
  5038. const Expr *E = Init->IgnoreParens();
  5039. if (!tryUnwrapAllocSizeCall(E))
  5040. return false;
  5041. // Store E instead of E unwrapped so that the type of the LValue's base is
  5042. // what the user wanted.
  5043. Result.setInvalid(E);
  5044. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  5045. Result.addUnsizedArray(Info, E, Pointee);
  5046. return true;
  5047. }
  5048. namespace {
  5049. class PointerExprEvaluator
  5050. : public ExprEvaluatorBase<PointerExprEvaluator> {
  5051. LValue &Result;
  5052. bool InvalidBaseOK;
  5053. bool Success(const Expr *E) {
  5054. Result.set(E);
  5055. return true;
  5056. }
  5057. bool evaluateLValue(const Expr *E, LValue &Result) {
  5058. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  5059. }
  5060. bool evaluatePointer(const Expr *E, LValue &Result) {
  5061. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  5062. }
  5063. bool visitNonBuiltinCallExpr(const CallExpr *E);
  5064. public:
  5065. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  5066. : ExprEvaluatorBaseTy(info), Result(Result),
  5067. InvalidBaseOK(InvalidBaseOK) {}
  5068. bool Success(const APValue &V, const Expr *E) {
  5069. Result.setFrom(Info.Ctx, V);
  5070. return true;
  5071. }
  5072. bool ZeroInitialization(const Expr *E) {
  5073. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  5074. Result.setNull(E->getType(), TargetVal);
  5075. return true;
  5076. }
  5077. bool VisitBinaryOperator(const BinaryOperator *E);
  5078. bool VisitCastExpr(const CastExpr* E);
  5079. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5080. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  5081. { return Success(E); }
  5082. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  5083. if (Info.noteFailure())
  5084. EvaluateIgnoredValue(Info, E->getSubExpr());
  5085. return Error(E);
  5086. }
  5087. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  5088. { return Success(E); }
  5089. bool VisitCallExpr(const CallExpr *E);
  5090. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  5091. bool VisitBlockExpr(const BlockExpr *E) {
  5092. if (!E->getBlockDecl()->hasCaptures())
  5093. return Success(E);
  5094. return Error(E);
  5095. }
  5096. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  5097. // Can't look at 'this' when checking a potential constant expression.
  5098. if (Info.checkingPotentialConstantExpression())
  5099. return false;
  5100. if (!Info.CurrentCall->This) {
  5101. if (Info.getLangOpts().CPlusPlus11)
  5102. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  5103. else
  5104. Info.FFDiag(E);
  5105. return false;
  5106. }
  5107. Result = *Info.CurrentCall->This;
  5108. // If we are inside a lambda's call operator, the 'this' expression refers
  5109. // to the enclosing '*this' object (either by value or reference) which is
  5110. // either copied into the closure object's field that represents the '*this'
  5111. // or refers to '*this'.
  5112. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  5113. // Update 'Result' to refer to the data member/field of the closure object
  5114. // that represents the '*this' capture.
  5115. if (!HandleLValueMember(Info, E, Result,
  5116. Info.CurrentCall->LambdaThisCaptureField))
  5117. return false;
  5118. // If we captured '*this' by reference, replace the field with its referent.
  5119. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  5120. ->isPointerType()) {
  5121. APValue RVal;
  5122. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  5123. RVal))
  5124. return false;
  5125. Result.setFrom(Info.Ctx, RVal);
  5126. }
  5127. }
  5128. return true;
  5129. }
  5130. // FIXME: Missing: @protocol, @selector
  5131. };
  5132. } // end anonymous namespace
  5133. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  5134. bool InvalidBaseOK) {
  5135. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  5136. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5137. }
  5138. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5139. if (E->getOpcode() != BO_Add &&
  5140. E->getOpcode() != BO_Sub)
  5141. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5142. const Expr *PExp = E->getLHS();
  5143. const Expr *IExp = E->getRHS();
  5144. if (IExp->getType()->isPointerType())
  5145. std::swap(PExp, IExp);
  5146. bool EvalPtrOK = evaluatePointer(PExp, Result);
  5147. if (!EvalPtrOK && !Info.noteFailure())
  5148. return false;
  5149. llvm::APSInt Offset;
  5150. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  5151. return false;
  5152. if (E->getOpcode() == BO_Sub)
  5153. negateAsSigned(Offset);
  5154. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  5155. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  5156. }
  5157. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5158. return evaluateLValue(E->getSubExpr(), Result);
  5159. }
  5160. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5161. const Expr *SubExpr = E->getSubExpr();
  5162. switch (E->getCastKind()) {
  5163. default:
  5164. break;
  5165. case CK_BitCast:
  5166. case CK_CPointerToObjCPointerCast:
  5167. case CK_BlockPointerToObjCPointerCast:
  5168. case CK_AnyPointerToBlockPointerCast:
  5169. case CK_AddressSpaceConversion:
  5170. if (!Visit(SubExpr))
  5171. return false;
  5172. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  5173. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  5174. // also static_casts, but we disallow them as a resolution to DR1312.
  5175. if (!E->getType()->isVoidPointerType()) {
  5176. Result.Designator.setInvalid();
  5177. if (SubExpr->getType()->isVoidPointerType())
  5178. CCEDiag(E, diag::note_constexpr_invalid_cast)
  5179. << 3 << SubExpr->getType();
  5180. else
  5181. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5182. }
  5183. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  5184. ZeroInitialization(E);
  5185. return true;
  5186. case CK_DerivedToBase:
  5187. case CK_UncheckedDerivedToBase:
  5188. if (!evaluatePointer(E->getSubExpr(), Result))
  5189. return false;
  5190. if (!Result.Base && Result.Offset.isZero())
  5191. return true;
  5192. // Now figure out the necessary offset to add to the base LV to get from
  5193. // the derived class to the base class.
  5194. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  5195. castAs<PointerType>()->getPointeeType(),
  5196. Result);
  5197. case CK_BaseToDerived:
  5198. if (!Visit(E->getSubExpr()))
  5199. return false;
  5200. if (!Result.Base && Result.Offset.isZero())
  5201. return true;
  5202. return HandleBaseToDerivedCast(Info, E, Result);
  5203. case CK_NullToPointer:
  5204. VisitIgnoredValue(E->getSubExpr());
  5205. return ZeroInitialization(E);
  5206. case CK_IntegralToPointer: {
  5207. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5208. APValue Value;
  5209. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  5210. break;
  5211. if (Value.isInt()) {
  5212. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  5213. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  5214. Result.Base = (Expr*)nullptr;
  5215. Result.InvalidBase = false;
  5216. Result.Offset = CharUnits::fromQuantity(N);
  5217. Result.Designator.setInvalid();
  5218. Result.IsNullPtr = false;
  5219. return true;
  5220. } else {
  5221. // Cast is of an lvalue, no need to change value.
  5222. Result.setFrom(Info.Ctx, Value);
  5223. return true;
  5224. }
  5225. }
  5226. case CK_ArrayToPointerDecay: {
  5227. if (SubExpr->isGLValue()) {
  5228. if (!evaluateLValue(SubExpr, Result))
  5229. return false;
  5230. } else {
  5231. APValue &Value = createTemporary(SubExpr, false, Result,
  5232. *Info.CurrentCall);
  5233. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  5234. return false;
  5235. }
  5236. // The result is a pointer to the first element of the array.
  5237. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  5238. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5239. Result.addArray(Info, E, CAT);
  5240. else
  5241. Result.addUnsizedArray(Info, E, AT->getElementType());
  5242. return true;
  5243. }
  5244. case CK_FunctionToPointerDecay:
  5245. return evaluateLValue(SubExpr, Result);
  5246. case CK_LValueToRValue: {
  5247. LValue LVal;
  5248. if (!evaluateLValue(E->getSubExpr(), LVal))
  5249. return false;
  5250. APValue RVal;
  5251. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5252. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5253. LVal, RVal))
  5254. return InvalidBaseOK &&
  5255. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  5256. return Success(RVal, E);
  5257. }
  5258. }
  5259. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5260. }
  5261. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  5262. UnaryExprOrTypeTrait ExprKind) {
  5263. // C++ [expr.alignof]p3:
  5264. // When alignof is applied to a reference type, the result is the
  5265. // alignment of the referenced type.
  5266. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  5267. T = Ref->getPointeeType();
  5268. if (T.getQualifiers().hasUnaligned())
  5269. return CharUnits::One();
  5270. const bool AlignOfReturnsPreferred =
  5271. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  5272. // __alignof is defined to return the preferred alignment.
  5273. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  5274. // as well.
  5275. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  5276. return Info.Ctx.toCharUnitsFromBits(
  5277. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  5278. // alignof and _Alignof are defined to return the ABI alignment.
  5279. else if (ExprKind == UETT_AlignOf)
  5280. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  5281. else
  5282. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  5283. }
  5284. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  5285. UnaryExprOrTypeTrait ExprKind) {
  5286. E = E->IgnoreParens();
  5287. // The kinds of expressions that we have special-case logic here for
  5288. // should be kept up to date with the special checks for those
  5289. // expressions in Sema.
  5290. // alignof decl is always accepted, even if it doesn't make sense: we default
  5291. // to 1 in those cases.
  5292. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5293. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  5294. /*RefAsPointee*/true);
  5295. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  5296. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  5297. /*RefAsPointee*/true);
  5298. return GetAlignOfType(Info, E->getType(), ExprKind);
  5299. }
  5300. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  5301. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  5302. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  5303. return true;
  5304. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  5305. return false;
  5306. Result.setInvalid(E);
  5307. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  5308. Result.addUnsizedArray(Info, E, PointeeTy);
  5309. return true;
  5310. }
  5311. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  5312. if (IsStringLiteralCall(E))
  5313. return Success(E);
  5314. if (unsigned BuiltinOp = E->getBuiltinCallee())
  5315. return VisitBuiltinCallExpr(E, BuiltinOp);
  5316. return visitNonBuiltinCallExpr(E);
  5317. }
  5318. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  5319. unsigned BuiltinOp) {
  5320. switch (BuiltinOp) {
  5321. case Builtin::BI__builtin_addressof:
  5322. return evaluateLValue(E->getArg(0), Result);
  5323. case Builtin::BI__builtin_assume_aligned: {
  5324. // We need to be very careful here because: if the pointer does not have the
  5325. // asserted alignment, then the behavior is undefined, and undefined
  5326. // behavior is non-constant.
  5327. if (!evaluatePointer(E->getArg(0), Result))
  5328. return false;
  5329. LValue OffsetResult(Result);
  5330. APSInt Alignment;
  5331. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  5332. return false;
  5333. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  5334. if (E->getNumArgs() > 2) {
  5335. APSInt Offset;
  5336. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  5337. return false;
  5338. int64_t AdditionalOffset = -Offset.getZExtValue();
  5339. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  5340. }
  5341. // If there is a base object, then it must have the correct alignment.
  5342. if (OffsetResult.Base) {
  5343. CharUnits BaseAlignment;
  5344. if (const ValueDecl *VD =
  5345. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  5346. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  5347. } else {
  5348. BaseAlignment = GetAlignOfExpr(
  5349. Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
  5350. }
  5351. if (BaseAlignment < Align) {
  5352. Result.Designator.setInvalid();
  5353. // FIXME: Add support to Diagnostic for long / long long.
  5354. CCEDiag(E->getArg(0),
  5355. diag::note_constexpr_baa_insufficient_alignment) << 0
  5356. << (unsigned)BaseAlignment.getQuantity()
  5357. << (unsigned)Align.getQuantity();
  5358. return false;
  5359. }
  5360. }
  5361. // The offset must also have the correct alignment.
  5362. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  5363. Result.Designator.setInvalid();
  5364. (OffsetResult.Base
  5365. ? CCEDiag(E->getArg(0),
  5366. diag::note_constexpr_baa_insufficient_alignment) << 1
  5367. : CCEDiag(E->getArg(0),
  5368. diag::note_constexpr_baa_value_insufficient_alignment))
  5369. << (int)OffsetResult.Offset.getQuantity()
  5370. << (unsigned)Align.getQuantity();
  5371. return false;
  5372. }
  5373. return true;
  5374. }
  5375. case Builtin::BIstrchr:
  5376. case Builtin::BIwcschr:
  5377. case Builtin::BImemchr:
  5378. case Builtin::BIwmemchr:
  5379. if (Info.getLangOpts().CPlusPlus11)
  5380. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5381. << /*isConstexpr*/0 << /*isConstructor*/0
  5382. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5383. else
  5384. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5385. LLVM_FALLTHROUGH;
  5386. case Builtin::BI__builtin_strchr:
  5387. case Builtin::BI__builtin_wcschr:
  5388. case Builtin::BI__builtin_memchr:
  5389. case Builtin::BI__builtin_char_memchr:
  5390. case Builtin::BI__builtin_wmemchr: {
  5391. if (!Visit(E->getArg(0)))
  5392. return false;
  5393. APSInt Desired;
  5394. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  5395. return false;
  5396. uint64_t MaxLength = uint64_t(-1);
  5397. if (BuiltinOp != Builtin::BIstrchr &&
  5398. BuiltinOp != Builtin::BIwcschr &&
  5399. BuiltinOp != Builtin::BI__builtin_strchr &&
  5400. BuiltinOp != Builtin::BI__builtin_wcschr) {
  5401. APSInt N;
  5402. if (!EvaluateInteger(E->getArg(2), N, Info))
  5403. return false;
  5404. MaxLength = N.getExtValue();
  5405. }
  5406. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  5407. // Figure out what value we're actually looking for (after converting to
  5408. // the corresponding unsigned type if necessary).
  5409. uint64_t DesiredVal;
  5410. bool StopAtNull = false;
  5411. switch (BuiltinOp) {
  5412. case Builtin::BIstrchr:
  5413. case Builtin::BI__builtin_strchr:
  5414. // strchr compares directly to the passed integer, and therefore
  5415. // always fails if given an int that is not a char.
  5416. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  5417. E->getArg(1)->getType(),
  5418. Desired),
  5419. Desired))
  5420. return ZeroInitialization(E);
  5421. StopAtNull = true;
  5422. LLVM_FALLTHROUGH;
  5423. case Builtin::BImemchr:
  5424. case Builtin::BI__builtin_memchr:
  5425. case Builtin::BI__builtin_char_memchr:
  5426. // memchr compares by converting both sides to unsigned char. That's also
  5427. // correct for strchr if we get this far (to cope with plain char being
  5428. // unsigned in the strchr case).
  5429. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  5430. break;
  5431. case Builtin::BIwcschr:
  5432. case Builtin::BI__builtin_wcschr:
  5433. StopAtNull = true;
  5434. LLVM_FALLTHROUGH;
  5435. case Builtin::BIwmemchr:
  5436. case Builtin::BI__builtin_wmemchr:
  5437. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  5438. DesiredVal = Desired.getZExtValue();
  5439. break;
  5440. }
  5441. for (; MaxLength; --MaxLength) {
  5442. APValue Char;
  5443. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  5444. !Char.isInt())
  5445. return false;
  5446. if (Char.getInt().getZExtValue() == DesiredVal)
  5447. return true;
  5448. if (StopAtNull && !Char.getInt())
  5449. break;
  5450. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  5451. return false;
  5452. }
  5453. // Not found: return nullptr.
  5454. return ZeroInitialization(E);
  5455. }
  5456. case Builtin::BImemcpy:
  5457. case Builtin::BImemmove:
  5458. case Builtin::BIwmemcpy:
  5459. case Builtin::BIwmemmove:
  5460. if (Info.getLangOpts().CPlusPlus11)
  5461. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5462. << /*isConstexpr*/0 << /*isConstructor*/0
  5463. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5464. else
  5465. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5466. LLVM_FALLTHROUGH;
  5467. case Builtin::BI__builtin_memcpy:
  5468. case Builtin::BI__builtin_memmove:
  5469. case Builtin::BI__builtin_wmemcpy:
  5470. case Builtin::BI__builtin_wmemmove: {
  5471. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  5472. BuiltinOp == Builtin::BIwmemmove ||
  5473. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  5474. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5475. bool Move = BuiltinOp == Builtin::BImemmove ||
  5476. BuiltinOp == Builtin::BIwmemmove ||
  5477. BuiltinOp == Builtin::BI__builtin_memmove ||
  5478. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5479. // The result of mem* is the first argument.
  5480. if (!Visit(E->getArg(0)))
  5481. return false;
  5482. LValue Dest = Result;
  5483. LValue Src;
  5484. if (!EvaluatePointer(E->getArg(1), Src, Info))
  5485. return false;
  5486. APSInt N;
  5487. if (!EvaluateInteger(E->getArg(2), N, Info))
  5488. return false;
  5489. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  5490. // If the size is zero, we treat this as always being a valid no-op.
  5491. // (Even if one of the src and dest pointers is null.)
  5492. if (!N)
  5493. return true;
  5494. // Otherwise, if either of the operands is null, we can't proceed. Don't
  5495. // try to determine the type of the copied objects, because there aren't
  5496. // any.
  5497. if (!Src.Base || !Dest.Base) {
  5498. APValue Val;
  5499. (!Src.Base ? Src : Dest).moveInto(Val);
  5500. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  5501. << Move << WChar << !!Src.Base
  5502. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  5503. return false;
  5504. }
  5505. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  5506. return false;
  5507. // We require that Src and Dest are both pointers to arrays of
  5508. // trivially-copyable type. (For the wide version, the designator will be
  5509. // invalid if the designated object is not a wchar_t.)
  5510. QualType T = Dest.Designator.getType(Info.Ctx);
  5511. QualType SrcT = Src.Designator.getType(Info.Ctx);
  5512. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  5513. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  5514. return false;
  5515. }
  5516. if (T->isIncompleteType()) {
  5517. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  5518. return false;
  5519. }
  5520. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  5521. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  5522. return false;
  5523. }
  5524. // Figure out how many T's we're copying.
  5525. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  5526. if (!WChar) {
  5527. uint64_t Remainder;
  5528. llvm::APInt OrigN = N;
  5529. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  5530. if (Remainder) {
  5531. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  5532. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  5533. << (unsigned)TSize;
  5534. return false;
  5535. }
  5536. }
  5537. // Check that the copying will remain within the arrays, just so that we
  5538. // can give a more meaningful diagnostic. This implicitly also checks that
  5539. // N fits into 64 bits.
  5540. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  5541. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  5542. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  5543. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  5544. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  5545. << N.toString(10, /*Signed*/false);
  5546. return false;
  5547. }
  5548. uint64_t NElems = N.getZExtValue();
  5549. uint64_t NBytes = NElems * TSize;
  5550. // Check for overlap.
  5551. int Direction = 1;
  5552. if (HasSameBase(Src, Dest)) {
  5553. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  5554. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  5555. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  5556. // Dest is inside the source region.
  5557. if (!Move) {
  5558. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  5559. return false;
  5560. }
  5561. // For memmove and friends, copy backwards.
  5562. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  5563. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  5564. return false;
  5565. Direction = -1;
  5566. } else if (!Move && SrcOffset >= DestOffset &&
  5567. SrcOffset - DestOffset < NBytes) {
  5568. // Src is inside the destination region for memcpy: invalid.
  5569. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  5570. return false;
  5571. }
  5572. }
  5573. while (true) {
  5574. APValue Val;
  5575. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  5576. !handleAssignment(Info, E, Dest, T, Val))
  5577. return false;
  5578. // Do not iterate past the last element; if we're copying backwards, that
  5579. // might take us off the start of the array.
  5580. if (--NElems == 0)
  5581. return true;
  5582. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  5583. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  5584. return false;
  5585. }
  5586. }
  5587. default:
  5588. return visitNonBuiltinCallExpr(E);
  5589. }
  5590. }
  5591. //===----------------------------------------------------------------------===//
  5592. // Member Pointer Evaluation
  5593. //===----------------------------------------------------------------------===//
  5594. namespace {
  5595. class MemberPointerExprEvaluator
  5596. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  5597. MemberPtr &Result;
  5598. bool Success(const ValueDecl *D) {
  5599. Result = MemberPtr(D);
  5600. return true;
  5601. }
  5602. public:
  5603. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  5604. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  5605. bool Success(const APValue &V, const Expr *E) {
  5606. Result.setFrom(V);
  5607. return true;
  5608. }
  5609. bool ZeroInitialization(const Expr *E) {
  5610. return Success((const ValueDecl*)nullptr);
  5611. }
  5612. bool VisitCastExpr(const CastExpr *E);
  5613. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5614. };
  5615. } // end anonymous namespace
  5616. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  5617. EvalInfo &Info) {
  5618. assert(E->isRValue() && E->getType()->isMemberPointerType());
  5619. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  5620. }
  5621. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5622. switch (E->getCastKind()) {
  5623. default:
  5624. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5625. case CK_NullToMemberPointer:
  5626. VisitIgnoredValue(E->getSubExpr());
  5627. return ZeroInitialization(E);
  5628. case CK_BaseToDerivedMemberPointer: {
  5629. if (!Visit(E->getSubExpr()))
  5630. return false;
  5631. if (E->path_empty())
  5632. return true;
  5633. // Base-to-derived member pointer casts store the path in derived-to-base
  5634. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  5635. // the wrong end of the derived->base arc, so stagger the path by one class.
  5636. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  5637. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  5638. PathI != PathE; ++PathI) {
  5639. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5640. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  5641. if (!Result.castToDerived(Derived))
  5642. return Error(E);
  5643. }
  5644. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  5645. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  5646. return Error(E);
  5647. return true;
  5648. }
  5649. case CK_DerivedToBaseMemberPointer:
  5650. if (!Visit(E->getSubExpr()))
  5651. return false;
  5652. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5653. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5654. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5655. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5656. if (!Result.castToBase(Base))
  5657. return Error(E);
  5658. }
  5659. return true;
  5660. }
  5661. }
  5662. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5663. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  5664. // member can be formed.
  5665. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  5666. }
  5667. //===----------------------------------------------------------------------===//
  5668. // Record Evaluation
  5669. //===----------------------------------------------------------------------===//
  5670. namespace {
  5671. class RecordExprEvaluator
  5672. : public ExprEvaluatorBase<RecordExprEvaluator> {
  5673. const LValue &This;
  5674. APValue &Result;
  5675. public:
  5676. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  5677. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  5678. bool Success(const APValue &V, const Expr *E) {
  5679. Result = V;
  5680. return true;
  5681. }
  5682. bool ZeroInitialization(const Expr *E) {
  5683. return ZeroInitialization(E, E->getType());
  5684. }
  5685. bool ZeroInitialization(const Expr *E, QualType T);
  5686. bool VisitCallExpr(const CallExpr *E) {
  5687. return handleCallExpr(E, Result, &This);
  5688. }
  5689. bool VisitCastExpr(const CastExpr *E);
  5690. bool VisitInitListExpr(const InitListExpr *E);
  5691. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5692. return VisitCXXConstructExpr(E, E->getType());
  5693. }
  5694. bool VisitLambdaExpr(const LambdaExpr *E);
  5695. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  5696. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  5697. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  5698. bool VisitBinCmp(const BinaryOperator *E);
  5699. };
  5700. }
  5701. /// Perform zero-initialization on an object of non-union class type.
  5702. /// C++11 [dcl.init]p5:
  5703. /// To zero-initialize an object or reference of type T means:
  5704. /// [...]
  5705. /// -- if T is a (possibly cv-qualified) non-union class type,
  5706. /// each non-static data member and each base-class subobject is
  5707. /// zero-initialized
  5708. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  5709. const RecordDecl *RD,
  5710. const LValue &This, APValue &Result) {
  5711. assert(!RD->isUnion() && "Expected non-union class type");
  5712. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  5713. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  5714. std::distance(RD->field_begin(), RD->field_end()));
  5715. if (RD->isInvalidDecl()) return false;
  5716. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5717. if (CD) {
  5718. unsigned Index = 0;
  5719. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  5720. End = CD->bases_end(); I != End; ++I, ++Index) {
  5721. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  5722. LValue Subobject = This;
  5723. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  5724. return false;
  5725. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  5726. Result.getStructBase(Index)))
  5727. return false;
  5728. }
  5729. }
  5730. for (const auto *I : RD->fields()) {
  5731. // -- if T is a reference type, no initialization is performed.
  5732. if (I->getType()->isReferenceType())
  5733. continue;
  5734. LValue Subobject = This;
  5735. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  5736. return false;
  5737. ImplicitValueInitExpr VIE(I->getType());
  5738. if (!EvaluateInPlace(
  5739. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  5740. return false;
  5741. }
  5742. return true;
  5743. }
  5744. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  5745. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  5746. if (RD->isInvalidDecl()) return false;
  5747. if (RD->isUnion()) {
  5748. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  5749. // object's first non-static named data member is zero-initialized
  5750. RecordDecl::field_iterator I = RD->field_begin();
  5751. if (I == RD->field_end()) {
  5752. Result = APValue((const FieldDecl*)nullptr);
  5753. return true;
  5754. }
  5755. LValue Subobject = This;
  5756. if (!HandleLValueMember(Info, E, Subobject, *I))
  5757. return false;
  5758. Result = APValue(*I);
  5759. ImplicitValueInitExpr VIE(I->getType());
  5760. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  5761. }
  5762. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  5763. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  5764. return false;
  5765. }
  5766. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  5767. }
  5768. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5769. switch (E->getCastKind()) {
  5770. default:
  5771. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5772. case CK_ConstructorConversion:
  5773. return Visit(E->getSubExpr());
  5774. case CK_DerivedToBase:
  5775. case CK_UncheckedDerivedToBase: {
  5776. APValue DerivedObject;
  5777. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  5778. return false;
  5779. if (!DerivedObject.isStruct())
  5780. return Error(E->getSubExpr());
  5781. // Derived-to-base rvalue conversion: just slice off the derived part.
  5782. APValue *Value = &DerivedObject;
  5783. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  5784. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5785. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5786. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  5787. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5788. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  5789. RD = Base;
  5790. }
  5791. Result = *Value;
  5792. return true;
  5793. }
  5794. }
  5795. }
  5796. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5797. if (E->isTransparent())
  5798. return Visit(E->getInit(0));
  5799. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  5800. if (RD->isInvalidDecl()) return false;
  5801. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5802. if (RD->isUnion()) {
  5803. const FieldDecl *Field = E->getInitializedFieldInUnion();
  5804. Result = APValue(Field);
  5805. if (!Field)
  5806. return true;
  5807. // If the initializer list for a union does not contain any elements, the
  5808. // first element of the union is value-initialized.
  5809. // FIXME: The element should be initialized from an initializer list.
  5810. // Is this difference ever observable for initializer lists which
  5811. // we don't build?
  5812. ImplicitValueInitExpr VIE(Field->getType());
  5813. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  5814. LValue Subobject = This;
  5815. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  5816. return false;
  5817. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5818. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5819. isa<CXXDefaultInitExpr>(InitExpr));
  5820. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  5821. }
  5822. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  5823. if (Result.isUninit())
  5824. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  5825. std::distance(RD->field_begin(), RD->field_end()));
  5826. unsigned ElementNo = 0;
  5827. bool Success = true;
  5828. // Initialize base classes.
  5829. if (CXXRD) {
  5830. for (const auto &Base : CXXRD->bases()) {
  5831. assert(ElementNo < E->getNumInits() && "missing init for base class");
  5832. const Expr *Init = E->getInit(ElementNo);
  5833. LValue Subobject = This;
  5834. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  5835. return false;
  5836. APValue &FieldVal = Result.getStructBase(ElementNo);
  5837. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  5838. if (!Info.noteFailure())
  5839. return false;
  5840. Success = false;
  5841. }
  5842. ++ElementNo;
  5843. }
  5844. }
  5845. // Initialize members.
  5846. for (const auto *Field : RD->fields()) {
  5847. // Anonymous bit-fields are not considered members of the class for
  5848. // purposes of aggregate initialization.
  5849. if (Field->isUnnamedBitfield())
  5850. continue;
  5851. LValue Subobject = This;
  5852. bool HaveInit = ElementNo < E->getNumInits();
  5853. // FIXME: Diagnostics here should point to the end of the initializer
  5854. // list, not the start.
  5855. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  5856. Subobject, Field, &Layout))
  5857. return false;
  5858. // Perform an implicit value-initialization for members beyond the end of
  5859. // the initializer list.
  5860. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  5861. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  5862. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5863. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5864. isa<CXXDefaultInitExpr>(Init));
  5865. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5866. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  5867. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  5868. FieldVal, Field))) {
  5869. if (!Info.noteFailure())
  5870. return false;
  5871. Success = false;
  5872. }
  5873. }
  5874. return Success;
  5875. }
  5876. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5877. QualType T) {
  5878. // Note that E's type is not necessarily the type of our class here; we might
  5879. // be initializing an array element instead.
  5880. const CXXConstructorDecl *FD = E->getConstructor();
  5881. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  5882. bool ZeroInit = E->requiresZeroInitialization();
  5883. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  5884. // If we've already performed zero-initialization, we're already done.
  5885. if (!Result.isUninit())
  5886. return true;
  5887. // We can get here in two different ways:
  5888. // 1) We're performing value-initialization, and should zero-initialize
  5889. // the object, or
  5890. // 2) We're performing default-initialization of an object with a trivial
  5891. // constexpr default constructor, in which case we should start the
  5892. // lifetimes of all the base subobjects (there can be no data member
  5893. // subobjects in this case) per [basic.life]p1.
  5894. // Either way, ZeroInitialization is appropriate.
  5895. return ZeroInitialization(E, T);
  5896. }
  5897. const FunctionDecl *Definition = nullptr;
  5898. auto Body = FD->getBody(Definition);
  5899. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5900. return false;
  5901. // Avoid materializing a temporary for an elidable copy/move constructor.
  5902. if (E->isElidable() && !ZeroInit)
  5903. if (const MaterializeTemporaryExpr *ME
  5904. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  5905. return Visit(ME->GetTemporaryExpr());
  5906. if (ZeroInit && !ZeroInitialization(E, T))
  5907. return false;
  5908. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5909. return HandleConstructorCall(E, This, Args,
  5910. cast<CXXConstructorDecl>(Definition), Info,
  5911. Result);
  5912. }
  5913. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  5914. const CXXInheritedCtorInitExpr *E) {
  5915. if (!Info.CurrentCall) {
  5916. assert(Info.checkingPotentialConstantExpression());
  5917. return false;
  5918. }
  5919. const CXXConstructorDecl *FD = E->getConstructor();
  5920. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  5921. return false;
  5922. const FunctionDecl *Definition = nullptr;
  5923. auto Body = FD->getBody(Definition);
  5924. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5925. return false;
  5926. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  5927. cast<CXXConstructorDecl>(Definition), Info,
  5928. Result);
  5929. }
  5930. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  5931. const CXXStdInitializerListExpr *E) {
  5932. const ConstantArrayType *ArrayType =
  5933. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  5934. LValue Array;
  5935. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  5936. return false;
  5937. // Get a pointer to the first element of the array.
  5938. Array.addArray(Info, E, ArrayType);
  5939. // FIXME: Perform the checks on the field types in SemaInit.
  5940. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  5941. RecordDecl::field_iterator Field = Record->field_begin();
  5942. if (Field == Record->field_end())
  5943. return Error(E);
  5944. // Start pointer.
  5945. if (!Field->getType()->isPointerType() ||
  5946. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5947. ArrayType->getElementType()))
  5948. return Error(E);
  5949. // FIXME: What if the initializer_list type has base classes, etc?
  5950. Result = APValue(APValue::UninitStruct(), 0, 2);
  5951. Array.moveInto(Result.getStructField(0));
  5952. if (++Field == Record->field_end())
  5953. return Error(E);
  5954. if (Field->getType()->isPointerType() &&
  5955. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5956. ArrayType->getElementType())) {
  5957. // End pointer.
  5958. if (!HandleLValueArrayAdjustment(Info, E, Array,
  5959. ArrayType->getElementType(),
  5960. ArrayType->getSize().getZExtValue()))
  5961. return false;
  5962. Array.moveInto(Result.getStructField(1));
  5963. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  5964. // Length.
  5965. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  5966. else
  5967. return Error(E);
  5968. if (++Field != Record->field_end())
  5969. return Error(E);
  5970. return true;
  5971. }
  5972. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  5973. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  5974. if (ClosureClass->isInvalidDecl()) return false;
  5975. if (Info.checkingPotentialConstantExpression()) return true;
  5976. const size_t NumFields =
  5977. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  5978. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  5979. E->capture_init_end()) &&
  5980. "The number of lambda capture initializers should equal the number of "
  5981. "fields within the closure type");
  5982. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  5983. // Iterate through all the lambda's closure object's fields and initialize
  5984. // them.
  5985. auto *CaptureInitIt = E->capture_init_begin();
  5986. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  5987. bool Success = true;
  5988. for (const auto *Field : ClosureClass->fields()) {
  5989. assert(CaptureInitIt != E->capture_init_end());
  5990. // Get the initializer for this field
  5991. Expr *const CurFieldInit = *CaptureInitIt++;
  5992. // If there is no initializer, either this is a VLA or an error has
  5993. // occurred.
  5994. if (!CurFieldInit)
  5995. return Error(E);
  5996. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5997. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  5998. if (!Info.keepEvaluatingAfterFailure())
  5999. return false;
  6000. Success = false;
  6001. }
  6002. ++CaptureIt;
  6003. }
  6004. return Success;
  6005. }
  6006. static bool EvaluateRecord(const Expr *E, const LValue &This,
  6007. APValue &Result, EvalInfo &Info) {
  6008. assert(E->isRValue() && E->getType()->isRecordType() &&
  6009. "can't evaluate expression as a record rvalue");
  6010. return RecordExprEvaluator(Info, This, Result).Visit(E);
  6011. }
  6012. //===----------------------------------------------------------------------===//
  6013. // Temporary Evaluation
  6014. //
  6015. // Temporaries are represented in the AST as rvalues, but generally behave like
  6016. // lvalues. The full-object of which the temporary is a subobject is implicitly
  6017. // materialized so that a reference can bind to it.
  6018. //===----------------------------------------------------------------------===//
  6019. namespace {
  6020. class TemporaryExprEvaluator
  6021. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  6022. public:
  6023. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  6024. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  6025. /// Visit an expression which constructs the value of this temporary.
  6026. bool VisitConstructExpr(const Expr *E) {
  6027. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  6028. return EvaluateInPlace(Value, Info, Result, E);
  6029. }
  6030. bool VisitCastExpr(const CastExpr *E) {
  6031. switch (E->getCastKind()) {
  6032. default:
  6033. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6034. case CK_ConstructorConversion:
  6035. return VisitConstructExpr(E->getSubExpr());
  6036. }
  6037. }
  6038. bool VisitInitListExpr(const InitListExpr *E) {
  6039. return VisitConstructExpr(E);
  6040. }
  6041. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6042. return VisitConstructExpr(E);
  6043. }
  6044. bool VisitCallExpr(const CallExpr *E) {
  6045. return VisitConstructExpr(E);
  6046. }
  6047. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  6048. return VisitConstructExpr(E);
  6049. }
  6050. bool VisitLambdaExpr(const LambdaExpr *E) {
  6051. return VisitConstructExpr(E);
  6052. }
  6053. };
  6054. } // end anonymous namespace
  6055. /// Evaluate an expression of record type as a temporary.
  6056. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  6057. assert(E->isRValue() && E->getType()->isRecordType());
  6058. return TemporaryExprEvaluator(Info, Result).Visit(E);
  6059. }
  6060. //===----------------------------------------------------------------------===//
  6061. // Vector Evaluation
  6062. //===----------------------------------------------------------------------===//
  6063. namespace {
  6064. class VectorExprEvaluator
  6065. : public ExprEvaluatorBase<VectorExprEvaluator> {
  6066. APValue &Result;
  6067. public:
  6068. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  6069. : ExprEvaluatorBaseTy(info), Result(Result) {}
  6070. bool Success(ArrayRef<APValue> V, const Expr *E) {
  6071. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  6072. // FIXME: remove this APValue copy.
  6073. Result = APValue(V.data(), V.size());
  6074. return true;
  6075. }
  6076. bool Success(const APValue &V, const Expr *E) {
  6077. assert(V.isVector());
  6078. Result = V;
  6079. return true;
  6080. }
  6081. bool ZeroInitialization(const Expr *E);
  6082. bool VisitUnaryReal(const UnaryOperator *E)
  6083. { return Visit(E->getSubExpr()); }
  6084. bool VisitCastExpr(const CastExpr* E);
  6085. bool VisitInitListExpr(const InitListExpr *E);
  6086. bool VisitUnaryImag(const UnaryOperator *E);
  6087. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  6088. // binary comparisons, binary and/or/xor,
  6089. // shufflevector, ExtVectorElementExpr
  6090. };
  6091. } // end anonymous namespace
  6092. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  6093. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  6094. return VectorExprEvaluator(Info, Result).Visit(E);
  6095. }
  6096. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6097. const VectorType *VTy = E->getType()->castAs<VectorType>();
  6098. unsigned NElts = VTy->getNumElements();
  6099. const Expr *SE = E->getSubExpr();
  6100. QualType SETy = SE->getType();
  6101. switch (E->getCastKind()) {
  6102. case CK_VectorSplat: {
  6103. APValue Val = APValue();
  6104. if (SETy->isIntegerType()) {
  6105. APSInt IntResult;
  6106. if (!EvaluateInteger(SE, IntResult, Info))
  6107. return false;
  6108. Val = APValue(std::move(IntResult));
  6109. } else if (SETy->isRealFloatingType()) {
  6110. APFloat FloatResult(0.0);
  6111. if (!EvaluateFloat(SE, FloatResult, Info))
  6112. return false;
  6113. Val = APValue(std::move(FloatResult));
  6114. } else {
  6115. return Error(E);
  6116. }
  6117. // Splat and create vector APValue.
  6118. SmallVector<APValue, 4> Elts(NElts, Val);
  6119. return Success(Elts, E);
  6120. }
  6121. case CK_BitCast: {
  6122. // Evaluate the operand into an APInt we can extract from.
  6123. llvm::APInt SValInt;
  6124. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  6125. return false;
  6126. // Extract the elements
  6127. QualType EltTy = VTy->getElementType();
  6128. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  6129. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  6130. SmallVector<APValue, 4> Elts;
  6131. if (EltTy->isRealFloatingType()) {
  6132. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  6133. unsigned FloatEltSize = EltSize;
  6134. if (&Sem == &APFloat::x87DoubleExtended())
  6135. FloatEltSize = 80;
  6136. for (unsigned i = 0; i < NElts; i++) {
  6137. llvm::APInt Elt;
  6138. if (BigEndian)
  6139. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  6140. else
  6141. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  6142. Elts.push_back(APValue(APFloat(Sem, Elt)));
  6143. }
  6144. } else if (EltTy->isIntegerType()) {
  6145. for (unsigned i = 0; i < NElts; i++) {
  6146. llvm::APInt Elt;
  6147. if (BigEndian)
  6148. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  6149. else
  6150. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  6151. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  6152. }
  6153. } else {
  6154. return Error(E);
  6155. }
  6156. return Success(Elts, E);
  6157. }
  6158. default:
  6159. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6160. }
  6161. }
  6162. bool
  6163. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6164. const VectorType *VT = E->getType()->castAs<VectorType>();
  6165. unsigned NumInits = E->getNumInits();
  6166. unsigned NumElements = VT->getNumElements();
  6167. QualType EltTy = VT->getElementType();
  6168. SmallVector<APValue, 4> Elements;
  6169. // The number of initializers can be less than the number of
  6170. // vector elements. For OpenCL, this can be due to nested vector
  6171. // initialization. For GCC compatibility, missing trailing elements
  6172. // should be initialized with zeroes.
  6173. unsigned CountInits = 0, CountElts = 0;
  6174. while (CountElts < NumElements) {
  6175. // Handle nested vector initialization.
  6176. if (CountInits < NumInits
  6177. && E->getInit(CountInits)->getType()->isVectorType()) {
  6178. APValue v;
  6179. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  6180. return Error(E);
  6181. unsigned vlen = v.getVectorLength();
  6182. for (unsigned j = 0; j < vlen; j++)
  6183. Elements.push_back(v.getVectorElt(j));
  6184. CountElts += vlen;
  6185. } else if (EltTy->isIntegerType()) {
  6186. llvm::APSInt sInt(32);
  6187. if (CountInits < NumInits) {
  6188. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  6189. return false;
  6190. } else // trailing integer zero.
  6191. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  6192. Elements.push_back(APValue(sInt));
  6193. CountElts++;
  6194. } else {
  6195. llvm::APFloat f(0.0);
  6196. if (CountInits < NumInits) {
  6197. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  6198. return false;
  6199. } else // trailing float zero.
  6200. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  6201. Elements.push_back(APValue(f));
  6202. CountElts++;
  6203. }
  6204. CountInits++;
  6205. }
  6206. return Success(Elements, E);
  6207. }
  6208. bool
  6209. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  6210. const VectorType *VT = E->getType()->getAs<VectorType>();
  6211. QualType EltTy = VT->getElementType();
  6212. APValue ZeroElement;
  6213. if (EltTy->isIntegerType())
  6214. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  6215. else
  6216. ZeroElement =
  6217. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  6218. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  6219. return Success(Elements, E);
  6220. }
  6221. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6222. VisitIgnoredValue(E->getSubExpr());
  6223. return ZeroInitialization(E);
  6224. }
  6225. //===----------------------------------------------------------------------===//
  6226. // Array Evaluation
  6227. //===----------------------------------------------------------------------===//
  6228. namespace {
  6229. class ArrayExprEvaluator
  6230. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  6231. const LValue &This;
  6232. APValue &Result;
  6233. public:
  6234. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  6235. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  6236. bool Success(const APValue &V, const Expr *E) {
  6237. assert((V.isArray() || V.isLValue()) &&
  6238. "expected array or string literal");
  6239. Result = V;
  6240. return true;
  6241. }
  6242. bool ZeroInitialization(const Expr *E) {
  6243. const ConstantArrayType *CAT =
  6244. Info.Ctx.getAsConstantArrayType(E->getType());
  6245. if (!CAT)
  6246. return Error(E);
  6247. Result = APValue(APValue::UninitArray(), 0,
  6248. CAT->getSize().getZExtValue());
  6249. if (!Result.hasArrayFiller()) return true;
  6250. // Zero-initialize all elements.
  6251. LValue Subobject = This;
  6252. Subobject.addArray(Info, E, CAT);
  6253. ImplicitValueInitExpr VIE(CAT->getElementType());
  6254. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  6255. }
  6256. bool VisitCallExpr(const CallExpr *E) {
  6257. return handleCallExpr(E, Result, &This);
  6258. }
  6259. bool VisitInitListExpr(const InitListExpr *E);
  6260. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  6261. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  6262. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  6263. const LValue &Subobject,
  6264. APValue *Value, QualType Type);
  6265. };
  6266. } // end anonymous namespace
  6267. static bool EvaluateArray(const Expr *E, const LValue &This,
  6268. APValue &Result, EvalInfo &Info) {
  6269. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  6270. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  6271. }
  6272. // Return true iff the given array filler may depend on the element index.
  6273. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  6274. // For now, just whitelist non-class value-initialization and initialization
  6275. // lists comprised of them.
  6276. if (isa<ImplicitValueInitExpr>(FillerExpr))
  6277. return false;
  6278. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  6279. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  6280. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  6281. return true;
  6282. }
  6283. return false;
  6284. }
  6285. return true;
  6286. }
  6287. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6288. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  6289. if (!CAT)
  6290. return Error(E);
  6291. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  6292. // an appropriately-typed string literal enclosed in braces.
  6293. if (E->isStringLiteralInit()) {
  6294. LValue LV;
  6295. if (!EvaluateLValue(E->getInit(0), LV, Info))
  6296. return false;
  6297. APValue Val;
  6298. LV.moveInto(Val);
  6299. return Success(Val, E);
  6300. }
  6301. bool Success = true;
  6302. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  6303. "zero-initialized array shouldn't have any initialized elts");
  6304. APValue Filler;
  6305. if (Result.isArray() && Result.hasArrayFiller())
  6306. Filler = Result.getArrayFiller();
  6307. unsigned NumEltsToInit = E->getNumInits();
  6308. unsigned NumElts = CAT->getSize().getZExtValue();
  6309. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  6310. // If the initializer might depend on the array index, run it for each
  6311. // array element.
  6312. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  6313. NumEltsToInit = NumElts;
  6314. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  6315. << NumEltsToInit << ".\n");
  6316. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  6317. // If the array was previously zero-initialized, preserve the
  6318. // zero-initialized values.
  6319. if (!Filler.isUninit()) {
  6320. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  6321. Result.getArrayInitializedElt(I) = Filler;
  6322. if (Result.hasArrayFiller())
  6323. Result.getArrayFiller() = Filler;
  6324. }
  6325. LValue Subobject = This;
  6326. Subobject.addArray(Info, E, CAT);
  6327. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  6328. const Expr *Init =
  6329. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  6330. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6331. Info, Subobject, Init) ||
  6332. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  6333. CAT->getElementType(), 1)) {
  6334. if (!Info.noteFailure())
  6335. return false;
  6336. Success = false;
  6337. }
  6338. }
  6339. if (!Result.hasArrayFiller())
  6340. return Success;
  6341. // If we get here, we have a trivial filler, which we can just evaluate
  6342. // once and splat over the rest of the array elements.
  6343. assert(FillerExpr && "no array filler for incomplete init list");
  6344. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  6345. FillerExpr) && Success;
  6346. }
  6347. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  6348. if (E->getCommonExpr() &&
  6349. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  6350. Info, E->getCommonExpr()->getSourceExpr()))
  6351. return false;
  6352. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  6353. uint64_t Elements = CAT->getSize().getZExtValue();
  6354. Result = APValue(APValue::UninitArray(), Elements, Elements);
  6355. LValue Subobject = This;
  6356. Subobject.addArray(Info, E, CAT);
  6357. bool Success = true;
  6358. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  6359. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6360. Info, Subobject, E->getSubExpr()) ||
  6361. !HandleLValueArrayAdjustment(Info, E, Subobject,
  6362. CAT->getElementType(), 1)) {
  6363. if (!Info.noteFailure())
  6364. return false;
  6365. Success = false;
  6366. }
  6367. }
  6368. return Success;
  6369. }
  6370. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6371. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  6372. }
  6373. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6374. const LValue &Subobject,
  6375. APValue *Value,
  6376. QualType Type) {
  6377. bool HadZeroInit = !Value->isUninit();
  6378. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  6379. unsigned N = CAT->getSize().getZExtValue();
  6380. // Preserve the array filler if we had prior zero-initialization.
  6381. APValue Filler =
  6382. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  6383. : APValue();
  6384. *Value = APValue(APValue::UninitArray(), N, N);
  6385. if (HadZeroInit)
  6386. for (unsigned I = 0; I != N; ++I)
  6387. Value->getArrayInitializedElt(I) = Filler;
  6388. // Initialize the elements.
  6389. LValue ArrayElt = Subobject;
  6390. ArrayElt.addArray(Info, E, CAT);
  6391. for (unsigned I = 0; I != N; ++I)
  6392. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  6393. CAT->getElementType()) ||
  6394. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  6395. CAT->getElementType(), 1))
  6396. return false;
  6397. return true;
  6398. }
  6399. if (!Type->isRecordType())
  6400. return Error(E);
  6401. return RecordExprEvaluator(Info, Subobject, *Value)
  6402. .VisitCXXConstructExpr(E, Type);
  6403. }
  6404. //===----------------------------------------------------------------------===//
  6405. // Integer Evaluation
  6406. //
  6407. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  6408. // types and back in constant folding. Integer values are thus represented
  6409. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  6410. //===----------------------------------------------------------------------===//
  6411. namespace {
  6412. class IntExprEvaluator
  6413. : public ExprEvaluatorBase<IntExprEvaluator> {
  6414. APValue &Result;
  6415. public:
  6416. IntExprEvaluator(EvalInfo &info, APValue &result)
  6417. : ExprEvaluatorBaseTy(info), Result(result) {}
  6418. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6419. assert(E->getType()->isIntegralOrEnumerationType() &&
  6420. "Invalid evaluation result.");
  6421. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  6422. "Invalid evaluation result.");
  6423. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6424. "Invalid evaluation result.");
  6425. Result = APValue(SI);
  6426. return true;
  6427. }
  6428. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6429. return Success(SI, E, Result);
  6430. }
  6431. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6432. assert(E->getType()->isIntegralOrEnumerationType() &&
  6433. "Invalid evaluation result.");
  6434. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6435. "Invalid evaluation result.");
  6436. Result = APValue(APSInt(I));
  6437. Result.getInt().setIsUnsigned(
  6438. E->getType()->isUnsignedIntegerOrEnumerationType());
  6439. return true;
  6440. }
  6441. bool Success(const llvm::APInt &I, const Expr *E) {
  6442. return Success(I, E, Result);
  6443. }
  6444. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6445. assert(E->getType()->isIntegralOrEnumerationType() &&
  6446. "Invalid evaluation result.");
  6447. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6448. return true;
  6449. }
  6450. bool Success(uint64_t Value, const Expr *E) {
  6451. return Success(Value, E, Result);
  6452. }
  6453. bool Success(CharUnits Size, const Expr *E) {
  6454. return Success(Size.getQuantity(), E);
  6455. }
  6456. bool Success(const APValue &V, const Expr *E) {
  6457. if (V.isLValue() || V.isAddrLabelDiff()) {
  6458. Result = V;
  6459. return true;
  6460. }
  6461. return Success(V.getInt(), E);
  6462. }
  6463. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6464. //===--------------------------------------------------------------------===//
  6465. // Visitor Methods
  6466. //===--------------------------------------------------------------------===//
  6467. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  6468. return Success(E->getValue(), E);
  6469. }
  6470. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  6471. return Success(E->getValue(), E);
  6472. }
  6473. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  6474. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  6475. if (CheckReferencedDecl(E, E->getDecl()))
  6476. return true;
  6477. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  6478. }
  6479. bool VisitMemberExpr(const MemberExpr *E) {
  6480. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  6481. VisitIgnoredBaseExpression(E->getBase());
  6482. return true;
  6483. }
  6484. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  6485. }
  6486. bool VisitCallExpr(const CallExpr *E);
  6487. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6488. bool VisitBinaryOperator(const BinaryOperator *E);
  6489. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  6490. bool VisitUnaryOperator(const UnaryOperator *E);
  6491. bool VisitCastExpr(const CastExpr* E);
  6492. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  6493. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  6494. return Success(E->getValue(), E);
  6495. }
  6496. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  6497. return Success(E->getValue(), E);
  6498. }
  6499. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  6500. if (Info.ArrayInitIndex == uint64_t(-1)) {
  6501. // We were asked to evaluate this subexpression independent of the
  6502. // enclosing ArrayInitLoopExpr. We can't do that.
  6503. Info.FFDiag(E);
  6504. return false;
  6505. }
  6506. return Success(Info.ArrayInitIndex, E);
  6507. }
  6508. // Note, GNU defines __null as an integer, not a pointer.
  6509. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  6510. return ZeroInitialization(E);
  6511. }
  6512. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  6513. return Success(E->getValue(), E);
  6514. }
  6515. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  6516. return Success(E->getValue(), E);
  6517. }
  6518. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  6519. return Success(E->getValue(), E);
  6520. }
  6521. bool VisitUnaryReal(const UnaryOperator *E);
  6522. bool VisitUnaryImag(const UnaryOperator *E);
  6523. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  6524. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  6525. // FIXME: Missing: array subscript of vector, member of vector
  6526. };
  6527. class FixedPointExprEvaluator
  6528. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  6529. APValue &Result;
  6530. public:
  6531. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  6532. : ExprEvaluatorBaseTy(info), Result(result) {}
  6533. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6534. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6535. assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
  6536. "Invalid evaluation result.");
  6537. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6538. "Invalid evaluation result.");
  6539. Result = APValue(SI);
  6540. return true;
  6541. }
  6542. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6543. return Success(SI, E, Result);
  6544. }
  6545. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6546. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6547. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6548. "Invalid evaluation result.");
  6549. Result = APValue(APSInt(I));
  6550. Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
  6551. return true;
  6552. }
  6553. bool Success(const llvm::APInt &I, const Expr *E) {
  6554. return Success(I, E, Result);
  6555. }
  6556. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6557. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6558. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6559. return true;
  6560. }
  6561. bool Success(uint64_t Value, const Expr *E) {
  6562. return Success(Value, E, Result);
  6563. }
  6564. bool Success(CharUnits Size, const Expr *E) {
  6565. return Success(Size.getQuantity(), E);
  6566. }
  6567. bool Success(const APValue &V, const Expr *E) {
  6568. if (V.isLValue() || V.isAddrLabelDiff()) {
  6569. Result = V;
  6570. return true;
  6571. }
  6572. return Success(V.getInt(), E);
  6573. }
  6574. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6575. //===--------------------------------------------------------------------===//
  6576. // Visitor Methods
  6577. //===--------------------------------------------------------------------===//
  6578. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  6579. return Success(E->getValue(), E);
  6580. }
  6581. bool VisitUnaryOperator(const UnaryOperator *E);
  6582. };
  6583. } // end anonymous namespace
  6584. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  6585. /// produce either the integer value or a pointer.
  6586. ///
  6587. /// GCC has a heinous extension which folds casts between pointer types and
  6588. /// pointer-sized integral types. We support this by allowing the evaluation of
  6589. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  6590. /// Some simple arithmetic on such values is supported (they are treated much
  6591. /// like char*).
  6592. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  6593. EvalInfo &Info) {
  6594. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  6595. return IntExprEvaluator(Info, Result).Visit(E);
  6596. }
  6597. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  6598. APValue Val;
  6599. if (!EvaluateIntegerOrLValue(E, Val, Info))
  6600. return false;
  6601. if (!Val.isInt()) {
  6602. // FIXME: It would be better to produce the diagnostic for casting
  6603. // a pointer to an integer.
  6604. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6605. return false;
  6606. }
  6607. Result = Val.getInt();
  6608. return true;
  6609. }
  6610. /// Check whether the given declaration can be directly converted to an integral
  6611. /// rvalue. If not, no diagnostic is produced; there are other things we can
  6612. /// try.
  6613. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  6614. // Enums are integer constant exprs.
  6615. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  6616. // Check for signedness/width mismatches between E type and ECD value.
  6617. bool SameSign = (ECD->getInitVal().isSigned()
  6618. == E->getType()->isSignedIntegerOrEnumerationType());
  6619. bool SameWidth = (ECD->getInitVal().getBitWidth()
  6620. == Info.Ctx.getIntWidth(E->getType()));
  6621. if (SameSign && SameWidth)
  6622. return Success(ECD->getInitVal(), E);
  6623. else {
  6624. // Get rid of mismatch (otherwise Success assertions will fail)
  6625. // by computing a new value matching the type of E.
  6626. llvm::APSInt Val = ECD->getInitVal();
  6627. if (!SameSign)
  6628. Val.setIsSigned(!ECD->getInitVal().isSigned());
  6629. if (!SameWidth)
  6630. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  6631. return Success(Val, E);
  6632. }
  6633. }
  6634. return false;
  6635. }
  6636. /// Values returned by __builtin_classify_type, chosen to match the values
  6637. /// produced by GCC's builtin.
  6638. enum class GCCTypeClass {
  6639. None = -1,
  6640. Void = 0,
  6641. Integer = 1,
  6642. // GCC reserves 2 for character types, but instead classifies them as
  6643. // integers.
  6644. Enum = 3,
  6645. Bool = 4,
  6646. Pointer = 5,
  6647. // GCC reserves 6 for references, but appears to never use it (because
  6648. // expressions never have reference type, presumably).
  6649. PointerToDataMember = 7,
  6650. RealFloat = 8,
  6651. Complex = 9,
  6652. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  6653. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6654. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  6655. // uses 12 for that purpose, same as for a class or struct. Maybe it
  6656. // internally implements a pointer to member as a struct? Who knows.
  6657. PointerToMemberFunction = 12, // Not a bug, see above.
  6658. ClassOrStruct = 12,
  6659. Union = 13,
  6660. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  6661. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6662. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  6663. // literals.
  6664. };
  6665. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6666. /// as GCC.
  6667. static GCCTypeClass
  6668. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  6669. assert(!T->isDependentType() && "unexpected dependent type");
  6670. QualType CanTy = T.getCanonicalType();
  6671. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  6672. switch (CanTy->getTypeClass()) {
  6673. #define TYPE(ID, BASE)
  6674. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6675. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  6676. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6677. #include "clang/AST/TypeNodes.def"
  6678. case Type::Auto:
  6679. case Type::DeducedTemplateSpecialization:
  6680. llvm_unreachable("unexpected non-canonical or dependent type");
  6681. case Type::Builtin:
  6682. switch (BT->getKind()) {
  6683. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  6684. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  6685. case BuiltinType::ID: return GCCTypeClass::Integer;
  6686. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  6687. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  6688. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  6689. case BuiltinType::ID: break;
  6690. #include "clang/AST/BuiltinTypes.def"
  6691. case BuiltinType::Void:
  6692. return GCCTypeClass::Void;
  6693. case BuiltinType::Bool:
  6694. return GCCTypeClass::Bool;
  6695. case BuiltinType::Char_U:
  6696. case BuiltinType::UChar:
  6697. case BuiltinType::WChar_U:
  6698. case BuiltinType::Char8:
  6699. case BuiltinType::Char16:
  6700. case BuiltinType::Char32:
  6701. case BuiltinType::UShort:
  6702. case BuiltinType::UInt:
  6703. case BuiltinType::ULong:
  6704. case BuiltinType::ULongLong:
  6705. case BuiltinType::UInt128:
  6706. return GCCTypeClass::Integer;
  6707. case BuiltinType::UShortAccum:
  6708. case BuiltinType::UAccum:
  6709. case BuiltinType::ULongAccum:
  6710. case BuiltinType::UShortFract:
  6711. case BuiltinType::UFract:
  6712. case BuiltinType::ULongFract:
  6713. case BuiltinType::SatUShortAccum:
  6714. case BuiltinType::SatUAccum:
  6715. case BuiltinType::SatULongAccum:
  6716. case BuiltinType::SatUShortFract:
  6717. case BuiltinType::SatUFract:
  6718. case BuiltinType::SatULongFract:
  6719. return GCCTypeClass::None;
  6720. case BuiltinType::NullPtr:
  6721. case BuiltinType::ObjCId:
  6722. case BuiltinType::ObjCClass:
  6723. case BuiltinType::ObjCSel:
  6724. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6725. case BuiltinType::Id:
  6726. #include "clang/Basic/OpenCLImageTypes.def"
  6727. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  6728. case BuiltinType::Id:
  6729. #include "clang/Basic/OpenCLExtensionTypes.def"
  6730. case BuiltinType::OCLSampler:
  6731. case BuiltinType::OCLEvent:
  6732. case BuiltinType::OCLClkEvent:
  6733. case BuiltinType::OCLQueue:
  6734. case BuiltinType::OCLReserveID:
  6735. return GCCTypeClass::None;
  6736. case BuiltinType::Dependent:
  6737. llvm_unreachable("unexpected dependent type");
  6738. };
  6739. llvm_unreachable("unexpected placeholder type");
  6740. case Type::Enum:
  6741. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  6742. case Type::Pointer:
  6743. case Type::ConstantArray:
  6744. case Type::VariableArray:
  6745. case Type::IncompleteArray:
  6746. case Type::FunctionNoProto:
  6747. case Type::FunctionProto:
  6748. return GCCTypeClass::Pointer;
  6749. case Type::MemberPointer:
  6750. return CanTy->isMemberDataPointerType()
  6751. ? GCCTypeClass::PointerToDataMember
  6752. : GCCTypeClass::PointerToMemberFunction;
  6753. case Type::Complex:
  6754. return GCCTypeClass::Complex;
  6755. case Type::Record:
  6756. return CanTy->isUnionType() ? GCCTypeClass::Union
  6757. : GCCTypeClass::ClassOrStruct;
  6758. case Type::Atomic:
  6759. // GCC classifies _Atomic T the same as T.
  6760. return EvaluateBuiltinClassifyType(
  6761. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  6762. case Type::BlockPointer:
  6763. case Type::Vector:
  6764. case Type::ExtVector:
  6765. case Type::ObjCObject:
  6766. case Type::ObjCInterface:
  6767. case Type::ObjCObjectPointer:
  6768. case Type::Pipe:
  6769. // GCC classifies vectors as None. We follow its lead and classify all
  6770. // other types that don't fit into the regular classification the same way.
  6771. return GCCTypeClass::None;
  6772. case Type::LValueReference:
  6773. case Type::RValueReference:
  6774. llvm_unreachable("invalid type for expression");
  6775. }
  6776. llvm_unreachable("unexpected type class");
  6777. }
  6778. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6779. /// as GCC.
  6780. static GCCTypeClass
  6781. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  6782. // If no argument was supplied, default to None. This isn't
  6783. // ideal, however it is what gcc does.
  6784. if (E->getNumArgs() == 0)
  6785. return GCCTypeClass::None;
  6786. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  6787. // being an ICE, but still folds it to a constant using the type of the first
  6788. // argument.
  6789. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  6790. }
  6791. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  6792. /// __builtin_constant_p when applied to the given lvalue.
  6793. ///
  6794. /// An lvalue is only "constant" if it is a pointer or reference to the first
  6795. /// character of a string literal.
  6796. template<typename LValue>
  6797. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  6798. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  6799. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  6800. }
  6801. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  6802. /// GCC as we can manage.
  6803. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  6804. QualType ArgType = Arg->getType();
  6805. // __builtin_constant_p always has one operand. The rules which gcc follows
  6806. // are not precisely documented, but are as follows:
  6807. //
  6808. // - If the operand is of integral, floating, complex or enumeration type,
  6809. // and can be folded to a known value of that type, it returns 1.
  6810. // - If the operand and can be folded to a pointer to the first character
  6811. // of a string literal (or such a pointer cast to an integral type), it
  6812. // returns 1.
  6813. //
  6814. // Otherwise, it returns 0.
  6815. //
  6816. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  6817. // its support for this does not currently work.
  6818. if (ArgType->isIntegralOrEnumerationType()) {
  6819. Expr::EvalResult Result;
  6820. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  6821. return false;
  6822. APValue &V = Result.Val;
  6823. if (V.getKind() == APValue::Int)
  6824. return true;
  6825. if (V.getKind() == APValue::LValue)
  6826. return EvaluateBuiltinConstantPForLValue(V);
  6827. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  6828. return Arg->isEvaluatable(Ctx);
  6829. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  6830. LValue LV;
  6831. Expr::EvalStatus Status;
  6832. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  6833. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  6834. : EvaluatePointer(Arg, LV, Info)) &&
  6835. !Status.HasSideEffects)
  6836. return EvaluateBuiltinConstantPForLValue(LV);
  6837. }
  6838. // Anything else isn't considered to be sufficiently constant.
  6839. return false;
  6840. }
  6841. /// Retrieves the "underlying object type" of the given expression,
  6842. /// as used by __builtin_object_size.
  6843. static QualType getObjectType(APValue::LValueBase B) {
  6844. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  6845. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  6846. return VD->getType();
  6847. } else if (const Expr *E = B.get<const Expr*>()) {
  6848. if (isa<CompoundLiteralExpr>(E))
  6849. return E->getType();
  6850. }
  6851. return QualType();
  6852. }
  6853. /// A more selective version of E->IgnoreParenCasts for
  6854. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  6855. /// to change the type of E.
  6856. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  6857. ///
  6858. /// Always returns an RValue with a pointer representation.
  6859. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  6860. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6861. auto *NoParens = E->IgnoreParens();
  6862. auto *Cast = dyn_cast<CastExpr>(NoParens);
  6863. if (Cast == nullptr)
  6864. return NoParens;
  6865. // We only conservatively allow a few kinds of casts, because this code is
  6866. // inherently a simple solution that seeks to support the common case.
  6867. auto CastKind = Cast->getCastKind();
  6868. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  6869. CastKind != CK_AddressSpaceConversion)
  6870. return NoParens;
  6871. auto *SubExpr = Cast->getSubExpr();
  6872. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  6873. return NoParens;
  6874. return ignorePointerCastsAndParens(SubExpr);
  6875. }
  6876. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  6877. /// record layout. e.g.
  6878. /// struct { struct { int a, b; } fst, snd; } obj;
  6879. /// obj.fst // no
  6880. /// obj.snd // yes
  6881. /// obj.fst.a // no
  6882. /// obj.fst.b // no
  6883. /// obj.snd.a // no
  6884. /// obj.snd.b // yes
  6885. ///
  6886. /// Please note: this function is specialized for how __builtin_object_size
  6887. /// views "objects".
  6888. ///
  6889. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  6890. /// correct result, it will always return true.
  6891. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  6892. assert(!LVal.Designator.Invalid);
  6893. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  6894. const RecordDecl *Parent = FD->getParent();
  6895. Invalid = Parent->isInvalidDecl();
  6896. if (Invalid || Parent->isUnion())
  6897. return true;
  6898. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  6899. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  6900. };
  6901. auto &Base = LVal.getLValueBase();
  6902. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  6903. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  6904. bool Invalid;
  6905. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6906. return Invalid;
  6907. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  6908. for (auto *FD : IFD->chain()) {
  6909. bool Invalid;
  6910. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  6911. return Invalid;
  6912. }
  6913. }
  6914. }
  6915. unsigned I = 0;
  6916. QualType BaseType = getType(Base);
  6917. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  6918. // If we don't know the array bound, conservatively assume we're looking at
  6919. // the final array element.
  6920. ++I;
  6921. if (BaseType->isIncompleteArrayType())
  6922. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  6923. else
  6924. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  6925. }
  6926. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  6927. const auto &Entry = LVal.Designator.Entries[I];
  6928. if (BaseType->isArrayType()) {
  6929. // Because __builtin_object_size treats arrays as objects, we can ignore
  6930. // the index iff this is the last array in the Designator.
  6931. if (I + 1 == E)
  6932. return true;
  6933. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  6934. uint64_t Index = Entry.ArrayIndex;
  6935. if (Index + 1 != CAT->getSize())
  6936. return false;
  6937. BaseType = CAT->getElementType();
  6938. } else if (BaseType->isAnyComplexType()) {
  6939. const auto *CT = BaseType->castAs<ComplexType>();
  6940. uint64_t Index = Entry.ArrayIndex;
  6941. if (Index != 1)
  6942. return false;
  6943. BaseType = CT->getElementType();
  6944. } else if (auto *FD = getAsField(Entry)) {
  6945. bool Invalid;
  6946. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6947. return Invalid;
  6948. BaseType = FD->getType();
  6949. } else {
  6950. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  6951. return false;
  6952. }
  6953. }
  6954. return true;
  6955. }
  6956. /// Tests to see if the LValue has a user-specified designator (that isn't
  6957. /// necessarily valid). Note that this always returns 'true' if the LValue has
  6958. /// an unsized array as its first designator entry, because there's currently no
  6959. /// way to tell if the user typed *foo or foo[0].
  6960. static bool refersToCompleteObject(const LValue &LVal) {
  6961. if (LVal.Designator.Invalid)
  6962. return false;
  6963. if (!LVal.Designator.Entries.empty())
  6964. return LVal.Designator.isMostDerivedAnUnsizedArray();
  6965. if (!LVal.InvalidBase)
  6966. return true;
  6967. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  6968. // the LValueBase.
  6969. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  6970. return !E || !isa<MemberExpr>(E);
  6971. }
  6972. /// Attempts to detect a user writing into a piece of memory that's impossible
  6973. /// to figure out the size of by just using types.
  6974. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  6975. const SubobjectDesignator &Designator = LVal.Designator;
  6976. // Notes:
  6977. // - Users can only write off of the end when we have an invalid base. Invalid
  6978. // bases imply we don't know where the memory came from.
  6979. // - We used to be a bit more aggressive here; we'd only be conservative if
  6980. // the array at the end was flexible, or if it had 0 or 1 elements. This
  6981. // broke some common standard library extensions (PR30346), but was
  6982. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  6983. // with some sort of whitelist. OTOH, it seems that GCC is always
  6984. // conservative with the last element in structs (if it's an array), so our
  6985. // current behavior is more compatible than a whitelisting approach would
  6986. // be.
  6987. return LVal.InvalidBase &&
  6988. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  6989. Designator.MostDerivedIsArrayElement &&
  6990. isDesignatorAtObjectEnd(Ctx, LVal);
  6991. }
  6992. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  6993. /// Fails if the conversion would cause loss of precision.
  6994. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  6995. CharUnits &Result) {
  6996. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  6997. if (Int.ugt(CharUnitsMax))
  6998. return false;
  6999. Result = CharUnits::fromQuantity(Int.getZExtValue());
  7000. return true;
  7001. }
  7002. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  7003. /// determine how many bytes exist from the beginning of the object to either
  7004. /// the end of the current subobject, or the end of the object itself, depending
  7005. /// on what the LValue looks like + the value of Type.
  7006. ///
  7007. /// If this returns false, the value of Result is undefined.
  7008. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  7009. unsigned Type, const LValue &LVal,
  7010. CharUnits &EndOffset) {
  7011. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  7012. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  7013. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  7014. return false;
  7015. return HandleSizeof(Info, ExprLoc, Ty, Result);
  7016. };
  7017. // We want to evaluate the size of the entire object. This is a valid fallback
  7018. // for when Type=1 and the designator is invalid, because we're asked for an
  7019. // upper-bound.
  7020. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  7021. // Type=3 wants a lower bound, so we can't fall back to this.
  7022. if (Type == 3 && !DetermineForCompleteObject)
  7023. return false;
  7024. llvm::APInt APEndOffset;
  7025. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7026. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7027. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7028. if (LVal.InvalidBase)
  7029. return false;
  7030. QualType BaseTy = getObjectType(LVal.getLValueBase());
  7031. return CheckedHandleSizeof(BaseTy, EndOffset);
  7032. }
  7033. // We want to evaluate the size of a subobject.
  7034. const SubobjectDesignator &Designator = LVal.Designator;
  7035. // The following is a moderately common idiom in C:
  7036. //
  7037. // struct Foo { int a; char c[1]; };
  7038. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  7039. // strcpy(&F->c[0], Bar);
  7040. //
  7041. // In order to not break too much legacy code, we need to support it.
  7042. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  7043. // If we can resolve this to an alloc_size call, we can hand that back,
  7044. // because we know for certain how many bytes there are to write to.
  7045. llvm::APInt APEndOffset;
  7046. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7047. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7048. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7049. // If we cannot determine the size of the initial allocation, then we can't
  7050. // given an accurate upper-bound. However, we are still able to give
  7051. // conservative lower-bounds for Type=3.
  7052. if (Type == 1)
  7053. return false;
  7054. }
  7055. CharUnits BytesPerElem;
  7056. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  7057. return false;
  7058. // According to the GCC documentation, we want the size of the subobject
  7059. // denoted by the pointer. But that's not quite right -- what we actually
  7060. // want is the size of the immediately-enclosing array, if there is one.
  7061. int64_t ElemsRemaining;
  7062. if (Designator.MostDerivedIsArrayElement &&
  7063. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  7064. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  7065. uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
  7066. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  7067. } else {
  7068. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  7069. }
  7070. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  7071. return true;
  7072. }
  7073. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  7074. /// returns true and stores the result in @p Size.
  7075. ///
  7076. /// If @p WasError is non-null, this will report whether the failure to evaluate
  7077. /// is to be treated as an Error in IntExprEvaluator.
  7078. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  7079. EvalInfo &Info, uint64_t &Size) {
  7080. // Determine the denoted object.
  7081. LValue LVal;
  7082. {
  7083. // The operand of __builtin_object_size is never evaluated for side-effects.
  7084. // If there are any, but we can determine the pointed-to object anyway, then
  7085. // ignore the side-effects.
  7086. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7087. IgnoreSideEffectsRAII Fold(Info);
  7088. if (E->isGLValue()) {
  7089. // It's possible for us to be given GLValues if we're called via
  7090. // Expr::tryEvaluateObjectSize.
  7091. APValue RVal;
  7092. if (!EvaluateAsRValue(Info, E, RVal))
  7093. return false;
  7094. LVal.setFrom(Info.Ctx, RVal);
  7095. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  7096. /*InvalidBaseOK=*/true))
  7097. return false;
  7098. }
  7099. // If we point to before the start of the object, there are no accessible
  7100. // bytes.
  7101. if (LVal.getLValueOffset().isNegative()) {
  7102. Size = 0;
  7103. return true;
  7104. }
  7105. CharUnits EndOffset;
  7106. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  7107. return false;
  7108. // If we've fallen outside of the end offset, just pretend there's nothing to
  7109. // write to/read from.
  7110. if (EndOffset <= LVal.getLValueOffset())
  7111. Size = 0;
  7112. else
  7113. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  7114. return true;
  7115. }
  7116. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7117. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7118. return VisitBuiltinCallExpr(E, BuiltinOp);
  7119. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7120. }
  7121. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7122. unsigned BuiltinOp) {
  7123. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  7124. default:
  7125. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7126. case Builtin::BI__builtin_object_size: {
  7127. // The type was checked when we built the expression.
  7128. unsigned Type =
  7129. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7130. assert(Type <= 3 && "unexpected type");
  7131. uint64_t Size;
  7132. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  7133. return Success(Size, E);
  7134. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  7135. return Success((Type & 2) ? 0 : -1, E);
  7136. // Expression had no side effects, but we couldn't statically determine the
  7137. // size of the referenced object.
  7138. switch (Info.EvalMode) {
  7139. case EvalInfo::EM_ConstantExpression:
  7140. case EvalInfo::EM_PotentialConstantExpression:
  7141. case EvalInfo::EM_ConstantFold:
  7142. case EvalInfo::EM_EvaluateForOverflow:
  7143. case EvalInfo::EM_IgnoreSideEffects:
  7144. // Leave it to IR generation.
  7145. return Error(E);
  7146. case EvalInfo::EM_ConstantExpressionUnevaluated:
  7147. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  7148. // Reduce it to a constant now.
  7149. return Success((Type & 2) ? 0 : -1, E);
  7150. }
  7151. llvm_unreachable("unexpected EvalMode");
  7152. }
  7153. case Builtin::BI__builtin_os_log_format_buffer_size: {
  7154. analyze_os_log::OSLogBufferLayout Layout;
  7155. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  7156. return Success(Layout.size().getQuantity(), E);
  7157. }
  7158. case Builtin::BI__builtin_bswap16:
  7159. case Builtin::BI__builtin_bswap32:
  7160. case Builtin::BI__builtin_bswap64: {
  7161. APSInt Val;
  7162. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7163. return false;
  7164. return Success(Val.byteSwap(), E);
  7165. }
  7166. case Builtin::BI__builtin_classify_type:
  7167. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  7168. case Builtin::BI__builtin_clrsb:
  7169. case Builtin::BI__builtin_clrsbl:
  7170. case Builtin::BI__builtin_clrsbll: {
  7171. APSInt Val;
  7172. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7173. return false;
  7174. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  7175. }
  7176. case Builtin::BI__builtin_clz:
  7177. case Builtin::BI__builtin_clzl:
  7178. case Builtin::BI__builtin_clzll:
  7179. case Builtin::BI__builtin_clzs: {
  7180. APSInt Val;
  7181. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7182. return false;
  7183. if (!Val)
  7184. return Error(E);
  7185. return Success(Val.countLeadingZeros(), E);
  7186. }
  7187. case Builtin::BI__builtin_constant_p:
  7188. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  7189. case Builtin::BI__builtin_ctz:
  7190. case Builtin::BI__builtin_ctzl:
  7191. case Builtin::BI__builtin_ctzll:
  7192. case Builtin::BI__builtin_ctzs: {
  7193. APSInt Val;
  7194. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7195. return false;
  7196. if (!Val)
  7197. return Error(E);
  7198. return Success(Val.countTrailingZeros(), E);
  7199. }
  7200. case Builtin::BI__builtin_eh_return_data_regno: {
  7201. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7202. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  7203. return Success(Operand, E);
  7204. }
  7205. case Builtin::BI__builtin_expect:
  7206. return Visit(E->getArg(0));
  7207. case Builtin::BI__builtin_ffs:
  7208. case Builtin::BI__builtin_ffsl:
  7209. case Builtin::BI__builtin_ffsll: {
  7210. APSInt Val;
  7211. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7212. return false;
  7213. unsigned N = Val.countTrailingZeros();
  7214. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  7215. }
  7216. case Builtin::BI__builtin_fpclassify: {
  7217. APFloat Val(0.0);
  7218. if (!EvaluateFloat(E->getArg(5), Val, Info))
  7219. return false;
  7220. unsigned Arg;
  7221. switch (Val.getCategory()) {
  7222. case APFloat::fcNaN: Arg = 0; break;
  7223. case APFloat::fcInfinity: Arg = 1; break;
  7224. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  7225. case APFloat::fcZero: Arg = 4; break;
  7226. }
  7227. return Visit(E->getArg(Arg));
  7228. }
  7229. case Builtin::BI__builtin_isinf_sign: {
  7230. APFloat Val(0.0);
  7231. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7232. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  7233. }
  7234. case Builtin::BI__builtin_isinf: {
  7235. APFloat Val(0.0);
  7236. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7237. Success(Val.isInfinity() ? 1 : 0, E);
  7238. }
  7239. case Builtin::BI__builtin_isfinite: {
  7240. APFloat Val(0.0);
  7241. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7242. Success(Val.isFinite() ? 1 : 0, E);
  7243. }
  7244. case Builtin::BI__builtin_isnan: {
  7245. APFloat Val(0.0);
  7246. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7247. Success(Val.isNaN() ? 1 : 0, E);
  7248. }
  7249. case Builtin::BI__builtin_isnormal: {
  7250. APFloat Val(0.0);
  7251. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7252. Success(Val.isNormal() ? 1 : 0, E);
  7253. }
  7254. case Builtin::BI__builtin_parity:
  7255. case Builtin::BI__builtin_parityl:
  7256. case Builtin::BI__builtin_parityll: {
  7257. APSInt Val;
  7258. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7259. return false;
  7260. return Success(Val.countPopulation() % 2, E);
  7261. }
  7262. case Builtin::BI__builtin_popcount:
  7263. case Builtin::BI__builtin_popcountl:
  7264. case Builtin::BI__builtin_popcountll: {
  7265. APSInt Val;
  7266. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7267. return false;
  7268. return Success(Val.countPopulation(), E);
  7269. }
  7270. case Builtin::BIstrlen:
  7271. case Builtin::BIwcslen:
  7272. // A call to strlen is not a constant expression.
  7273. if (Info.getLangOpts().CPlusPlus11)
  7274. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7275. << /*isConstexpr*/0 << /*isConstructor*/0
  7276. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7277. else
  7278. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7279. LLVM_FALLTHROUGH;
  7280. case Builtin::BI__builtin_strlen:
  7281. case Builtin::BI__builtin_wcslen: {
  7282. // As an extension, we support __builtin_strlen() as a constant expression,
  7283. // and support folding strlen() to a constant.
  7284. LValue String;
  7285. if (!EvaluatePointer(E->getArg(0), String, Info))
  7286. return false;
  7287. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7288. // Fast path: if it's a string literal, search the string value.
  7289. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  7290. String.getLValueBase().dyn_cast<const Expr *>())) {
  7291. // The string literal may have embedded null characters. Find the first
  7292. // one and truncate there.
  7293. StringRef Str = S->getBytes();
  7294. int64_t Off = String.Offset.getQuantity();
  7295. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  7296. S->getCharByteWidth() == 1 &&
  7297. // FIXME: Add fast-path for wchar_t too.
  7298. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  7299. Str = Str.substr(Off);
  7300. StringRef::size_type Pos = Str.find(0);
  7301. if (Pos != StringRef::npos)
  7302. Str = Str.substr(0, Pos);
  7303. return Success(Str.size(), E);
  7304. }
  7305. // Fall through to slow path to issue appropriate diagnostic.
  7306. }
  7307. // Slow path: scan the bytes of the string looking for the terminating 0.
  7308. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  7309. APValue Char;
  7310. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  7311. !Char.isInt())
  7312. return false;
  7313. if (!Char.getInt())
  7314. return Success(Strlen, E);
  7315. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  7316. return false;
  7317. }
  7318. }
  7319. case Builtin::BIstrcmp:
  7320. case Builtin::BIwcscmp:
  7321. case Builtin::BIstrncmp:
  7322. case Builtin::BIwcsncmp:
  7323. case Builtin::BImemcmp:
  7324. case Builtin::BIwmemcmp:
  7325. // A call to strlen is not a constant expression.
  7326. if (Info.getLangOpts().CPlusPlus11)
  7327. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7328. << /*isConstexpr*/0 << /*isConstructor*/0
  7329. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7330. else
  7331. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7332. LLVM_FALLTHROUGH;
  7333. case Builtin::BI__builtin_strcmp:
  7334. case Builtin::BI__builtin_wcscmp:
  7335. case Builtin::BI__builtin_strncmp:
  7336. case Builtin::BI__builtin_wcsncmp:
  7337. case Builtin::BI__builtin_memcmp:
  7338. case Builtin::BI__builtin_wmemcmp: {
  7339. LValue String1, String2;
  7340. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  7341. !EvaluatePointer(E->getArg(1), String2, Info))
  7342. return false;
  7343. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7344. uint64_t MaxLength = uint64_t(-1);
  7345. if (BuiltinOp != Builtin::BIstrcmp &&
  7346. BuiltinOp != Builtin::BIwcscmp &&
  7347. BuiltinOp != Builtin::BI__builtin_strcmp &&
  7348. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  7349. APSInt N;
  7350. if (!EvaluateInteger(E->getArg(2), N, Info))
  7351. return false;
  7352. MaxLength = N.getExtValue();
  7353. }
  7354. bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
  7355. BuiltinOp != Builtin::BIwmemcmp &&
  7356. BuiltinOp != Builtin::BI__builtin_memcmp &&
  7357. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  7358. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  7359. BuiltinOp == Builtin::BIwcsncmp ||
  7360. BuiltinOp == Builtin::BIwmemcmp ||
  7361. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  7362. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  7363. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  7364. for (; MaxLength; --MaxLength) {
  7365. APValue Char1, Char2;
  7366. if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
  7367. !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
  7368. !Char1.isInt() || !Char2.isInt())
  7369. return false;
  7370. if (Char1.getInt() != Char2.getInt()) {
  7371. if (IsWide) // wmemcmp compares with wchar_t signedness.
  7372. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  7373. // memcmp always compares unsigned chars.
  7374. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  7375. }
  7376. if (StopAtNull && !Char1.getInt())
  7377. return Success(0, E);
  7378. assert(!(StopAtNull && !Char2.getInt()));
  7379. if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
  7380. !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
  7381. return false;
  7382. }
  7383. // We hit the strncmp / memcmp limit.
  7384. return Success(0, E);
  7385. }
  7386. case Builtin::BI__atomic_always_lock_free:
  7387. case Builtin::BI__atomic_is_lock_free:
  7388. case Builtin::BI__c11_atomic_is_lock_free: {
  7389. APSInt SizeVal;
  7390. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  7391. return false;
  7392. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  7393. // of two less than the maximum inline atomic width, we know it is
  7394. // lock-free. If the size isn't a power of two, or greater than the
  7395. // maximum alignment where we promote atomics, we know it is not lock-free
  7396. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  7397. // the answer can only be determined at runtime; for example, 16-byte
  7398. // atomics have lock-free implementations on some, but not all,
  7399. // x86-64 processors.
  7400. // Check power-of-two.
  7401. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  7402. if (Size.isPowerOfTwo()) {
  7403. // Check against inlining width.
  7404. unsigned InlineWidthBits =
  7405. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  7406. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  7407. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  7408. Size == CharUnits::One() ||
  7409. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  7410. Expr::NPC_NeverValueDependent))
  7411. // OK, we will inline appropriately-aligned operations of this size,
  7412. // and _Atomic(T) is appropriately-aligned.
  7413. return Success(1, E);
  7414. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  7415. castAs<PointerType>()->getPointeeType();
  7416. if (!PointeeType->isIncompleteType() &&
  7417. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  7418. // OK, we will inline operations on this object.
  7419. return Success(1, E);
  7420. }
  7421. }
  7422. }
  7423. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  7424. Success(0, E) : Error(E);
  7425. }
  7426. case Builtin::BIomp_is_initial_device:
  7427. // We can decide statically which value the runtime would return if called.
  7428. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  7429. case Builtin::BI__builtin_add_overflow:
  7430. case Builtin::BI__builtin_sub_overflow:
  7431. case Builtin::BI__builtin_mul_overflow:
  7432. case Builtin::BI__builtin_sadd_overflow:
  7433. case Builtin::BI__builtin_uadd_overflow:
  7434. case Builtin::BI__builtin_uaddl_overflow:
  7435. case Builtin::BI__builtin_uaddll_overflow:
  7436. case Builtin::BI__builtin_usub_overflow:
  7437. case Builtin::BI__builtin_usubl_overflow:
  7438. case Builtin::BI__builtin_usubll_overflow:
  7439. case Builtin::BI__builtin_umul_overflow:
  7440. case Builtin::BI__builtin_umull_overflow:
  7441. case Builtin::BI__builtin_umulll_overflow:
  7442. case Builtin::BI__builtin_saddl_overflow:
  7443. case Builtin::BI__builtin_saddll_overflow:
  7444. case Builtin::BI__builtin_ssub_overflow:
  7445. case Builtin::BI__builtin_ssubl_overflow:
  7446. case Builtin::BI__builtin_ssubll_overflow:
  7447. case Builtin::BI__builtin_smul_overflow:
  7448. case Builtin::BI__builtin_smull_overflow:
  7449. case Builtin::BI__builtin_smulll_overflow: {
  7450. LValue ResultLValue;
  7451. APSInt LHS, RHS;
  7452. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  7453. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  7454. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  7455. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  7456. return false;
  7457. APSInt Result;
  7458. bool DidOverflow = false;
  7459. // If the types don't have to match, enlarge all 3 to the largest of them.
  7460. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7461. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7462. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7463. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  7464. ResultType->isSignedIntegerOrEnumerationType();
  7465. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  7466. ResultType->isSignedIntegerOrEnumerationType();
  7467. uint64_t LHSSize = LHS.getBitWidth();
  7468. uint64_t RHSSize = RHS.getBitWidth();
  7469. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  7470. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  7471. // Add an additional bit if the signedness isn't uniformly agreed to. We
  7472. // could do this ONLY if there is a signed and an unsigned that both have
  7473. // MaxBits, but the code to check that is pretty nasty. The issue will be
  7474. // caught in the shrink-to-result later anyway.
  7475. if (IsSigned && !AllSigned)
  7476. ++MaxBits;
  7477. LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
  7478. !IsSigned);
  7479. RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
  7480. !IsSigned);
  7481. Result = APSInt(MaxBits, !IsSigned);
  7482. }
  7483. // Find largest int.
  7484. switch (BuiltinOp) {
  7485. default:
  7486. llvm_unreachable("Invalid value for BuiltinOp");
  7487. case Builtin::BI__builtin_add_overflow:
  7488. case Builtin::BI__builtin_sadd_overflow:
  7489. case Builtin::BI__builtin_saddl_overflow:
  7490. case Builtin::BI__builtin_saddll_overflow:
  7491. case Builtin::BI__builtin_uadd_overflow:
  7492. case Builtin::BI__builtin_uaddl_overflow:
  7493. case Builtin::BI__builtin_uaddll_overflow:
  7494. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  7495. : LHS.uadd_ov(RHS, DidOverflow);
  7496. break;
  7497. case Builtin::BI__builtin_sub_overflow:
  7498. case Builtin::BI__builtin_ssub_overflow:
  7499. case Builtin::BI__builtin_ssubl_overflow:
  7500. case Builtin::BI__builtin_ssubll_overflow:
  7501. case Builtin::BI__builtin_usub_overflow:
  7502. case Builtin::BI__builtin_usubl_overflow:
  7503. case Builtin::BI__builtin_usubll_overflow:
  7504. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  7505. : LHS.usub_ov(RHS, DidOverflow);
  7506. break;
  7507. case Builtin::BI__builtin_mul_overflow:
  7508. case Builtin::BI__builtin_smul_overflow:
  7509. case Builtin::BI__builtin_smull_overflow:
  7510. case Builtin::BI__builtin_smulll_overflow:
  7511. case Builtin::BI__builtin_umul_overflow:
  7512. case Builtin::BI__builtin_umull_overflow:
  7513. case Builtin::BI__builtin_umulll_overflow:
  7514. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  7515. : LHS.umul_ov(RHS, DidOverflow);
  7516. break;
  7517. }
  7518. // In the case where multiple sizes are allowed, truncate and see if
  7519. // the values are the same.
  7520. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7521. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7522. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7523. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  7524. // since it will give us the behavior of a TruncOrSelf in the case where
  7525. // its parameter <= its size. We previously set Result to be at least the
  7526. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  7527. // will work exactly like TruncOrSelf.
  7528. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  7529. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  7530. if (!APSInt::isSameValue(Temp, Result))
  7531. DidOverflow = true;
  7532. Result = Temp;
  7533. }
  7534. APValue APV{Result};
  7535. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  7536. return false;
  7537. return Success(DidOverflow, E);
  7538. }
  7539. }
  7540. }
  7541. /// Determine whether this is a pointer past the end of the complete
  7542. /// object referred to by the lvalue.
  7543. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  7544. const LValue &LV) {
  7545. // A null pointer can be viewed as being "past the end" but we don't
  7546. // choose to look at it that way here.
  7547. if (!LV.getLValueBase())
  7548. return false;
  7549. // If the designator is valid and refers to a subobject, we're not pointing
  7550. // past the end.
  7551. if (!LV.getLValueDesignator().Invalid &&
  7552. !LV.getLValueDesignator().isOnePastTheEnd())
  7553. return false;
  7554. // A pointer to an incomplete type might be past-the-end if the type's size is
  7555. // zero. We cannot tell because the type is incomplete.
  7556. QualType Ty = getType(LV.getLValueBase());
  7557. if (Ty->isIncompleteType())
  7558. return true;
  7559. // We're a past-the-end pointer if we point to the byte after the object,
  7560. // no matter what our type or path is.
  7561. auto Size = Ctx.getTypeSizeInChars(Ty);
  7562. return LV.getLValueOffset() == Size;
  7563. }
  7564. namespace {
  7565. /// Data recursive integer evaluator of certain binary operators.
  7566. ///
  7567. /// We use a data recursive algorithm for binary operators so that we are able
  7568. /// to handle extreme cases of chained binary operators without causing stack
  7569. /// overflow.
  7570. class DataRecursiveIntBinOpEvaluator {
  7571. struct EvalResult {
  7572. APValue Val;
  7573. bool Failed;
  7574. EvalResult() : Failed(false) { }
  7575. void swap(EvalResult &RHS) {
  7576. Val.swap(RHS.Val);
  7577. Failed = RHS.Failed;
  7578. RHS.Failed = false;
  7579. }
  7580. };
  7581. struct Job {
  7582. const Expr *E;
  7583. EvalResult LHSResult; // meaningful only for binary operator expression.
  7584. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  7585. Job() = default;
  7586. Job(Job &&) = default;
  7587. void startSpeculativeEval(EvalInfo &Info) {
  7588. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  7589. }
  7590. private:
  7591. SpeculativeEvaluationRAII SpecEvalRAII;
  7592. };
  7593. SmallVector<Job, 16> Queue;
  7594. IntExprEvaluator &IntEval;
  7595. EvalInfo &Info;
  7596. APValue &FinalResult;
  7597. public:
  7598. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  7599. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  7600. /// True if \param E is a binary operator that we are going to handle
  7601. /// data recursively.
  7602. /// We handle binary operators that are comma, logical, or that have operands
  7603. /// with integral or enumeration type.
  7604. static bool shouldEnqueue(const BinaryOperator *E) {
  7605. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  7606. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  7607. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7608. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7609. }
  7610. bool Traverse(const BinaryOperator *E) {
  7611. enqueue(E);
  7612. EvalResult PrevResult;
  7613. while (!Queue.empty())
  7614. process(PrevResult);
  7615. if (PrevResult.Failed) return false;
  7616. FinalResult.swap(PrevResult.Val);
  7617. return true;
  7618. }
  7619. private:
  7620. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  7621. return IntEval.Success(Value, E, Result);
  7622. }
  7623. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  7624. return IntEval.Success(Value, E, Result);
  7625. }
  7626. bool Error(const Expr *E) {
  7627. return IntEval.Error(E);
  7628. }
  7629. bool Error(const Expr *E, diag::kind D) {
  7630. return IntEval.Error(E, D);
  7631. }
  7632. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  7633. return Info.CCEDiag(E, D);
  7634. }
  7635. // Returns true if visiting the RHS is necessary, false otherwise.
  7636. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7637. bool &SuppressRHSDiags);
  7638. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7639. const BinaryOperator *E, APValue &Result);
  7640. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  7641. Result.Failed = !Evaluate(Result.Val, Info, E);
  7642. if (Result.Failed)
  7643. Result.Val = APValue();
  7644. }
  7645. void process(EvalResult &Result);
  7646. void enqueue(const Expr *E) {
  7647. E = E->IgnoreParens();
  7648. Queue.resize(Queue.size()+1);
  7649. Queue.back().E = E;
  7650. Queue.back().Kind = Job::AnyExprKind;
  7651. }
  7652. };
  7653. }
  7654. bool DataRecursiveIntBinOpEvaluator::
  7655. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7656. bool &SuppressRHSDiags) {
  7657. if (E->getOpcode() == BO_Comma) {
  7658. // Ignore LHS but note if we could not evaluate it.
  7659. if (LHSResult.Failed)
  7660. return Info.noteSideEffect();
  7661. return true;
  7662. }
  7663. if (E->isLogicalOp()) {
  7664. bool LHSAsBool;
  7665. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  7666. // We were able to evaluate the LHS, see if we can get away with not
  7667. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  7668. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  7669. Success(LHSAsBool, E, LHSResult.Val);
  7670. return false; // Ignore RHS
  7671. }
  7672. } else {
  7673. LHSResult.Failed = true;
  7674. // Since we weren't able to evaluate the left hand side, it
  7675. // might have had side effects.
  7676. if (!Info.noteSideEffect())
  7677. return false;
  7678. // We can't evaluate the LHS; however, sometimes the result
  7679. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7680. // Don't ignore RHS and suppress diagnostics from this arm.
  7681. SuppressRHSDiags = true;
  7682. }
  7683. return true;
  7684. }
  7685. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7686. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7687. if (LHSResult.Failed && !Info.noteFailure())
  7688. return false; // Ignore RHS;
  7689. return true;
  7690. }
  7691. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  7692. bool IsSub) {
  7693. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  7694. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  7695. // offsets.
  7696. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  7697. CharUnits &Offset = LVal.getLValueOffset();
  7698. uint64_t Offset64 = Offset.getQuantity();
  7699. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  7700. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  7701. : Offset64 + Index64);
  7702. }
  7703. bool DataRecursiveIntBinOpEvaluator::
  7704. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7705. const BinaryOperator *E, APValue &Result) {
  7706. if (E->getOpcode() == BO_Comma) {
  7707. if (RHSResult.Failed)
  7708. return false;
  7709. Result = RHSResult.Val;
  7710. return true;
  7711. }
  7712. if (E->isLogicalOp()) {
  7713. bool lhsResult, rhsResult;
  7714. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  7715. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  7716. if (LHSIsOK) {
  7717. if (RHSIsOK) {
  7718. if (E->getOpcode() == BO_LOr)
  7719. return Success(lhsResult || rhsResult, E, Result);
  7720. else
  7721. return Success(lhsResult && rhsResult, E, Result);
  7722. }
  7723. } else {
  7724. if (RHSIsOK) {
  7725. // We can't evaluate the LHS; however, sometimes the result
  7726. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7727. if (rhsResult == (E->getOpcode() == BO_LOr))
  7728. return Success(rhsResult, E, Result);
  7729. }
  7730. }
  7731. return false;
  7732. }
  7733. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7734. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7735. if (LHSResult.Failed || RHSResult.Failed)
  7736. return false;
  7737. const APValue &LHSVal = LHSResult.Val;
  7738. const APValue &RHSVal = RHSResult.Val;
  7739. // Handle cases like (unsigned long)&a + 4.
  7740. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  7741. Result = LHSVal;
  7742. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  7743. return true;
  7744. }
  7745. // Handle cases like 4 + (unsigned long)&a
  7746. if (E->getOpcode() == BO_Add &&
  7747. RHSVal.isLValue() && LHSVal.isInt()) {
  7748. Result = RHSVal;
  7749. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  7750. return true;
  7751. }
  7752. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  7753. // Handle (intptr_t)&&A - (intptr_t)&&B.
  7754. if (!LHSVal.getLValueOffset().isZero() ||
  7755. !RHSVal.getLValueOffset().isZero())
  7756. return false;
  7757. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  7758. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  7759. if (!LHSExpr || !RHSExpr)
  7760. return false;
  7761. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  7762. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  7763. if (!LHSAddrExpr || !RHSAddrExpr)
  7764. return false;
  7765. // Make sure both labels come from the same function.
  7766. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  7767. RHSAddrExpr->getLabel()->getDeclContext())
  7768. return false;
  7769. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  7770. return true;
  7771. }
  7772. // All the remaining cases expect both operands to be an integer
  7773. if (!LHSVal.isInt() || !RHSVal.isInt())
  7774. return Error(E);
  7775. // Set up the width and signedness manually, in case it can't be deduced
  7776. // from the operation we're performing.
  7777. // FIXME: Don't do this in the cases where we can deduce it.
  7778. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  7779. E->getType()->isUnsignedIntegerOrEnumerationType());
  7780. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  7781. RHSVal.getInt(), Value))
  7782. return false;
  7783. return Success(Value, E, Result);
  7784. }
  7785. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  7786. Job &job = Queue.back();
  7787. switch (job.Kind) {
  7788. case Job::AnyExprKind: {
  7789. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  7790. if (shouldEnqueue(Bop)) {
  7791. job.Kind = Job::BinOpKind;
  7792. enqueue(Bop->getLHS());
  7793. return;
  7794. }
  7795. }
  7796. EvaluateExpr(job.E, Result);
  7797. Queue.pop_back();
  7798. return;
  7799. }
  7800. case Job::BinOpKind: {
  7801. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7802. bool SuppressRHSDiags = false;
  7803. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  7804. Queue.pop_back();
  7805. return;
  7806. }
  7807. if (SuppressRHSDiags)
  7808. job.startSpeculativeEval(Info);
  7809. job.LHSResult.swap(Result);
  7810. job.Kind = Job::BinOpVisitedLHSKind;
  7811. enqueue(Bop->getRHS());
  7812. return;
  7813. }
  7814. case Job::BinOpVisitedLHSKind: {
  7815. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7816. EvalResult RHS;
  7817. RHS.swap(Result);
  7818. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  7819. Queue.pop_back();
  7820. return;
  7821. }
  7822. }
  7823. llvm_unreachable("Invalid Job::Kind!");
  7824. }
  7825. namespace {
  7826. /// Used when we determine that we should fail, but can keep evaluating prior to
  7827. /// noting that we had a failure.
  7828. class DelayedNoteFailureRAII {
  7829. EvalInfo &Info;
  7830. bool NoteFailure;
  7831. public:
  7832. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  7833. : Info(Info), NoteFailure(NoteFailure) {}
  7834. ~DelayedNoteFailureRAII() {
  7835. if (NoteFailure) {
  7836. bool ContinueAfterFailure = Info.noteFailure();
  7837. (void)ContinueAfterFailure;
  7838. assert(ContinueAfterFailure &&
  7839. "Shouldn't have kept evaluating on failure.");
  7840. }
  7841. }
  7842. };
  7843. }
  7844. template <class SuccessCB, class AfterCB>
  7845. static bool
  7846. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  7847. SuccessCB &&Success, AfterCB &&DoAfter) {
  7848. assert(E->isComparisonOp() && "expected comparison operator");
  7849. assert((E->getOpcode() == BO_Cmp ||
  7850. E->getType()->isIntegralOrEnumerationType()) &&
  7851. "unsupported binary expression evaluation");
  7852. auto Error = [&](const Expr *E) {
  7853. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7854. return false;
  7855. };
  7856. using CCR = ComparisonCategoryResult;
  7857. bool IsRelational = E->isRelationalOp();
  7858. bool IsEquality = E->isEqualityOp();
  7859. if (E->getOpcode() == BO_Cmp) {
  7860. const ComparisonCategoryInfo &CmpInfo =
  7861. Info.Ctx.CompCategories.getInfoForType(E->getType());
  7862. IsRelational = CmpInfo.isOrdered();
  7863. IsEquality = CmpInfo.isEquality();
  7864. }
  7865. QualType LHSTy = E->getLHS()->getType();
  7866. QualType RHSTy = E->getRHS()->getType();
  7867. if (LHSTy->isIntegralOrEnumerationType() &&
  7868. RHSTy->isIntegralOrEnumerationType()) {
  7869. APSInt LHS, RHS;
  7870. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  7871. if (!LHSOK && !Info.noteFailure())
  7872. return false;
  7873. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  7874. return false;
  7875. if (LHS < RHS)
  7876. return Success(CCR::Less, E);
  7877. if (LHS > RHS)
  7878. return Success(CCR::Greater, E);
  7879. return Success(CCR::Equal, E);
  7880. }
  7881. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  7882. ComplexValue LHS, RHS;
  7883. bool LHSOK;
  7884. if (E->isAssignmentOp()) {
  7885. LValue LV;
  7886. EvaluateLValue(E->getLHS(), LV, Info);
  7887. LHSOK = false;
  7888. } else if (LHSTy->isRealFloatingType()) {
  7889. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  7890. if (LHSOK) {
  7891. LHS.makeComplexFloat();
  7892. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  7893. }
  7894. } else {
  7895. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  7896. }
  7897. if (!LHSOK && !Info.noteFailure())
  7898. return false;
  7899. if (E->getRHS()->getType()->isRealFloatingType()) {
  7900. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  7901. return false;
  7902. RHS.makeComplexFloat();
  7903. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  7904. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  7905. return false;
  7906. if (LHS.isComplexFloat()) {
  7907. APFloat::cmpResult CR_r =
  7908. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  7909. APFloat::cmpResult CR_i =
  7910. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  7911. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  7912. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7913. } else {
  7914. assert(IsEquality && "invalid complex comparison");
  7915. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  7916. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  7917. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7918. }
  7919. }
  7920. if (LHSTy->isRealFloatingType() &&
  7921. RHSTy->isRealFloatingType()) {
  7922. APFloat RHS(0.0), LHS(0.0);
  7923. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  7924. if (!LHSOK && !Info.noteFailure())
  7925. return false;
  7926. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  7927. return false;
  7928. assert(E->isComparisonOp() && "Invalid binary operator!");
  7929. auto GetCmpRes = [&]() {
  7930. switch (LHS.compare(RHS)) {
  7931. case APFloat::cmpEqual:
  7932. return CCR::Equal;
  7933. case APFloat::cmpLessThan:
  7934. return CCR::Less;
  7935. case APFloat::cmpGreaterThan:
  7936. return CCR::Greater;
  7937. case APFloat::cmpUnordered:
  7938. return CCR::Unordered;
  7939. }
  7940. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  7941. };
  7942. return Success(GetCmpRes(), E);
  7943. }
  7944. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  7945. LValue LHSValue, RHSValue;
  7946. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  7947. if (!LHSOK && !Info.noteFailure())
  7948. return false;
  7949. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  7950. return false;
  7951. // Reject differing bases from the normal codepath; we special-case
  7952. // comparisons to null.
  7953. if (!HasSameBase(LHSValue, RHSValue)) {
  7954. // Inequalities and subtractions between unrelated pointers have
  7955. // unspecified or undefined behavior.
  7956. if (!IsEquality)
  7957. return Error(E);
  7958. // A constant address may compare equal to the address of a symbol.
  7959. // The one exception is that address of an object cannot compare equal
  7960. // to a null pointer constant.
  7961. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  7962. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  7963. return Error(E);
  7964. // It's implementation-defined whether distinct literals will have
  7965. // distinct addresses. In clang, the result of such a comparison is
  7966. // unspecified, so it is not a constant expression. However, we do know
  7967. // that the address of a literal will be non-null.
  7968. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  7969. LHSValue.Base && RHSValue.Base)
  7970. return Error(E);
  7971. // We can't tell whether weak symbols will end up pointing to the same
  7972. // object.
  7973. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  7974. return Error(E);
  7975. // We can't compare the address of the start of one object with the
  7976. // past-the-end address of another object, per C++ DR1652.
  7977. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  7978. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  7979. (RHSValue.Base && RHSValue.Offset.isZero() &&
  7980. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  7981. return Error(E);
  7982. // We can't tell whether an object is at the same address as another
  7983. // zero sized object.
  7984. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  7985. (LHSValue.Base && isZeroSized(RHSValue)))
  7986. return Error(E);
  7987. return Success(CCR::Nonequal, E);
  7988. }
  7989. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  7990. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  7991. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  7992. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  7993. // C++11 [expr.rel]p3:
  7994. // Pointers to void (after pointer conversions) can be compared, with a
  7995. // result defined as follows: If both pointers represent the same
  7996. // address or are both the null pointer value, the result is true if the
  7997. // operator is <= or >= and false otherwise; otherwise the result is
  7998. // unspecified.
  7999. // We interpret this as applying to pointers to *cv* void.
  8000. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  8001. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  8002. // C++11 [expr.rel]p2:
  8003. // - If two pointers point to non-static data members of the same object,
  8004. // or to subobjects or array elements fo such members, recursively, the
  8005. // pointer to the later declared member compares greater provided the
  8006. // two members have the same access control and provided their class is
  8007. // not a union.
  8008. // [...]
  8009. // - Otherwise pointer comparisons are unspecified.
  8010. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  8011. bool WasArrayIndex;
  8012. unsigned Mismatch = FindDesignatorMismatch(
  8013. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  8014. // At the point where the designators diverge, the comparison has a
  8015. // specified value if:
  8016. // - we are comparing array indices
  8017. // - we are comparing fields of a union, or fields with the same access
  8018. // Otherwise, the result is unspecified and thus the comparison is not a
  8019. // constant expression.
  8020. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  8021. Mismatch < RHSDesignator.Entries.size()) {
  8022. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  8023. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  8024. if (!LF && !RF)
  8025. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  8026. else if (!LF)
  8027. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8028. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  8029. << RF->getParent() << RF;
  8030. else if (!RF)
  8031. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8032. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  8033. << LF->getParent() << LF;
  8034. else if (!LF->getParent()->isUnion() &&
  8035. LF->getAccess() != RF->getAccess())
  8036. Info.CCEDiag(E,
  8037. diag::note_constexpr_pointer_comparison_differing_access)
  8038. << LF << LF->getAccess() << RF << RF->getAccess()
  8039. << LF->getParent();
  8040. }
  8041. }
  8042. // The comparison here must be unsigned, and performed with the same
  8043. // width as the pointer.
  8044. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  8045. uint64_t CompareLHS = LHSOffset.getQuantity();
  8046. uint64_t CompareRHS = RHSOffset.getQuantity();
  8047. assert(PtrSize <= 64 && "Unexpected pointer width");
  8048. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  8049. CompareLHS &= Mask;
  8050. CompareRHS &= Mask;
  8051. // If there is a base and this is a relational operator, we can only
  8052. // compare pointers within the object in question; otherwise, the result
  8053. // depends on where the object is located in memory.
  8054. if (!LHSValue.Base.isNull() && IsRelational) {
  8055. QualType BaseTy = getType(LHSValue.Base);
  8056. if (BaseTy->isIncompleteType())
  8057. return Error(E);
  8058. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  8059. uint64_t OffsetLimit = Size.getQuantity();
  8060. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  8061. return Error(E);
  8062. }
  8063. if (CompareLHS < CompareRHS)
  8064. return Success(CCR::Less, E);
  8065. if (CompareLHS > CompareRHS)
  8066. return Success(CCR::Greater, E);
  8067. return Success(CCR::Equal, E);
  8068. }
  8069. if (LHSTy->isMemberPointerType()) {
  8070. assert(IsEquality && "unexpected member pointer operation");
  8071. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  8072. MemberPtr LHSValue, RHSValue;
  8073. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  8074. if (!LHSOK && !Info.noteFailure())
  8075. return false;
  8076. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8077. return false;
  8078. // C++11 [expr.eq]p2:
  8079. // If both operands are null, they compare equal. Otherwise if only one is
  8080. // null, they compare unequal.
  8081. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  8082. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  8083. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8084. }
  8085. // Otherwise if either is a pointer to a virtual member function, the
  8086. // result is unspecified.
  8087. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  8088. if (MD->isVirtual())
  8089. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8090. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  8091. if (MD->isVirtual())
  8092. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8093. // Otherwise they compare equal if and only if they would refer to the
  8094. // same member of the same most derived object or the same subobject if
  8095. // they were dereferenced with a hypothetical object of the associated
  8096. // class type.
  8097. bool Equal = LHSValue == RHSValue;
  8098. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8099. }
  8100. if (LHSTy->isNullPtrType()) {
  8101. assert(E->isComparisonOp() && "unexpected nullptr operation");
  8102. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  8103. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  8104. // are compared, the result is true of the operator is <=, >= or ==, and
  8105. // false otherwise.
  8106. return Success(CCR::Equal, E);
  8107. }
  8108. return DoAfter();
  8109. }
  8110. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  8111. if (!CheckLiteralType(Info, E))
  8112. return false;
  8113. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8114. const BinaryOperator *E) {
  8115. // Evaluation succeeded. Lookup the information for the comparison category
  8116. // type and fetch the VarDecl for the result.
  8117. const ComparisonCategoryInfo &CmpInfo =
  8118. Info.Ctx.CompCategories.getInfoForType(E->getType());
  8119. const VarDecl *VD =
  8120. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  8121. // Check and evaluate the result as a constant expression.
  8122. LValue LV;
  8123. LV.set(VD);
  8124. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  8125. return false;
  8126. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  8127. };
  8128. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8129. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  8130. });
  8131. }
  8132. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8133. // We don't call noteFailure immediately because the assignment happens after
  8134. // we evaluate LHS and RHS.
  8135. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  8136. return Error(E);
  8137. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  8138. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  8139. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  8140. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  8141. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  8142. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  8143. if (E->isComparisonOp()) {
  8144. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  8145. // comparisons and then translating the result.
  8146. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8147. const BinaryOperator *E) {
  8148. using CCR = ComparisonCategoryResult;
  8149. bool IsEqual = ResKind == CCR::Equal,
  8150. IsLess = ResKind == CCR::Less,
  8151. IsGreater = ResKind == CCR::Greater;
  8152. auto Op = E->getOpcode();
  8153. switch (Op) {
  8154. default:
  8155. llvm_unreachable("unsupported binary operator");
  8156. case BO_EQ:
  8157. case BO_NE:
  8158. return Success(IsEqual == (Op == BO_EQ), E);
  8159. case BO_LT: return Success(IsLess, E);
  8160. case BO_GT: return Success(IsGreater, E);
  8161. case BO_LE: return Success(IsEqual || IsLess, E);
  8162. case BO_GE: return Success(IsEqual || IsGreater, E);
  8163. }
  8164. };
  8165. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8166. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8167. });
  8168. }
  8169. QualType LHSTy = E->getLHS()->getType();
  8170. QualType RHSTy = E->getRHS()->getType();
  8171. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  8172. E->getOpcode() == BO_Sub) {
  8173. LValue LHSValue, RHSValue;
  8174. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  8175. if (!LHSOK && !Info.noteFailure())
  8176. return false;
  8177. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8178. return false;
  8179. // Reject differing bases from the normal codepath; we special-case
  8180. // comparisons to null.
  8181. if (!HasSameBase(LHSValue, RHSValue)) {
  8182. // Handle &&A - &&B.
  8183. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  8184. return Error(E);
  8185. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  8186. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  8187. if (!LHSExpr || !RHSExpr)
  8188. return Error(E);
  8189. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8190. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8191. if (!LHSAddrExpr || !RHSAddrExpr)
  8192. return Error(E);
  8193. // Make sure both labels come from the same function.
  8194. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8195. RHSAddrExpr->getLabel()->getDeclContext())
  8196. return Error(E);
  8197. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  8198. }
  8199. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  8200. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  8201. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  8202. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  8203. // C++11 [expr.add]p6:
  8204. // Unless both pointers point to elements of the same array object, or
  8205. // one past the last element of the array object, the behavior is
  8206. // undefined.
  8207. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  8208. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  8209. RHSDesignator))
  8210. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  8211. QualType Type = E->getLHS()->getType();
  8212. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  8213. CharUnits ElementSize;
  8214. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  8215. return false;
  8216. // As an extension, a type may have zero size (empty struct or union in
  8217. // C, array of zero length). Pointer subtraction in such cases has
  8218. // undefined behavior, so is not constant.
  8219. if (ElementSize.isZero()) {
  8220. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  8221. << ElementType;
  8222. return false;
  8223. }
  8224. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  8225. // and produce incorrect results when it overflows. Such behavior
  8226. // appears to be non-conforming, but is common, so perhaps we should
  8227. // assume the standard intended for such cases to be undefined behavior
  8228. // and check for them.
  8229. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  8230. // overflow in the final conversion to ptrdiff_t.
  8231. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  8232. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  8233. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  8234. false);
  8235. APSInt TrueResult = (LHS - RHS) / ElemSize;
  8236. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  8237. if (Result.extend(65) != TrueResult &&
  8238. !HandleOverflow(Info, E, TrueResult, E->getType()))
  8239. return false;
  8240. return Success(Result, E);
  8241. }
  8242. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8243. }
  8244. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  8245. /// a result as the expression's type.
  8246. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  8247. const UnaryExprOrTypeTraitExpr *E) {
  8248. switch(E->getKind()) {
  8249. case UETT_PreferredAlignOf:
  8250. case UETT_AlignOf: {
  8251. if (E->isArgumentType())
  8252. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  8253. E);
  8254. else
  8255. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  8256. E);
  8257. }
  8258. case UETT_VecStep: {
  8259. QualType Ty = E->getTypeOfArgument();
  8260. if (Ty->isVectorType()) {
  8261. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  8262. // The vec_step built-in functions that take a 3-component
  8263. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  8264. if (n == 3)
  8265. n = 4;
  8266. return Success(n, E);
  8267. } else
  8268. return Success(1, E);
  8269. }
  8270. case UETT_SizeOf: {
  8271. QualType SrcTy = E->getTypeOfArgument();
  8272. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  8273. // the result is the size of the referenced type."
  8274. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  8275. SrcTy = Ref->getPointeeType();
  8276. CharUnits Sizeof;
  8277. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  8278. return false;
  8279. return Success(Sizeof, E);
  8280. }
  8281. case UETT_OpenMPRequiredSimdAlign:
  8282. assert(E->isArgumentType());
  8283. return Success(
  8284. Info.Ctx.toCharUnitsFromBits(
  8285. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  8286. .getQuantity(),
  8287. E);
  8288. }
  8289. llvm_unreachable("unknown expr/type trait");
  8290. }
  8291. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  8292. CharUnits Result;
  8293. unsigned n = OOE->getNumComponents();
  8294. if (n == 0)
  8295. return Error(OOE);
  8296. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  8297. for (unsigned i = 0; i != n; ++i) {
  8298. OffsetOfNode ON = OOE->getComponent(i);
  8299. switch (ON.getKind()) {
  8300. case OffsetOfNode::Array: {
  8301. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  8302. APSInt IdxResult;
  8303. if (!EvaluateInteger(Idx, IdxResult, Info))
  8304. return false;
  8305. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  8306. if (!AT)
  8307. return Error(OOE);
  8308. CurrentType = AT->getElementType();
  8309. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  8310. Result += IdxResult.getSExtValue() * ElementSize;
  8311. break;
  8312. }
  8313. case OffsetOfNode::Field: {
  8314. FieldDecl *MemberDecl = ON.getField();
  8315. const RecordType *RT = CurrentType->getAs<RecordType>();
  8316. if (!RT)
  8317. return Error(OOE);
  8318. RecordDecl *RD = RT->getDecl();
  8319. if (RD->isInvalidDecl()) return false;
  8320. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8321. unsigned i = MemberDecl->getFieldIndex();
  8322. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  8323. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  8324. CurrentType = MemberDecl->getType().getNonReferenceType();
  8325. break;
  8326. }
  8327. case OffsetOfNode::Identifier:
  8328. llvm_unreachable("dependent __builtin_offsetof");
  8329. case OffsetOfNode::Base: {
  8330. CXXBaseSpecifier *BaseSpec = ON.getBase();
  8331. if (BaseSpec->isVirtual())
  8332. return Error(OOE);
  8333. // Find the layout of the class whose base we are looking into.
  8334. const RecordType *RT = CurrentType->getAs<RecordType>();
  8335. if (!RT)
  8336. return Error(OOE);
  8337. RecordDecl *RD = RT->getDecl();
  8338. if (RD->isInvalidDecl()) return false;
  8339. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8340. // Find the base class itself.
  8341. CurrentType = BaseSpec->getType();
  8342. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  8343. if (!BaseRT)
  8344. return Error(OOE);
  8345. // Add the offset to the base.
  8346. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  8347. break;
  8348. }
  8349. }
  8350. }
  8351. return Success(Result, OOE);
  8352. }
  8353. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8354. switch (E->getOpcode()) {
  8355. default:
  8356. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  8357. // See C99 6.6p3.
  8358. return Error(E);
  8359. case UO_Extension:
  8360. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  8361. // If so, we could clear the diagnostic ID.
  8362. return Visit(E->getSubExpr());
  8363. case UO_Plus:
  8364. // The result is just the value.
  8365. return Visit(E->getSubExpr());
  8366. case UO_Minus: {
  8367. if (!Visit(E->getSubExpr()))
  8368. return false;
  8369. if (!Result.isInt()) return Error(E);
  8370. const APSInt &Value = Result.getInt();
  8371. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  8372. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  8373. E->getType()))
  8374. return false;
  8375. return Success(-Value, E);
  8376. }
  8377. case UO_Not: {
  8378. if (!Visit(E->getSubExpr()))
  8379. return false;
  8380. if (!Result.isInt()) return Error(E);
  8381. return Success(~Result.getInt(), E);
  8382. }
  8383. case UO_LNot: {
  8384. bool bres;
  8385. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8386. return false;
  8387. return Success(!bres, E);
  8388. }
  8389. }
  8390. }
  8391. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  8392. /// result type is integer.
  8393. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8394. const Expr *SubExpr = E->getSubExpr();
  8395. QualType DestType = E->getType();
  8396. QualType SrcType = SubExpr->getType();
  8397. switch (E->getCastKind()) {
  8398. case CK_BaseToDerived:
  8399. case CK_DerivedToBase:
  8400. case CK_UncheckedDerivedToBase:
  8401. case CK_Dynamic:
  8402. case CK_ToUnion:
  8403. case CK_ArrayToPointerDecay:
  8404. case CK_FunctionToPointerDecay:
  8405. case CK_NullToPointer:
  8406. case CK_NullToMemberPointer:
  8407. case CK_BaseToDerivedMemberPointer:
  8408. case CK_DerivedToBaseMemberPointer:
  8409. case CK_ReinterpretMemberPointer:
  8410. case CK_ConstructorConversion:
  8411. case CK_IntegralToPointer:
  8412. case CK_ToVoid:
  8413. case CK_VectorSplat:
  8414. case CK_IntegralToFloating:
  8415. case CK_FloatingCast:
  8416. case CK_CPointerToObjCPointerCast:
  8417. case CK_BlockPointerToObjCPointerCast:
  8418. case CK_AnyPointerToBlockPointerCast:
  8419. case CK_ObjCObjectLValueCast:
  8420. case CK_FloatingRealToComplex:
  8421. case CK_FloatingComplexToReal:
  8422. case CK_FloatingComplexCast:
  8423. case CK_FloatingComplexToIntegralComplex:
  8424. case CK_IntegralRealToComplex:
  8425. case CK_IntegralComplexCast:
  8426. case CK_IntegralComplexToFloatingComplex:
  8427. case CK_BuiltinFnToFnPtr:
  8428. case CK_ZeroToOCLOpaqueType:
  8429. case CK_NonAtomicToAtomic:
  8430. case CK_AddressSpaceConversion:
  8431. case CK_IntToOCLSampler:
  8432. case CK_FixedPointCast:
  8433. llvm_unreachable("invalid cast kind for integral value");
  8434. case CK_BitCast:
  8435. case CK_Dependent:
  8436. case CK_LValueBitCast:
  8437. case CK_ARCProduceObject:
  8438. case CK_ARCConsumeObject:
  8439. case CK_ARCReclaimReturnedObject:
  8440. case CK_ARCExtendBlockObject:
  8441. case CK_CopyAndAutoreleaseBlockObject:
  8442. return Error(E);
  8443. case CK_UserDefinedConversion:
  8444. case CK_LValueToRValue:
  8445. case CK_AtomicToNonAtomic:
  8446. case CK_NoOp:
  8447. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8448. case CK_MemberPointerToBoolean:
  8449. case CK_PointerToBoolean:
  8450. case CK_IntegralToBoolean:
  8451. case CK_FloatingToBoolean:
  8452. case CK_BooleanToSignedIntegral:
  8453. case CK_FloatingComplexToBoolean:
  8454. case CK_IntegralComplexToBoolean: {
  8455. bool BoolResult;
  8456. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  8457. return false;
  8458. uint64_t IntResult = BoolResult;
  8459. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  8460. IntResult = (uint64_t)-1;
  8461. return Success(IntResult, E);
  8462. }
  8463. case CK_FixedPointToBoolean: {
  8464. // Unsigned padding does not affect this.
  8465. APValue Val;
  8466. if (!Evaluate(Val, Info, SubExpr))
  8467. return false;
  8468. return Success(Val.getInt().getBoolValue(), E);
  8469. }
  8470. case CK_IntegralCast: {
  8471. if (!Visit(SubExpr))
  8472. return false;
  8473. if (!Result.isInt()) {
  8474. // Allow casts of address-of-label differences if they are no-ops
  8475. // or narrowing. (The narrowing case isn't actually guaranteed to
  8476. // be constant-evaluatable except in some narrow cases which are hard
  8477. // to detect here. We let it through on the assumption the user knows
  8478. // what they are doing.)
  8479. if (Result.isAddrLabelDiff())
  8480. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  8481. // Only allow casts of lvalues if they are lossless.
  8482. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  8483. }
  8484. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  8485. Result.getInt()), E);
  8486. }
  8487. case CK_PointerToIntegral: {
  8488. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  8489. LValue LV;
  8490. if (!EvaluatePointer(SubExpr, LV, Info))
  8491. return false;
  8492. if (LV.getLValueBase()) {
  8493. // Only allow based lvalue casts if they are lossless.
  8494. // FIXME: Allow a larger integer size than the pointer size, and allow
  8495. // narrowing back down to pointer width in subsequent integral casts.
  8496. // FIXME: Check integer type's active bits, not its type size.
  8497. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  8498. return Error(E);
  8499. LV.Designator.setInvalid();
  8500. LV.moveInto(Result);
  8501. return true;
  8502. }
  8503. uint64_t V;
  8504. if (LV.isNullPointer())
  8505. V = Info.Ctx.getTargetNullPointerValue(SrcType);
  8506. else
  8507. V = LV.getLValueOffset().getQuantity();
  8508. APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
  8509. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  8510. }
  8511. case CK_IntegralComplexToReal: {
  8512. ComplexValue C;
  8513. if (!EvaluateComplex(SubExpr, C, Info))
  8514. return false;
  8515. return Success(C.getComplexIntReal(), E);
  8516. }
  8517. case CK_FloatingToIntegral: {
  8518. APFloat F(0.0);
  8519. if (!EvaluateFloat(SubExpr, F, Info))
  8520. return false;
  8521. APSInt Value;
  8522. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  8523. return false;
  8524. return Success(Value, E);
  8525. }
  8526. }
  8527. llvm_unreachable("unknown cast resulting in integral value");
  8528. }
  8529. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8530. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8531. ComplexValue LV;
  8532. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8533. return false;
  8534. if (!LV.isComplexInt())
  8535. return Error(E);
  8536. return Success(LV.getComplexIntReal(), E);
  8537. }
  8538. return Visit(E->getSubExpr());
  8539. }
  8540. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8541. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  8542. ComplexValue LV;
  8543. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8544. return false;
  8545. if (!LV.isComplexInt())
  8546. return Error(E);
  8547. return Success(LV.getComplexIntImag(), E);
  8548. }
  8549. VisitIgnoredValue(E->getSubExpr());
  8550. return Success(0, E);
  8551. }
  8552. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  8553. return Success(E->getPackLength(), E);
  8554. }
  8555. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  8556. return Success(E->getValue(), E);
  8557. }
  8558. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8559. switch (E->getOpcode()) {
  8560. default:
  8561. // Invalid unary operators
  8562. return Error(E);
  8563. case UO_Plus:
  8564. // The result is just the value.
  8565. return Visit(E->getSubExpr());
  8566. case UO_Minus: {
  8567. if (!Visit(E->getSubExpr())) return false;
  8568. if (!Result.isInt()) return Error(E);
  8569. const APSInt &Value = Result.getInt();
  8570. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
  8571. SmallString<64> S;
  8572. FixedPointValueToString(S, Value,
  8573. Info.Ctx.getTypeInfo(E->getType()).Width);
  8574. Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
  8575. if (Info.noteUndefinedBehavior()) return false;
  8576. }
  8577. return Success(-Value, E);
  8578. }
  8579. case UO_LNot: {
  8580. bool bres;
  8581. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8582. return false;
  8583. return Success(!bres, E);
  8584. }
  8585. }
  8586. }
  8587. //===----------------------------------------------------------------------===//
  8588. // Float Evaluation
  8589. //===----------------------------------------------------------------------===//
  8590. namespace {
  8591. class FloatExprEvaluator
  8592. : public ExprEvaluatorBase<FloatExprEvaluator> {
  8593. APFloat &Result;
  8594. public:
  8595. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  8596. : ExprEvaluatorBaseTy(info), Result(result) {}
  8597. bool Success(const APValue &V, const Expr *e) {
  8598. Result = V.getFloat();
  8599. return true;
  8600. }
  8601. bool ZeroInitialization(const Expr *E) {
  8602. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  8603. return true;
  8604. }
  8605. bool VisitCallExpr(const CallExpr *E);
  8606. bool VisitUnaryOperator(const UnaryOperator *E);
  8607. bool VisitBinaryOperator(const BinaryOperator *E);
  8608. bool VisitFloatingLiteral(const FloatingLiteral *E);
  8609. bool VisitCastExpr(const CastExpr *E);
  8610. bool VisitUnaryReal(const UnaryOperator *E);
  8611. bool VisitUnaryImag(const UnaryOperator *E);
  8612. // FIXME: Missing: array subscript of vector, member of vector
  8613. };
  8614. } // end anonymous namespace
  8615. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  8616. assert(E->isRValue() && E->getType()->isRealFloatingType());
  8617. return FloatExprEvaluator(Info, Result).Visit(E);
  8618. }
  8619. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  8620. QualType ResultTy,
  8621. const Expr *Arg,
  8622. bool SNaN,
  8623. llvm::APFloat &Result) {
  8624. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  8625. if (!S) return false;
  8626. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  8627. llvm::APInt fill;
  8628. // Treat empty strings as if they were zero.
  8629. if (S->getString().empty())
  8630. fill = llvm::APInt(32, 0);
  8631. else if (S->getString().getAsInteger(0, fill))
  8632. return false;
  8633. if (Context.getTargetInfo().isNan2008()) {
  8634. if (SNaN)
  8635. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8636. else
  8637. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8638. } else {
  8639. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  8640. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  8641. // a different encoding to what became a standard in 2008, and for pre-
  8642. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  8643. // sNaN. This is now known as "legacy NaN" encoding.
  8644. if (SNaN)
  8645. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8646. else
  8647. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8648. }
  8649. return true;
  8650. }
  8651. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8652. switch (E->getBuiltinCallee()) {
  8653. default:
  8654. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8655. case Builtin::BI__builtin_huge_val:
  8656. case Builtin::BI__builtin_huge_valf:
  8657. case Builtin::BI__builtin_huge_vall:
  8658. case Builtin::BI__builtin_huge_valf128:
  8659. case Builtin::BI__builtin_inf:
  8660. case Builtin::BI__builtin_inff:
  8661. case Builtin::BI__builtin_infl:
  8662. case Builtin::BI__builtin_inff128: {
  8663. const llvm::fltSemantics &Sem =
  8664. Info.Ctx.getFloatTypeSemantics(E->getType());
  8665. Result = llvm::APFloat::getInf(Sem);
  8666. return true;
  8667. }
  8668. case Builtin::BI__builtin_nans:
  8669. case Builtin::BI__builtin_nansf:
  8670. case Builtin::BI__builtin_nansl:
  8671. case Builtin::BI__builtin_nansf128:
  8672. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8673. true, Result))
  8674. return Error(E);
  8675. return true;
  8676. case Builtin::BI__builtin_nan:
  8677. case Builtin::BI__builtin_nanf:
  8678. case Builtin::BI__builtin_nanl:
  8679. case Builtin::BI__builtin_nanf128:
  8680. // If this is __builtin_nan() turn this into a nan, otherwise we
  8681. // can't constant fold it.
  8682. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8683. false, Result))
  8684. return Error(E);
  8685. return true;
  8686. case Builtin::BI__builtin_fabs:
  8687. case Builtin::BI__builtin_fabsf:
  8688. case Builtin::BI__builtin_fabsl:
  8689. case Builtin::BI__builtin_fabsf128:
  8690. if (!EvaluateFloat(E->getArg(0), Result, Info))
  8691. return false;
  8692. if (Result.isNegative())
  8693. Result.changeSign();
  8694. return true;
  8695. // FIXME: Builtin::BI__builtin_powi
  8696. // FIXME: Builtin::BI__builtin_powif
  8697. // FIXME: Builtin::BI__builtin_powil
  8698. case Builtin::BI__builtin_copysign:
  8699. case Builtin::BI__builtin_copysignf:
  8700. case Builtin::BI__builtin_copysignl:
  8701. case Builtin::BI__builtin_copysignf128: {
  8702. APFloat RHS(0.);
  8703. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  8704. !EvaluateFloat(E->getArg(1), RHS, Info))
  8705. return false;
  8706. Result.copySign(RHS);
  8707. return true;
  8708. }
  8709. }
  8710. }
  8711. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8712. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8713. ComplexValue CV;
  8714. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8715. return false;
  8716. Result = CV.FloatReal;
  8717. return true;
  8718. }
  8719. return Visit(E->getSubExpr());
  8720. }
  8721. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8722. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8723. ComplexValue CV;
  8724. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8725. return false;
  8726. Result = CV.FloatImag;
  8727. return true;
  8728. }
  8729. VisitIgnoredValue(E->getSubExpr());
  8730. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  8731. Result = llvm::APFloat::getZero(Sem);
  8732. return true;
  8733. }
  8734. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8735. switch (E->getOpcode()) {
  8736. default: return Error(E);
  8737. case UO_Plus:
  8738. return EvaluateFloat(E->getSubExpr(), Result, Info);
  8739. case UO_Minus:
  8740. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  8741. return false;
  8742. Result.changeSign();
  8743. return true;
  8744. }
  8745. }
  8746. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8747. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8748. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8749. APFloat RHS(0.0);
  8750. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  8751. if (!LHSOK && !Info.noteFailure())
  8752. return false;
  8753. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  8754. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  8755. }
  8756. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  8757. Result = E->getValue();
  8758. return true;
  8759. }
  8760. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8761. const Expr* SubExpr = E->getSubExpr();
  8762. switch (E->getCastKind()) {
  8763. default:
  8764. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8765. case CK_IntegralToFloating: {
  8766. APSInt IntResult;
  8767. return EvaluateInteger(SubExpr, IntResult, Info) &&
  8768. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  8769. E->getType(), Result);
  8770. }
  8771. case CK_FloatingCast: {
  8772. if (!Visit(SubExpr))
  8773. return false;
  8774. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  8775. Result);
  8776. }
  8777. case CK_FloatingComplexToReal: {
  8778. ComplexValue V;
  8779. if (!EvaluateComplex(SubExpr, V, Info))
  8780. return false;
  8781. Result = V.getComplexFloatReal();
  8782. return true;
  8783. }
  8784. }
  8785. }
  8786. //===----------------------------------------------------------------------===//
  8787. // Complex Evaluation (for float and integer)
  8788. //===----------------------------------------------------------------------===//
  8789. namespace {
  8790. class ComplexExprEvaluator
  8791. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  8792. ComplexValue &Result;
  8793. public:
  8794. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  8795. : ExprEvaluatorBaseTy(info), Result(Result) {}
  8796. bool Success(const APValue &V, const Expr *e) {
  8797. Result.setFrom(V);
  8798. return true;
  8799. }
  8800. bool ZeroInitialization(const Expr *E);
  8801. //===--------------------------------------------------------------------===//
  8802. // Visitor Methods
  8803. //===--------------------------------------------------------------------===//
  8804. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  8805. bool VisitCastExpr(const CastExpr *E);
  8806. bool VisitBinaryOperator(const BinaryOperator *E);
  8807. bool VisitUnaryOperator(const UnaryOperator *E);
  8808. bool VisitInitListExpr(const InitListExpr *E);
  8809. };
  8810. } // end anonymous namespace
  8811. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  8812. EvalInfo &Info) {
  8813. assert(E->isRValue() && E->getType()->isAnyComplexType());
  8814. return ComplexExprEvaluator(Info, Result).Visit(E);
  8815. }
  8816. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  8817. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  8818. if (ElemTy->isRealFloatingType()) {
  8819. Result.makeComplexFloat();
  8820. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  8821. Result.FloatReal = Zero;
  8822. Result.FloatImag = Zero;
  8823. } else {
  8824. Result.makeComplexInt();
  8825. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  8826. Result.IntReal = Zero;
  8827. Result.IntImag = Zero;
  8828. }
  8829. return true;
  8830. }
  8831. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  8832. const Expr* SubExpr = E->getSubExpr();
  8833. if (SubExpr->getType()->isRealFloatingType()) {
  8834. Result.makeComplexFloat();
  8835. APFloat &Imag = Result.FloatImag;
  8836. if (!EvaluateFloat(SubExpr, Imag, Info))
  8837. return false;
  8838. Result.FloatReal = APFloat(Imag.getSemantics());
  8839. return true;
  8840. } else {
  8841. assert(SubExpr->getType()->isIntegerType() &&
  8842. "Unexpected imaginary literal.");
  8843. Result.makeComplexInt();
  8844. APSInt &Imag = Result.IntImag;
  8845. if (!EvaluateInteger(SubExpr, Imag, Info))
  8846. return false;
  8847. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  8848. return true;
  8849. }
  8850. }
  8851. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8852. switch (E->getCastKind()) {
  8853. case CK_BitCast:
  8854. case CK_BaseToDerived:
  8855. case CK_DerivedToBase:
  8856. case CK_UncheckedDerivedToBase:
  8857. case CK_Dynamic:
  8858. case CK_ToUnion:
  8859. case CK_ArrayToPointerDecay:
  8860. case CK_FunctionToPointerDecay:
  8861. case CK_NullToPointer:
  8862. case CK_NullToMemberPointer:
  8863. case CK_BaseToDerivedMemberPointer:
  8864. case CK_DerivedToBaseMemberPointer:
  8865. case CK_MemberPointerToBoolean:
  8866. case CK_ReinterpretMemberPointer:
  8867. case CK_ConstructorConversion:
  8868. case CK_IntegralToPointer:
  8869. case CK_PointerToIntegral:
  8870. case CK_PointerToBoolean:
  8871. case CK_ToVoid:
  8872. case CK_VectorSplat:
  8873. case CK_IntegralCast:
  8874. case CK_BooleanToSignedIntegral:
  8875. case CK_IntegralToBoolean:
  8876. case CK_IntegralToFloating:
  8877. case CK_FloatingToIntegral:
  8878. case CK_FloatingToBoolean:
  8879. case CK_FloatingCast:
  8880. case CK_CPointerToObjCPointerCast:
  8881. case CK_BlockPointerToObjCPointerCast:
  8882. case CK_AnyPointerToBlockPointerCast:
  8883. case CK_ObjCObjectLValueCast:
  8884. case CK_FloatingComplexToReal:
  8885. case CK_FloatingComplexToBoolean:
  8886. case CK_IntegralComplexToReal:
  8887. case CK_IntegralComplexToBoolean:
  8888. case CK_ARCProduceObject:
  8889. case CK_ARCConsumeObject:
  8890. case CK_ARCReclaimReturnedObject:
  8891. case CK_ARCExtendBlockObject:
  8892. case CK_CopyAndAutoreleaseBlockObject:
  8893. case CK_BuiltinFnToFnPtr:
  8894. case CK_ZeroToOCLOpaqueType:
  8895. case CK_NonAtomicToAtomic:
  8896. case CK_AddressSpaceConversion:
  8897. case CK_IntToOCLSampler:
  8898. case CK_FixedPointCast:
  8899. case CK_FixedPointToBoolean:
  8900. llvm_unreachable("invalid cast kind for complex value");
  8901. case CK_LValueToRValue:
  8902. case CK_AtomicToNonAtomic:
  8903. case CK_NoOp:
  8904. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8905. case CK_Dependent:
  8906. case CK_LValueBitCast:
  8907. case CK_UserDefinedConversion:
  8908. return Error(E);
  8909. case CK_FloatingRealToComplex: {
  8910. APFloat &Real = Result.FloatReal;
  8911. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  8912. return false;
  8913. Result.makeComplexFloat();
  8914. Result.FloatImag = APFloat(Real.getSemantics());
  8915. return true;
  8916. }
  8917. case CK_FloatingComplexCast: {
  8918. if (!Visit(E->getSubExpr()))
  8919. return false;
  8920. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8921. QualType From
  8922. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8923. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  8924. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  8925. }
  8926. case CK_FloatingComplexToIntegralComplex: {
  8927. if (!Visit(E->getSubExpr()))
  8928. return false;
  8929. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8930. QualType From
  8931. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8932. Result.makeComplexInt();
  8933. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  8934. To, Result.IntReal) &&
  8935. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  8936. To, Result.IntImag);
  8937. }
  8938. case CK_IntegralRealToComplex: {
  8939. APSInt &Real = Result.IntReal;
  8940. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  8941. return false;
  8942. Result.makeComplexInt();
  8943. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  8944. return true;
  8945. }
  8946. case CK_IntegralComplexCast: {
  8947. if (!Visit(E->getSubExpr()))
  8948. return false;
  8949. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8950. QualType From
  8951. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8952. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  8953. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  8954. return true;
  8955. }
  8956. case CK_IntegralComplexToFloatingComplex: {
  8957. if (!Visit(E->getSubExpr()))
  8958. return false;
  8959. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  8960. QualType From
  8961. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  8962. Result.makeComplexFloat();
  8963. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  8964. To, Result.FloatReal) &&
  8965. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  8966. To, Result.FloatImag);
  8967. }
  8968. }
  8969. llvm_unreachable("unknown cast resulting in complex value");
  8970. }
  8971. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8972. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8973. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8974. // Track whether the LHS or RHS is real at the type system level. When this is
  8975. // the case we can simplify our evaluation strategy.
  8976. bool LHSReal = false, RHSReal = false;
  8977. bool LHSOK;
  8978. if (E->getLHS()->getType()->isRealFloatingType()) {
  8979. LHSReal = true;
  8980. APFloat &Real = Result.FloatReal;
  8981. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  8982. if (LHSOK) {
  8983. Result.makeComplexFloat();
  8984. Result.FloatImag = APFloat(Real.getSemantics());
  8985. }
  8986. } else {
  8987. LHSOK = Visit(E->getLHS());
  8988. }
  8989. if (!LHSOK && !Info.noteFailure())
  8990. return false;
  8991. ComplexValue RHS;
  8992. if (E->getRHS()->getType()->isRealFloatingType()) {
  8993. RHSReal = true;
  8994. APFloat &Real = RHS.FloatReal;
  8995. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  8996. return false;
  8997. RHS.makeComplexFloat();
  8998. RHS.FloatImag = APFloat(Real.getSemantics());
  8999. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  9000. return false;
  9001. assert(!(LHSReal && RHSReal) &&
  9002. "Cannot have both operands of a complex operation be real.");
  9003. switch (E->getOpcode()) {
  9004. default: return Error(E);
  9005. case BO_Add:
  9006. if (Result.isComplexFloat()) {
  9007. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  9008. APFloat::rmNearestTiesToEven);
  9009. if (LHSReal)
  9010. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9011. else if (!RHSReal)
  9012. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  9013. APFloat::rmNearestTiesToEven);
  9014. } else {
  9015. Result.getComplexIntReal() += RHS.getComplexIntReal();
  9016. Result.getComplexIntImag() += RHS.getComplexIntImag();
  9017. }
  9018. break;
  9019. case BO_Sub:
  9020. if (Result.isComplexFloat()) {
  9021. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  9022. APFloat::rmNearestTiesToEven);
  9023. if (LHSReal) {
  9024. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9025. Result.getComplexFloatImag().changeSign();
  9026. } else if (!RHSReal) {
  9027. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  9028. APFloat::rmNearestTiesToEven);
  9029. }
  9030. } else {
  9031. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  9032. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  9033. }
  9034. break;
  9035. case BO_Mul:
  9036. if (Result.isComplexFloat()) {
  9037. // This is an implementation of complex multiplication according to the
  9038. // constraints laid out in C11 Annex G. The implemention uses the
  9039. // following naming scheme:
  9040. // (a + ib) * (c + id)
  9041. ComplexValue LHS = Result;
  9042. APFloat &A = LHS.getComplexFloatReal();
  9043. APFloat &B = LHS.getComplexFloatImag();
  9044. APFloat &C = RHS.getComplexFloatReal();
  9045. APFloat &D = RHS.getComplexFloatImag();
  9046. APFloat &ResR = Result.getComplexFloatReal();
  9047. APFloat &ResI = Result.getComplexFloatImag();
  9048. if (LHSReal) {
  9049. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  9050. ResR = A * C;
  9051. ResI = A * D;
  9052. } else if (RHSReal) {
  9053. ResR = C * A;
  9054. ResI = C * B;
  9055. } else {
  9056. // In the fully general case, we need to handle NaNs and infinities
  9057. // robustly.
  9058. APFloat AC = A * C;
  9059. APFloat BD = B * D;
  9060. APFloat AD = A * D;
  9061. APFloat BC = B * C;
  9062. ResR = AC - BD;
  9063. ResI = AD + BC;
  9064. if (ResR.isNaN() && ResI.isNaN()) {
  9065. bool Recalc = false;
  9066. if (A.isInfinity() || B.isInfinity()) {
  9067. A = APFloat::copySign(
  9068. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9069. B = APFloat::copySign(
  9070. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9071. if (C.isNaN())
  9072. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9073. if (D.isNaN())
  9074. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9075. Recalc = true;
  9076. }
  9077. if (C.isInfinity() || D.isInfinity()) {
  9078. C = APFloat::copySign(
  9079. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9080. D = APFloat::copySign(
  9081. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9082. if (A.isNaN())
  9083. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9084. if (B.isNaN())
  9085. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9086. Recalc = true;
  9087. }
  9088. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  9089. AD.isInfinity() || BC.isInfinity())) {
  9090. if (A.isNaN())
  9091. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9092. if (B.isNaN())
  9093. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9094. if (C.isNaN())
  9095. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9096. if (D.isNaN())
  9097. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9098. Recalc = true;
  9099. }
  9100. if (Recalc) {
  9101. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  9102. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  9103. }
  9104. }
  9105. }
  9106. } else {
  9107. ComplexValue LHS = Result;
  9108. Result.getComplexIntReal() =
  9109. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  9110. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  9111. Result.getComplexIntImag() =
  9112. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  9113. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  9114. }
  9115. break;
  9116. case BO_Div:
  9117. if (Result.isComplexFloat()) {
  9118. // This is an implementation of complex division according to the
  9119. // constraints laid out in C11 Annex G. The implemention uses the
  9120. // following naming scheme:
  9121. // (a + ib) / (c + id)
  9122. ComplexValue LHS = Result;
  9123. APFloat &A = LHS.getComplexFloatReal();
  9124. APFloat &B = LHS.getComplexFloatImag();
  9125. APFloat &C = RHS.getComplexFloatReal();
  9126. APFloat &D = RHS.getComplexFloatImag();
  9127. APFloat &ResR = Result.getComplexFloatReal();
  9128. APFloat &ResI = Result.getComplexFloatImag();
  9129. if (RHSReal) {
  9130. ResR = A / C;
  9131. ResI = B / C;
  9132. } else {
  9133. if (LHSReal) {
  9134. // No real optimizations we can do here, stub out with zero.
  9135. B = APFloat::getZero(A.getSemantics());
  9136. }
  9137. int DenomLogB = 0;
  9138. APFloat MaxCD = maxnum(abs(C), abs(D));
  9139. if (MaxCD.isFinite()) {
  9140. DenomLogB = ilogb(MaxCD);
  9141. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  9142. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  9143. }
  9144. APFloat Denom = C * C + D * D;
  9145. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  9146. APFloat::rmNearestTiesToEven);
  9147. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  9148. APFloat::rmNearestTiesToEven);
  9149. if (ResR.isNaN() && ResI.isNaN()) {
  9150. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  9151. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  9152. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  9153. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  9154. D.isFinite()) {
  9155. A = APFloat::copySign(
  9156. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9157. B = APFloat::copySign(
  9158. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9159. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  9160. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  9161. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  9162. C = APFloat::copySign(
  9163. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9164. D = APFloat::copySign(
  9165. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9166. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  9167. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  9168. }
  9169. }
  9170. }
  9171. } else {
  9172. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  9173. return Error(E, diag::note_expr_divide_by_zero);
  9174. ComplexValue LHS = Result;
  9175. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9176. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  9177. Result.getComplexIntReal() =
  9178. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9179. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  9180. Result.getComplexIntImag() =
  9181. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  9182. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  9183. }
  9184. break;
  9185. }
  9186. return true;
  9187. }
  9188. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9189. // Get the operand value into 'Result'.
  9190. if (!Visit(E->getSubExpr()))
  9191. return false;
  9192. switch (E->getOpcode()) {
  9193. default:
  9194. return Error(E);
  9195. case UO_Extension:
  9196. return true;
  9197. case UO_Plus:
  9198. // The result is always just the subexpr.
  9199. return true;
  9200. case UO_Minus:
  9201. if (Result.isComplexFloat()) {
  9202. Result.getComplexFloatReal().changeSign();
  9203. Result.getComplexFloatImag().changeSign();
  9204. }
  9205. else {
  9206. Result.getComplexIntReal() = -Result.getComplexIntReal();
  9207. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9208. }
  9209. return true;
  9210. case UO_Not:
  9211. if (Result.isComplexFloat())
  9212. Result.getComplexFloatImag().changeSign();
  9213. else
  9214. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9215. return true;
  9216. }
  9217. }
  9218. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  9219. if (E->getNumInits() == 2) {
  9220. if (E->getType()->isComplexType()) {
  9221. Result.makeComplexFloat();
  9222. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  9223. return false;
  9224. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  9225. return false;
  9226. } else {
  9227. Result.makeComplexInt();
  9228. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  9229. return false;
  9230. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  9231. return false;
  9232. }
  9233. return true;
  9234. }
  9235. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  9236. }
  9237. //===----------------------------------------------------------------------===//
  9238. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  9239. // implicit conversion.
  9240. //===----------------------------------------------------------------------===//
  9241. namespace {
  9242. class AtomicExprEvaluator :
  9243. public ExprEvaluatorBase<AtomicExprEvaluator> {
  9244. const LValue *This;
  9245. APValue &Result;
  9246. public:
  9247. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  9248. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  9249. bool Success(const APValue &V, const Expr *E) {
  9250. Result = V;
  9251. return true;
  9252. }
  9253. bool ZeroInitialization(const Expr *E) {
  9254. ImplicitValueInitExpr VIE(
  9255. E->getType()->castAs<AtomicType>()->getValueType());
  9256. // For atomic-qualified class (and array) types in C++, initialize the
  9257. // _Atomic-wrapped subobject directly, in-place.
  9258. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  9259. : Evaluate(Result, Info, &VIE);
  9260. }
  9261. bool VisitCastExpr(const CastExpr *E) {
  9262. switch (E->getCastKind()) {
  9263. default:
  9264. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9265. case CK_NonAtomicToAtomic:
  9266. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  9267. : Evaluate(Result, Info, E->getSubExpr());
  9268. }
  9269. }
  9270. };
  9271. } // end anonymous namespace
  9272. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  9273. EvalInfo &Info) {
  9274. assert(E->isRValue() && E->getType()->isAtomicType());
  9275. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  9276. }
  9277. //===----------------------------------------------------------------------===//
  9278. // Void expression evaluation, primarily for a cast to void on the LHS of a
  9279. // comma operator
  9280. //===----------------------------------------------------------------------===//
  9281. namespace {
  9282. class VoidExprEvaluator
  9283. : public ExprEvaluatorBase<VoidExprEvaluator> {
  9284. public:
  9285. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  9286. bool Success(const APValue &V, const Expr *e) { return true; }
  9287. bool ZeroInitialization(const Expr *E) { return true; }
  9288. bool VisitCastExpr(const CastExpr *E) {
  9289. switch (E->getCastKind()) {
  9290. default:
  9291. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9292. case CK_ToVoid:
  9293. VisitIgnoredValue(E->getSubExpr());
  9294. return true;
  9295. }
  9296. }
  9297. bool VisitCallExpr(const CallExpr *E) {
  9298. switch (E->getBuiltinCallee()) {
  9299. default:
  9300. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9301. case Builtin::BI__assume:
  9302. case Builtin::BI__builtin_assume:
  9303. // The argument is not evaluated!
  9304. return true;
  9305. }
  9306. }
  9307. };
  9308. } // end anonymous namespace
  9309. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  9310. assert(E->isRValue() && E->getType()->isVoidType());
  9311. return VoidExprEvaluator(Info).Visit(E);
  9312. }
  9313. //===----------------------------------------------------------------------===//
  9314. // Top level Expr::EvaluateAsRValue method.
  9315. //===----------------------------------------------------------------------===//
  9316. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  9317. // In C, function designators are not lvalues, but we evaluate them as if they
  9318. // are.
  9319. QualType T = E->getType();
  9320. if (E->isGLValue() || T->isFunctionType()) {
  9321. LValue LV;
  9322. if (!EvaluateLValue(E, LV, Info))
  9323. return false;
  9324. LV.moveInto(Result);
  9325. } else if (T->isVectorType()) {
  9326. if (!EvaluateVector(E, Result, Info))
  9327. return false;
  9328. } else if (T->isIntegralOrEnumerationType()) {
  9329. if (!IntExprEvaluator(Info, Result).Visit(E))
  9330. return false;
  9331. } else if (T->hasPointerRepresentation()) {
  9332. LValue LV;
  9333. if (!EvaluatePointer(E, LV, Info))
  9334. return false;
  9335. LV.moveInto(Result);
  9336. } else if (T->isRealFloatingType()) {
  9337. llvm::APFloat F(0.0);
  9338. if (!EvaluateFloat(E, F, Info))
  9339. return false;
  9340. Result = APValue(F);
  9341. } else if (T->isAnyComplexType()) {
  9342. ComplexValue C;
  9343. if (!EvaluateComplex(E, C, Info))
  9344. return false;
  9345. C.moveInto(Result);
  9346. } else if (T->isFixedPointType()) {
  9347. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  9348. } else if (T->isMemberPointerType()) {
  9349. MemberPtr P;
  9350. if (!EvaluateMemberPointer(E, P, Info))
  9351. return false;
  9352. P.moveInto(Result);
  9353. return true;
  9354. } else if (T->isArrayType()) {
  9355. LValue LV;
  9356. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9357. if (!EvaluateArray(E, LV, Value, Info))
  9358. return false;
  9359. Result = Value;
  9360. } else if (T->isRecordType()) {
  9361. LValue LV;
  9362. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9363. if (!EvaluateRecord(E, LV, Value, Info))
  9364. return false;
  9365. Result = Value;
  9366. } else if (T->isVoidType()) {
  9367. if (!Info.getLangOpts().CPlusPlus11)
  9368. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  9369. << E->getType();
  9370. if (!EvaluateVoid(E, Info))
  9371. return false;
  9372. } else if (T->isAtomicType()) {
  9373. QualType Unqual = T.getAtomicUnqualifiedType();
  9374. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  9375. LValue LV;
  9376. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9377. if (!EvaluateAtomic(E, &LV, Value, Info))
  9378. return false;
  9379. } else {
  9380. if (!EvaluateAtomic(E, nullptr, Result, Info))
  9381. return false;
  9382. }
  9383. } else if (Info.getLangOpts().CPlusPlus11) {
  9384. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  9385. return false;
  9386. } else {
  9387. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9388. return false;
  9389. }
  9390. return true;
  9391. }
  9392. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  9393. /// cases, the in-place evaluation is essential, since later initializers for
  9394. /// an object can indirectly refer to subobjects which were initialized earlier.
  9395. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  9396. const Expr *E, bool AllowNonLiteralTypes) {
  9397. assert(!E->isValueDependent());
  9398. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  9399. return false;
  9400. if (E->isRValue()) {
  9401. // Evaluate arrays and record types in-place, so that later initializers can
  9402. // refer to earlier-initialized members of the object.
  9403. QualType T = E->getType();
  9404. if (T->isArrayType())
  9405. return EvaluateArray(E, This, Result, Info);
  9406. else if (T->isRecordType())
  9407. return EvaluateRecord(E, This, Result, Info);
  9408. else if (T->isAtomicType()) {
  9409. QualType Unqual = T.getAtomicUnqualifiedType();
  9410. if (Unqual->isArrayType() || Unqual->isRecordType())
  9411. return EvaluateAtomic(E, &This, Result, Info);
  9412. }
  9413. }
  9414. // For any other type, in-place evaluation is unimportant.
  9415. return Evaluate(Result, Info, E);
  9416. }
  9417. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  9418. /// lvalue-to-rvalue cast if it is an lvalue.
  9419. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  9420. if (E->getType().isNull())
  9421. return false;
  9422. if (!CheckLiteralType(Info, E))
  9423. return false;
  9424. if (!::Evaluate(Result, Info, E))
  9425. return false;
  9426. if (E->isGLValue()) {
  9427. LValue LV;
  9428. LV.setFrom(Info.Ctx, Result);
  9429. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  9430. return false;
  9431. }
  9432. // Check this core constant expression is a constant expression.
  9433. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  9434. }
  9435. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  9436. const ASTContext &Ctx, bool &IsConst) {
  9437. // Fast-path evaluations of integer literals, since we sometimes see files
  9438. // containing vast quantities of these.
  9439. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  9440. Result.Val = APValue(APSInt(L->getValue(),
  9441. L->getType()->isUnsignedIntegerType()));
  9442. IsConst = true;
  9443. return true;
  9444. }
  9445. // This case should be rare, but we need to check it before we check on
  9446. // the type below.
  9447. if (Exp->getType().isNull()) {
  9448. IsConst = false;
  9449. return true;
  9450. }
  9451. // FIXME: Evaluating values of large array and record types can cause
  9452. // performance problems. Only do so in C++11 for now.
  9453. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  9454. Exp->getType()->isRecordType()) &&
  9455. !Ctx.getLangOpts().CPlusPlus11) {
  9456. IsConst = false;
  9457. return true;
  9458. }
  9459. return false;
  9460. }
  9461. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  9462. /// any crazy technique (that has nothing to do with language standards) that
  9463. /// we want to. If this function returns true, it returns the folded constant
  9464. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  9465. /// will be applied to the result.
  9466. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  9467. bool IsConst;
  9468. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
  9469. return IsConst;
  9470. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  9471. return ::EvaluateAsRValue(Info, this, Result.Val);
  9472. }
  9473. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  9474. const ASTContext &Ctx) const {
  9475. EvalResult Scratch;
  9476. return EvaluateAsRValue(Scratch, Ctx) &&
  9477. HandleConversionToBool(Scratch.Val, Result);
  9478. }
  9479. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  9480. Expr::SideEffectsKind SEK) {
  9481. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  9482. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  9483. }
  9484. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  9485. SideEffectsKind AllowSideEffects) const {
  9486. if (!getType()->isIntegralOrEnumerationType())
  9487. return false;
  9488. EvalResult ExprResult;
  9489. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  9490. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9491. return false;
  9492. Result = ExprResult.Val.getInt();
  9493. return true;
  9494. }
  9495. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  9496. SideEffectsKind AllowSideEffects) const {
  9497. if (!getType()->isRealFloatingType())
  9498. return false;
  9499. EvalResult ExprResult;
  9500. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
  9501. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9502. return false;
  9503. Result = ExprResult.Val.getFloat();
  9504. return true;
  9505. }
  9506. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  9507. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  9508. LValue LV;
  9509. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  9510. !CheckLValueConstantExpression(Info, getExprLoc(),
  9511. Ctx.getLValueReferenceType(getType()), LV,
  9512. Expr::EvaluateForCodeGen))
  9513. return false;
  9514. LV.moveInto(Result.Val);
  9515. return true;
  9516. }
  9517. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  9518. const ASTContext &Ctx) const {
  9519. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  9520. EvalInfo Info(Ctx, Result, EM);
  9521. if (!::Evaluate(Result.Val, Info, this))
  9522. return false;
  9523. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  9524. Usage);
  9525. }
  9526. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  9527. const VarDecl *VD,
  9528. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  9529. // FIXME: Evaluating initializers for large array and record types can cause
  9530. // performance problems. Only do so in C++11 for now.
  9531. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  9532. !Ctx.getLangOpts().CPlusPlus11)
  9533. return false;
  9534. Expr::EvalStatus EStatus;
  9535. EStatus.Diag = &Notes;
  9536. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  9537. ? EvalInfo::EM_ConstantExpression
  9538. : EvalInfo::EM_ConstantFold);
  9539. InitInfo.setEvaluatingDecl(VD, Value);
  9540. LValue LVal;
  9541. LVal.set(VD);
  9542. // C++11 [basic.start.init]p2:
  9543. // Variables with static storage duration or thread storage duration shall be
  9544. // zero-initialized before any other initialization takes place.
  9545. // This behavior is not present in C.
  9546. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  9547. !VD->getType()->isReferenceType()) {
  9548. ImplicitValueInitExpr VIE(VD->getType());
  9549. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  9550. /*AllowNonLiteralTypes=*/true))
  9551. return false;
  9552. }
  9553. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  9554. /*AllowNonLiteralTypes=*/true) ||
  9555. EStatus.HasSideEffects)
  9556. return false;
  9557. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  9558. Value);
  9559. }
  9560. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  9561. /// constant folded, but discard the result.
  9562. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  9563. EvalResult Result;
  9564. return EvaluateAsRValue(Result, Ctx) &&
  9565. !hasUnacceptableSideEffect(Result, SEK);
  9566. }
  9567. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  9568. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  9569. EvalResult EvalResult;
  9570. EvalResult.Diag = Diag;
  9571. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  9572. (void)Result;
  9573. assert(Result && "Could not evaluate expression");
  9574. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  9575. return EvalResult.Val.getInt();
  9576. }
  9577. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  9578. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  9579. EvalResult EvalResult;
  9580. EvalResult.Diag = Diag;
  9581. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  9582. bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val);
  9583. (void)Result;
  9584. assert(Result && "Could not evaluate expression");
  9585. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  9586. return EvalResult.Val.getInt();
  9587. }
  9588. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  9589. bool IsConst;
  9590. EvalResult EvalResult;
  9591. if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
  9592. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  9593. (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
  9594. }
  9595. }
  9596. bool Expr::EvalResult::isGlobalLValue() const {
  9597. assert(Val.isLValue());
  9598. return IsGlobalLValue(Val.getLValueBase());
  9599. }
  9600. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  9601. /// an integer constant expression.
  9602. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  9603. /// comma, etc
  9604. // CheckICE - This function does the fundamental ICE checking: the returned
  9605. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  9606. // and a (possibly null) SourceLocation indicating the location of the problem.
  9607. //
  9608. // Note that to reduce code duplication, this helper does no evaluation
  9609. // itself; the caller checks whether the expression is evaluatable, and
  9610. // in the rare cases where CheckICE actually cares about the evaluated
  9611. // value, it calls into Evaluate.
  9612. namespace {
  9613. enum ICEKind {
  9614. /// This expression is an ICE.
  9615. IK_ICE,
  9616. /// This expression is not an ICE, but if it isn't evaluated, it's
  9617. /// a legal subexpression for an ICE. This return value is used to handle
  9618. /// the comma operator in C99 mode, and non-constant subexpressions.
  9619. IK_ICEIfUnevaluated,
  9620. /// This expression is not an ICE, and is not a legal subexpression for one.
  9621. IK_NotICE
  9622. };
  9623. struct ICEDiag {
  9624. ICEKind Kind;
  9625. SourceLocation Loc;
  9626. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  9627. };
  9628. }
  9629. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  9630. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  9631. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  9632. Expr::EvalResult EVResult;
  9633. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  9634. !EVResult.Val.isInt())
  9635. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9636. return NoDiag();
  9637. }
  9638. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  9639. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  9640. if (!E->getType()->isIntegralOrEnumerationType())
  9641. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9642. switch (E->getStmtClass()) {
  9643. #define ABSTRACT_STMT(Node)
  9644. #define STMT(Node, Base) case Expr::Node##Class:
  9645. #define EXPR(Node, Base)
  9646. #include "clang/AST/StmtNodes.inc"
  9647. case Expr::PredefinedExprClass:
  9648. case Expr::FloatingLiteralClass:
  9649. case Expr::ImaginaryLiteralClass:
  9650. case Expr::StringLiteralClass:
  9651. case Expr::ArraySubscriptExprClass:
  9652. case Expr::OMPArraySectionExprClass:
  9653. case Expr::MemberExprClass:
  9654. case Expr::CompoundAssignOperatorClass:
  9655. case Expr::CompoundLiteralExprClass:
  9656. case Expr::ExtVectorElementExprClass:
  9657. case Expr::DesignatedInitExprClass:
  9658. case Expr::ArrayInitLoopExprClass:
  9659. case Expr::ArrayInitIndexExprClass:
  9660. case Expr::NoInitExprClass:
  9661. case Expr::DesignatedInitUpdateExprClass:
  9662. case Expr::ImplicitValueInitExprClass:
  9663. case Expr::ParenListExprClass:
  9664. case Expr::VAArgExprClass:
  9665. case Expr::AddrLabelExprClass:
  9666. case Expr::StmtExprClass:
  9667. case Expr::CXXMemberCallExprClass:
  9668. case Expr::CUDAKernelCallExprClass:
  9669. case Expr::CXXDynamicCastExprClass:
  9670. case Expr::CXXTypeidExprClass:
  9671. case Expr::CXXUuidofExprClass:
  9672. case Expr::MSPropertyRefExprClass:
  9673. case Expr::MSPropertySubscriptExprClass:
  9674. case Expr::CXXNullPtrLiteralExprClass:
  9675. case Expr::UserDefinedLiteralClass:
  9676. case Expr::CXXThisExprClass:
  9677. case Expr::CXXThrowExprClass:
  9678. case Expr::CXXNewExprClass:
  9679. case Expr::CXXDeleteExprClass:
  9680. case Expr::CXXPseudoDestructorExprClass:
  9681. case Expr::UnresolvedLookupExprClass:
  9682. case Expr::TypoExprClass:
  9683. case Expr::DependentScopeDeclRefExprClass:
  9684. case Expr::CXXConstructExprClass:
  9685. case Expr::CXXInheritedCtorInitExprClass:
  9686. case Expr::CXXStdInitializerListExprClass:
  9687. case Expr::CXXBindTemporaryExprClass:
  9688. case Expr::ExprWithCleanupsClass:
  9689. case Expr::CXXTemporaryObjectExprClass:
  9690. case Expr::CXXUnresolvedConstructExprClass:
  9691. case Expr::CXXDependentScopeMemberExprClass:
  9692. case Expr::UnresolvedMemberExprClass:
  9693. case Expr::ObjCStringLiteralClass:
  9694. case Expr::ObjCBoxedExprClass:
  9695. case Expr::ObjCArrayLiteralClass:
  9696. case Expr::ObjCDictionaryLiteralClass:
  9697. case Expr::ObjCEncodeExprClass:
  9698. case Expr::ObjCMessageExprClass:
  9699. case Expr::ObjCSelectorExprClass:
  9700. case Expr::ObjCProtocolExprClass:
  9701. case Expr::ObjCIvarRefExprClass:
  9702. case Expr::ObjCPropertyRefExprClass:
  9703. case Expr::ObjCSubscriptRefExprClass:
  9704. case Expr::ObjCIsaExprClass:
  9705. case Expr::ObjCAvailabilityCheckExprClass:
  9706. case Expr::ShuffleVectorExprClass:
  9707. case Expr::ConvertVectorExprClass:
  9708. case Expr::BlockExprClass:
  9709. case Expr::NoStmtClass:
  9710. case Expr::OpaqueValueExprClass:
  9711. case Expr::PackExpansionExprClass:
  9712. case Expr::SubstNonTypeTemplateParmPackExprClass:
  9713. case Expr::FunctionParmPackExprClass:
  9714. case Expr::AsTypeExprClass:
  9715. case Expr::ObjCIndirectCopyRestoreExprClass:
  9716. case Expr::MaterializeTemporaryExprClass:
  9717. case Expr::PseudoObjectExprClass:
  9718. case Expr::AtomicExprClass:
  9719. case Expr::LambdaExprClass:
  9720. case Expr::CXXFoldExprClass:
  9721. case Expr::CoawaitExprClass:
  9722. case Expr::DependentCoawaitExprClass:
  9723. case Expr::CoyieldExprClass:
  9724. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9725. case Expr::InitListExprClass: {
  9726. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  9727. // form "T x = { a };" is equivalent to "T x = a;".
  9728. // Unless we're initializing a reference, T is a scalar as it is known to be
  9729. // of integral or enumeration type.
  9730. if (E->isRValue())
  9731. if (cast<InitListExpr>(E)->getNumInits() == 1)
  9732. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  9733. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9734. }
  9735. case Expr::SizeOfPackExprClass:
  9736. case Expr::GNUNullExprClass:
  9737. // GCC considers the GNU __null value to be an integral constant expression.
  9738. return NoDiag();
  9739. case Expr::SubstNonTypeTemplateParmExprClass:
  9740. return
  9741. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  9742. case Expr::ConstantExprClass:
  9743. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  9744. case Expr::ParenExprClass:
  9745. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  9746. case Expr::GenericSelectionExprClass:
  9747. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  9748. case Expr::IntegerLiteralClass:
  9749. case Expr::FixedPointLiteralClass:
  9750. case Expr::CharacterLiteralClass:
  9751. case Expr::ObjCBoolLiteralExprClass:
  9752. case Expr::CXXBoolLiteralExprClass:
  9753. case Expr::CXXScalarValueInitExprClass:
  9754. case Expr::TypeTraitExprClass:
  9755. case Expr::ArrayTypeTraitExprClass:
  9756. case Expr::ExpressionTraitExprClass:
  9757. case Expr::CXXNoexceptExprClass:
  9758. return NoDiag();
  9759. case Expr::CallExprClass:
  9760. case Expr::CXXOperatorCallExprClass: {
  9761. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  9762. // constant expressions, but they can never be ICEs because an ICE cannot
  9763. // contain an operand of (pointer to) function type.
  9764. const CallExpr *CE = cast<CallExpr>(E);
  9765. if (CE->getBuiltinCallee())
  9766. return CheckEvalInICE(E, Ctx);
  9767. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9768. }
  9769. case Expr::DeclRefExprClass: {
  9770. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  9771. return NoDiag();
  9772. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  9773. if (Ctx.getLangOpts().CPlusPlus &&
  9774. D && IsConstNonVolatile(D->getType())) {
  9775. // Parameter variables are never constants. Without this check,
  9776. // getAnyInitializer() can find a default argument, which leads
  9777. // to chaos.
  9778. if (isa<ParmVarDecl>(D))
  9779. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9780. // C++ 7.1.5.1p2
  9781. // A variable of non-volatile const-qualified integral or enumeration
  9782. // type initialized by an ICE can be used in ICEs.
  9783. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  9784. if (!Dcl->getType()->isIntegralOrEnumerationType())
  9785. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9786. const VarDecl *VD;
  9787. // Look for a declaration of this variable that has an initializer, and
  9788. // check whether it is an ICE.
  9789. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  9790. return NoDiag();
  9791. else
  9792. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9793. }
  9794. }
  9795. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9796. }
  9797. case Expr::UnaryOperatorClass: {
  9798. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  9799. switch (Exp->getOpcode()) {
  9800. case UO_PostInc:
  9801. case UO_PostDec:
  9802. case UO_PreInc:
  9803. case UO_PreDec:
  9804. case UO_AddrOf:
  9805. case UO_Deref:
  9806. case UO_Coawait:
  9807. // C99 6.6/3 allows increment and decrement within unevaluated
  9808. // subexpressions of constant expressions, but they can never be ICEs
  9809. // because an ICE cannot contain an lvalue operand.
  9810. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9811. case UO_Extension:
  9812. case UO_LNot:
  9813. case UO_Plus:
  9814. case UO_Minus:
  9815. case UO_Not:
  9816. case UO_Real:
  9817. case UO_Imag:
  9818. return CheckICE(Exp->getSubExpr(), Ctx);
  9819. }
  9820. llvm_unreachable("invalid unary operator class");
  9821. }
  9822. case Expr::OffsetOfExprClass: {
  9823. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  9824. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  9825. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  9826. // compliance: we should warn earlier for offsetof expressions with
  9827. // array subscripts that aren't ICEs, and if the array subscripts
  9828. // are ICEs, the value of the offsetof must be an integer constant.
  9829. return CheckEvalInICE(E, Ctx);
  9830. }
  9831. case Expr::UnaryExprOrTypeTraitExprClass: {
  9832. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  9833. if ((Exp->getKind() == UETT_SizeOf) &&
  9834. Exp->getTypeOfArgument()->isVariableArrayType())
  9835. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9836. return NoDiag();
  9837. }
  9838. case Expr::BinaryOperatorClass: {
  9839. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  9840. switch (Exp->getOpcode()) {
  9841. case BO_PtrMemD:
  9842. case BO_PtrMemI:
  9843. case BO_Assign:
  9844. case BO_MulAssign:
  9845. case BO_DivAssign:
  9846. case BO_RemAssign:
  9847. case BO_AddAssign:
  9848. case BO_SubAssign:
  9849. case BO_ShlAssign:
  9850. case BO_ShrAssign:
  9851. case BO_AndAssign:
  9852. case BO_XorAssign:
  9853. case BO_OrAssign:
  9854. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  9855. // constant expressions, but they can never be ICEs because an ICE cannot
  9856. // contain an lvalue operand.
  9857. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9858. case BO_Mul:
  9859. case BO_Div:
  9860. case BO_Rem:
  9861. case BO_Add:
  9862. case BO_Sub:
  9863. case BO_Shl:
  9864. case BO_Shr:
  9865. case BO_LT:
  9866. case BO_GT:
  9867. case BO_LE:
  9868. case BO_GE:
  9869. case BO_EQ:
  9870. case BO_NE:
  9871. case BO_And:
  9872. case BO_Xor:
  9873. case BO_Or:
  9874. case BO_Comma:
  9875. case BO_Cmp: {
  9876. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9877. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9878. if (Exp->getOpcode() == BO_Div ||
  9879. Exp->getOpcode() == BO_Rem) {
  9880. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  9881. // we don't evaluate one.
  9882. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  9883. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  9884. if (REval == 0)
  9885. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9886. if (REval.isSigned() && REval.isAllOnesValue()) {
  9887. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  9888. if (LEval.isMinSignedValue())
  9889. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9890. }
  9891. }
  9892. }
  9893. if (Exp->getOpcode() == BO_Comma) {
  9894. if (Ctx.getLangOpts().C99) {
  9895. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  9896. // if it isn't evaluated.
  9897. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  9898. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9899. } else {
  9900. // In both C89 and C++, commas in ICEs are illegal.
  9901. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9902. }
  9903. }
  9904. return Worst(LHSResult, RHSResult);
  9905. }
  9906. case BO_LAnd:
  9907. case BO_LOr: {
  9908. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9909. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9910. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  9911. // Rare case where the RHS has a comma "side-effect"; we need
  9912. // to actually check the condition to see whether the side
  9913. // with the comma is evaluated.
  9914. if ((Exp->getOpcode() == BO_LAnd) !=
  9915. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  9916. return RHSResult;
  9917. return NoDiag();
  9918. }
  9919. return Worst(LHSResult, RHSResult);
  9920. }
  9921. }
  9922. llvm_unreachable("invalid binary operator kind");
  9923. }
  9924. case Expr::ImplicitCastExprClass:
  9925. case Expr::CStyleCastExprClass:
  9926. case Expr::CXXFunctionalCastExprClass:
  9927. case Expr::CXXStaticCastExprClass:
  9928. case Expr::CXXReinterpretCastExprClass:
  9929. case Expr::CXXConstCastExprClass:
  9930. case Expr::ObjCBridgedCastExprClass: {
  9931. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  9932. if (isa<ExplicitCastExpr>(E)) {
  9933. if (const FloatingLiteral *FL
  9934. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  9935. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  9936. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  9937. APSInt IgnoredVal(DestWidth, !DestSigned);
  9938. bool Ignored;
  9939. // If the value does not fit in the destination type, the behavior is
  9940. // undefined, so we are not required to treat it as a constant
  9941. // expression.
  9942. if (FL->getValue().convertToInteger(IgnoredVal,
  9943. llvm::APFloat::rmTowardZero,
  9944. &Ignored) & APFloat::opInvalidOp)
  9945. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9946. return NoDiag();
  9947. }
  9948. }
  9949. switch (cast<CastExpr>(E)->getCastKind()) {
  9950. case CK_LValueToRValue:
  9951. case CK_AtomicToNonAtomic:
  9952. case CK_NonAtomicToAtomic:
  9953. case CK_NoOp:
  9954. case CK_IntegralToBoolean:
  9955. case CK_IntegralCast:
  9956. return CheckICE(SubExpr, Ctx);
  9957. default:
  9958. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9959. }
  9960. }
  9961. case Expr::BinaryConditionalOperatorClass: {
  9962. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  9963. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  9964. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  9965. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9966. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  9967. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  9968. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  9969. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  9970. return FalseResult;
  9971. }
  9972. case Expr::ConditionalOperatorClass: {
  9973. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  9974. // If the condition (ignoring parens) is a __builtin_constant_p call,
  9975. // then only the true side is actually considered in an integer constant
  9976. // expression, and it is fully evaluated. This is an important GNU
  9977. // extension. See GCC PR38377 for discussion.
  9978. if (const CallExpr *CallCE
  9979. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  9980. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  9981. return CheckEvalInICE(E, Ctx);
  9982. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  9983. if (CondResult.Kind == IK_NotICE)
  9984. return CondResult;
  9985. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  9986. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9987. if (TrueResult.Kind == IK_NotICE)
  9988. return TrueResult;
  9989. if (FalseResult.Kind == IK_NotICE)
  9990. return FalseResult;
  9991. if (CondResult.Kind == IK_ICEIfUnevaluated)
  9992. return CondResult;
  9993. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  9994. return NoDiag();
  9995. // Rare case where the diagnostics depend on which side is evaluated
  9996. // Note that if we get here, CondResult is 0, and at least one of
  9997. // TrueResult and FalseResult is non-zero.
  9998. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  9999. return FalseResult;
  10000. return TrueResult;
  10001. }
  10002. case Expr::CXXDefaultArgExprClass:
  10003. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  10004. case Expr::CXXDefaultInitExprClass:
  10005. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  10006. case Expr::ChooseExprClass: {
  10007. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  10008. }
  10009. }
  10010. llvm_unreachable("Invalid StmtClass!");
  10011. }
  10012. /// Evaluate an expression as a C++11 integral constant expression.
  10013. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  10014. const Expr *E,
  10015. llvm::APSInt *Value,
  10016. SourceLocation *Loc) {
  10017. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10018. if (Loc) *Loc = E->getExprLoc();
  10019. return false;
  10020. }
  10021. APValue Result;
  10022. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  10023. return false;
  10024. if (!Result.isInt()) {
  10025. if (Loc) *Loc = E->getExprLoc();
  10026. return false;
  10027. }
  10028. if (Value) *Value = Result.getInt();
  10029. return true;
  10030. }
  10031. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  10032. SourceLocation *Loc) const {
  10033. if (Ctx.getLangOpts().CPlusPlus11)
  10034. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  10035. ICEDiag D = CheckICE(this, Ctx);
  10036. if (D.Kind != IK_ICE) {
  10037. if (Loc) *Loc = D.Loc;
  10038. return false;
  10039. }
  10040. return true;
  10041. }
  10042. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  10043. SourceLocation *Loc, bool isEvaluated) const {
  10044. if (Ctx.getLangOpts().CPlusPlus11)
  10045. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  10046. if (!isIntegerConstantExpr(Ctx, Loc))
  10047. return false;
  10048. // The only possible side-effects here are due to UB discovered in the
  10049. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  10050. // required to treat the expression as an ICE, so we produce the folded
  10051. // value.
  10052. if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
  10053. llvm_unreachable("ICE cannot be evaluated!");
  10054. return true;
  10055. }
  10056. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  10057. return CheckICE(this, Ctx).Kind == IK_ICE;
  10058. }
  10059. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  10060. SourceLocation *Loc) const {
  10061. // We support this checking in C++98 mode in order to diagnose compatibility
  10062. // issues.
  10063. assert(Ctx.getLangOpts().CPlusPlus);
  10064. // Build evaluation settings.
  10065. Expr::EvalStatus Status;
  10066. SmallVector<PartialDiagnosticAt, 8> Diags;
  10067. Status.Diag = &Diags;
  10068. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  10069. APValue Scratch;
  10070. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  10071. if (!Diags.empty()) {
  10072. IsConstExpr = false;
  10073. if (Loc) *Loc = Diags[0].first;
  10074. } else if (!IsConstExpr) {
  10075. // FIXME: This shouldn't happen.
  10076. if (Loc) *Loc = getExprLoc();
  10077. }
  10078. return IsConstExpr;
  10079. }
  10080. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  10081. const FunctionDecl *Callee,
  10082. ArrayRef<const Expr*> Args,
  10083. const Expr *This) const {
  10084. Expr::EvalStatus Status;
  10085. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  10086. LValue ThisVal;
  10087. const LValue *ThisPtr = nullptr;
  10088. if (This) {
  10089. #ifndef NDEBUG
  10090. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  10091. assert(MD && "Don't provide `this` for non-methods.");
  10092. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  10093. #endif
  10094. if (EvaluateObjectArgument(Info, This, ThisVal))
  10095. ThisPtr = &ThisVal;
  10096. if (Info.EvalStatus.HasSideEffects)
  10097. return false;
  10098. }
  10099. ArgVector ArgValues(Args.size());
  10100. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  10101. I != E; ++I) {
  10102. if ((*I)->isValueDependent() ||
  10103. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  10104. // If evaluation fails, throw away the argument entirely.
  10105. ArgValues[I - Args.begin()] = APValue();
  10106. if (Info.EvalStatus.HasSideEffects)
  10107. return false;
  10108. }
  10109. // Build fake call to Callee.
  10110. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  10111. ArgValues.data());
  10112. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  10113. }
  10114. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  10115. SmallVectorImpl<
  10116. PartialDiagnosticAt> &Diags) {
  10117. // FIXME: It would be useful to check constexpr function templates, but at the
  10118. // moment the constant expression evaluator cannot cope with the non-rigorous
  10119. // ASTs which we build for dependent expressions.
  10120. if (FD->isDependentContext())
  10121. return true;
  10122. Expr::EvalStatus Status;
  10123. Status.Diag = &Diags;
  10124. EvalInfo Info(FD->getASTContext(), Status,
  10125. EvalInfo::EM_PotentialConstantExpression);
  10126. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  10127. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  10128. // Fabricate an arbitrary expression on the stack and pretend that it
  10129. // is a temporary being used as the 'this' pointer.
  10130. LValue This;
  10131. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  10132. This.set({&VIE, Info.CurrentCall->Index});
  10133. ArrayRef<const Expr*> Args;
  10134. APValue Scratch;
  10135. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  10136. // Evaluate the call as a constant initializer, to allow the construction
  10137. // of objects of non-literal types.
  10138. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  10139. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  10140. } else {
  10141. SourceLocation Loc = FD->getLocation();
  10142. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  10143. Args, FD->getBody(), Info, Scratch, nullptr);
  10144. }
  10145. return Diags.empty();
  10146. }
  10147. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  10148. const FunctionDecl *FD,
  10149. SmallVectorImpl<
  10150. PartialDiagnosticAt> &Diags) {
  10151. Expr::EvalStatus Status;
  10152. Status.Diag = &Diags;
  10153. EvalInfo Info(FD->getASTContext(), Status,
  10154. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  10155. // Fabricate a call stack frame to give the arguments a plausible cover story.
  10156. ArrayRef<const Expr*> Args;
  10157. ArgVector ArgValues(0);
  10158. bool Success = EvaluateArgs(Args, ArgValues, Info);
  10159. (void)Success;
  10160. assert(Success &&
  10161. "Failed to set up arguments for potential constant evaluation");
  10162. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  10163. APValue ResultScratch;
  10164. Evaluate(ResultScratch, Info, E);
  10165. return Diags.empty();
  10166. }
  10167. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  10168. unsigned Type) const {
  10169. if (!getType()->isPointerType())
  10170. return false;
  10171. Expr::EvalStatus Status;
  10172. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  10173. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  10174. }