ExprConstant.cpp 467 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Expr constant evaluator.
  10. //
  11. // Constant expression evaluation produces four main results:
  12. //
  13. // * A success/failure flag indicating whether constant folding was successful.
  14. // This is the 'bool' return value used by most of the code in this file. A
  15. // 'false' return value indicates that constant folding has failed, and any
  16. // appropriate diagnostic has already been produced.
  17. //
  18. // * An evaluated result, valid only if constant folding has not failed.
  19. //
  20. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  21. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  22. // where it is possible to determine the evaluated result regardless.
  23. //
  24. // * A set of notes indicating why the evaluation was not a constant expression
  25. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  26. // too, why the expression could not be folded.
  27. //
  28. // If we are checking for a potential constant expression, failure to constant
  29. // fold a potential constant sub-expression will be indicated by a 'false'
  30. // return value (the expression could not be folded) and no diagnostic (the
  31. // expression is not necessarily non-constant).
  32. //
  33. //===----------------------------------------------------------------------===//
  34. #include <cstring>
  35. #include <functional>
  36. #include "Interp/Context.h"
  37. #include "Interp/Frame.h"
  38. #include "Interp/State.h"
  39. #include "clang/AST/APValue.h"
  40. #include "clang/AST/ASTContext.h"
  41. #include "clang/AST/ASTDiagnostic.h"
  42. #include "clang/AST/ASTLambda.h"
  43. #include "clang/AST/CXXInheritance.h"
  44. #include "clang/AST/CharUnits.h"
  45. #include "clang/AST/CurrentSourceLocExprScope.h"
  46. #include "clang/AST/Expr.h"
  47. #include "clang/AST/OSLog.h"
  48. #include "clang/AST/OptionalDiagnostic.h"
  49. #include "clang/AST/RecordLayout.h"
  50. #include "clang/AST/StmtVisitor.h"
  51. #include "clang/AST/TypeLoc.h"
  52. #include "clang/Basic/Builtins.h"
  53. #include "clang/Basic/FixedPoint.h"
  54. #include "clang/Basic/TargetInfo.h"
  55. #include "llvm/ADT/Optional.h"
  56. #include "llvm/ADT/SmallBitVector.h"
  57. #include "llvm/Support/SaveAndRestore.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #define DEBUG_TYPE "exprconstant"
  60. using namespace clang;
  61. using llvm::APInt;
  62. using llvm::APSInt;
  63. using llvm::APFloat;
  64. using llvm::Optional;
  65. static bool IsGlobalLValue(APValue::LValueBase B);
  66. namespace {
  67. struct LValue;
  68. class CallStackFrame;
  69. class EvalInfo;
  70. using SourceLocExprScopeGuard =
  71. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  72. static QualType getType(APValue::LValueBase B) {
  73. if (!B) return QualType();
  74. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  75. // FIXME: It's unclear where we're supposed to take the type from, and
  76. // this actually matters for arrays of unknown bound. Eg:
  77. //
  78. // extern int arr[]; void f() { extern int arr[3]; };
  79. // constexpr int *p = &arr[1]; // valid?
  80. //
  81. // For now, we take the array bound from the most recent declaration.
  82. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  83. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  84. QualType T = Redecl->getType();
  85. if (!T->isIncompleteArrayType())
  86. return T;
  87. }
  88. return D->getType();
  89. }
  90. if (B.is<TypeInfoLValue>())
  91. return B.getTypeInfoType();
  92. const Expr *Base = B.get<const Expr*>();
  93. // For a materialized temporary, the type of the temporary we materialized
  94. // may not be the type of the expression.
  95. if (const MaterializeTemporaryExpr *MTE =
  96. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  97. SmallVector<const Expr *, 2> CommaLHSs;
  98. SmallVector<SubobjectAdjustment, 2> Adjustments;
  99. const Expr *Temp = MTE->GetTemporaryExpr();
  100. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  101. Adjustments);
  102. // Keep any cv-qualifiers from the reference if we generated a temporary
  103. // for it directly. Otherwise use the type after adjustment.
  104. if (!Adjustments.empty())
  105. return Inner->getType();
  106. }
  107. return Base->getType();
  108. }
  109. /// Get an LValue path entry, which is known to not be an array index, as a
  110. /// field declaration.
  111. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  112. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  113. }
  114. /// Get an LValue path entry, which is known to not be an array index, as a
  115. /// base class declaration.
  116. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  117. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  118. }
  119. /// Determine whether this LValue path entry for a base class names a virtual
  120. /// base class.
  121. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  122. return E.getAsBaseOrMember().getInt();
  123. }
  124. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  125. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  126. const FunctionDecl *Callee = CE->getDirectCallee();
  127. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  128. }
  129. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  130. /// This will look through a single cast.
  131. ///
  132. /// Returns null if we couldn't unwrap a function with alloc_size.
  133. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  134. if (!E->getType()->isPointerType())
  135. return nullptr;
  136. E = E->IgnoreParens();
  137. // If we're doing a variable assignment from e.g. malloc(N), there will
  138. // probably be a cast of some kind. In exotic cases, we might also see a
  139. // top-level ExprWithCleanups. Ignore them either way.
  140. if (const auto *FE = dyn_cast<FullExpr>(E))
  141. E = FE->getSubExpr()->IgnoreParens();
  142. if (const auto *Cast = dyn_cast<CastExpr>(E))
  143. E = Cast->getSubExpr()->IgnoreParens();
  144. if (const auto *CE = dyn_cast<CallExpr>(E))
  145. return getAllocSizeAttr(CE) ? CE : nullptr;
  146. return nullptr;
  147. }
  148. /// Determines whether or not the given Base contains a call to a function
  149. /// with the alloc_size attribute.
  150. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  151. const auto *E = Base.dyn_cast<const Expr *>();
  152. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  153. }
  154. /// The bound to claim that an array of unknown bound has.
  155. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  156. /// to an arbitrary value that's likely to loudly break things if it's used.
  157. static const uint64_t AssumedSizeForUnsizedArray =
  158. std::numeric_limits<uint64_t>::max() / 2;
  159. /// Determines if an LValue with the given LValueBase will have an unsized
  160. /// array in its designator.
  161. /// Find the path length and type of the most-derived subobject in the given
  162. /// path, and find the size of the containing array, if any.
  163. static unsigned
  164. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  165. ArrayRef<APValue::LValuePathEntry> Path,
  166. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  167. bool &FirstEntryIsUnsizedArray) {
  168. // This only accepts LValueBases from APValues, and APValues don't support
  169. // arrays that lack size info.
  170. assert(!isBaseAnAllocSizeCall(Base) &&
  171. "Unsized arrays shouldn't appear here");
  172. unsigned MostDerivedLength = 0;
  173. Type = getType(Base);
  174. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  175. if (Type->isArrayType()) {
  176. const ArrayType *AT = Ctx.getAsArrayType(Type);
  177. Type = AT->getElementType();
  178. MostDerivedLength = I + 1;
  179. IsArray = true;
  180. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  181. ArraySize = CAT->getSize().getZExtValue();
  182. } else {
  183. assert(I == 0 && "unexpected unsized array designator");
  184. FirstEntryIsUnsizedArray = true;
  185. ArraySize = AssumedSizeForUnsizedArray;
  186. }
  187. } else if (Type->isAnyComplexType()) {
  188. const ComplexType *CT = Type->castAs<ComplexType>();
  189. Type = CT->getElementType();
  190. ArraySize = 2;
  191. MostDerivedLength = I + 1;
  192. IsArray = true;
  193. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  194. Type = FD->getType();
  195. ArraySize = 0;
  196. MostDerivedLength = I + 1;
  197. IsArray = false;
  198. } else {
  199. // Path[I] describes a base class.
  200. ArraySize = 0;
  201. IsArray = false;
  202. }
  203. }
  204. return MostDerivedLength;
  205. }
  206. /// A path from a glvalue to a subobject of that glvalue.
  207. struct SubobjectDesignator {
  208. /// True if the subobject was named in a manner not supported by C++11. Such
  209. /// lvalues can still be folded, but they are not core constant expressions
  210. /// and we cannot perform lvalue-to-rvalue conversions on them.
  211. unsigned Invalid : 1;
  212. /// Is this a pointer one past the end of an object?
  213. unsigned IsOnePastTheEnd : 1;
  214. /// Indicator of whether the first entry is an unsized array.
  215. unsigned FirstEntryIsAnUnsizedArray : 1;
  216. /// Indicator of whether the most-derived object is an array element.
  217. unsigned MostDerivedIsArrayElement : 1;
  218. /// The length of the path to the most-derived object of which this is a
  219. /// subobject.
  220. unsigned MostDerivedPathLength : 28;
  221. /// The size of the array of which the most-derived object is an element.
  222. /// This will always be 0 if the most-derived object is not an array
  223. /// element. 0 is not an indicator of whether or not the most-derived object
  224. /// is an array, however, because 0-length arrays are allowed.
  225. ///
  226. /// If the current array is an unsized array, the value of this is
  227. /// undefined.
  228. uint64_t MostDerivedArraySize;
  229. /// The type of the most derived object referred to by this address.
  230. QualType MostDerivedType;
  231. typedef APValue::LValuePathEntry PathEntry;
  232. /// The entries on the path from the glvalue to the designated subobject.
  233. SmallVector<PathEntry, 8> Entries;
  234. SubobjectDesignator() : Invalid(true) {}
  235. explicit SubobjectDesignator(QualType T)
  236. : Invalid(false), IsOnePastTheEnd(false),
  237. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  238. MostDerivedPathLength(0), MostDerivedArraySize(0),
  239. MostDerivedType(T) {}
  240. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  241. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  242. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  243. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  244. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  245. if (!Invalid) {
  246. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  247. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  248. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  249. if (V.getLValueBase()) {
  250. bool IsArray = false;
  251. bool FirstIsUnsizedArray = false;
  252. MostDerivedPathLength = findMostDerivedSubobject(
  253. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  254. MostDerivedType, IsArray, FirstIsUnsizedArray);
  255. MostDerivedIsArrayElement = IsArray;
  256. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  257. }
  258. }
  259. }
  260. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  261. unsigned NewLength) {
  262. if (Invalid)
  263. return;
  264. assert(Base && "cannot truncate path for null pointer");
  265. assert(NewLength <= Entries.size() && "not a truncation");
  266. if (NewLength == Entries.size())
  267. return;
  268. Entries.resize(NewLength);
  269. bool IsArray = false;
  270. bool FirstIsUnsizedArray = false;
  271. MostDerivedPathLength = findMostDerivedSubobject(
  272. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  273. FirstIsUnsizedArray);
  274. MostDerivedIsArrayElement = IsArray;
  275. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  276. }
  277. void setInvalid() {
  278. Invalid = true;
  279. Entries.clear();
  280. }
  281. /// Determine whether the most derived subobject is an array without a
  282. /// known bound.
  283. bool isMostDerivedAnUnsizedArray() const {
  284. assert(!Invalid && "Calling this makes no sense on invalid designators");
  285. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  286. }
  287. /// Determine what the most derived array's size is. Results in an assertion
  288. /// failure if the most derived array lacks a size.
  289. uint64_t getMostDerivedArraySize() const {
  290. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  291. return MostDerivedArraySize;
  292. }
  293. /// Determine whether this is a one-past-the-end pointer.
  294. bool isOnePastTheEnd() const {
  295. assert(!Invalid);
  296. if (IsOnePastTheEnd)
  297. return true;
  298. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  299. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  300. MostDerivedArraySize)
  301. return true;
  302. return false;
  303. }
  304. /// Get the range of valid index adjustments in the form
  305. /// {maximum value that can be subtracted from this pointer,
  306. /// maximum value that can be added to this pointer}
  307. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  308. if (Invalid || isMostDerivedAnUnsizedArray())
  309. return {0, 0};
  310. // [expr.add]p4: For the purposes of these operators, a pointer to a
  311. // nonarray object behaves the same as a pointer to the first element of
  312. // an array of length one with the type of the object as its element type.
  313. bool IsArray = MostDerivedPathLength == Entries.size() &&
  314. MostDerivedIsArrayElement;
  315. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  316. : (uint64_t)IsOnePastTheEnd;
  317. uint64_t ArraySize =
  318. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  319. return {ArrayIndex, ArraySize - ArrayIndex};
  320. }
  321. /// Check that this refers to a valid subobject.
  322. bool isValidSubobject() const {
  323. if (Invalid)
  324. return false;
  325. return !isOnePastTheEnd();
  326. }
  327. /// Check that this refers to a valid subobject, and if not, produce a
  328. /// relevant diagnostic and set the designator as invalid.
  329. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  330. /// Get the type of the designated object.
  331. QualType getType(ASTContext &Ctx) const {
  332. assert(!Invalid && "invalid designator has no subobject type");
  333. return MostDerivedPathLength == Entries.size()
  334. ? MostDerivedType
  335. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  336. }
  337. /// Update this designator to refer to the first element within this array.
  338. void addArrayUnchecked(const ConstantArrayType *CAT) {
  339. Entries.push_back(PathEntry::ArrayIndex(0));
  340. // This is a most-derived object.
  341. MostDerivedType = CAT->getElementType();
  342. MostDerivedIsArrayElement = true;
  343. MostDerivedArraySize = CAT->getSize().getZExtValue();
  344. MostDerivedPathLength = Entries.size();
  345. }
  346. /// Update this designator to refer to the first element within the array of
  347. /// elements of type T. This is an array of unknown size.
  348. void addUnsizedArrayUnchecked(QualType ElemTy) {
  349. Entries.push_back(PathEntry::ArrayIndex(0));
  350. MostDerivedType = ElemTy;
  351. MostDerivedIsArrayElement = true;
  352. // The value in MostDerivedArraySize is undefined in this case. So, set it
  353. // to an arbitrary value that's likely to loudly break things if it's
  354. // used.
  355. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  356. MostDerivedPathLength = Entries.size();
  357. }
  358. /// Update this designator to refer to the given base or member of this
  359. /// object.
  360. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  361. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  362. // If this isn't a base class, it's a new most-derived object.
  363. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  364. MostDerivedType = FD->getType();
  365. MostDerivedIsArrayElement = false;
  366. MostDerivedArraySize = 0;
  367. MostDerivedPathLength = Entries.size();
  368. }
  369. }
  370. /// Update this designator to refer to the given complex component.
  371. void addComplexUnchecked(QualType EltTy, bool Imag) {
  372. Entries.push_back(PathEntry::ArrayIndex(Imag));
  373. // This is technically a most-derived object, though in practice this
  374. // is unlikely to matter.
  375. MostDerivedType = EltTy;
  376. MostDerivedIsArrayElement = true;
  377. MostDerivedArraySize = 2;
  378. MostDerivedPathLength = Entries.size();
  379. }
  380. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  381. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  382. const APSInt &N);
  383. /// Add N to the address of this subobject.
  384. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  385. if (Invalid || !N) return;
  386. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  387. if (isMostDerivedAnUnsizedArray()) {
  388. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  389. // Can't verify -- trust that the user is doing the right thing (or if
  390. // not, trust that the caller will catch the bad behavior).
  391. // FIXME: Should we reject if this overflows, at least?
  392. Entries.back() = PathEntry::ArrayIndex(
  393. Entries.back().getAsArrayIndex() + TruncatedN);
  394. return;
  395. }
  396. // [expr.add]p4: For the purposes of these operators, a pointer to a
  397. // nonarray object behaves the same as a pointer to the first element of
  398. // an array of length one with the type of the object as its element type.
  399. bool IsArray = MostDerivedPathLength == Entries.size() &&
  400. MostDerivedIsArrayElement;
  401. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  402. : (uint64_t)IsOnePastTheEnd;
  403. uint64_t ArraySize =
  404. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  405. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  406. // Calculate the actual index in a wide enough type, so we can include
  407. // it in the note.
  408. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  409. (llvm::APInt&)N += ArrayIndex;
  410. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  411. diagnosePointerArithmetic(Info, E, N);
  412. setInvalid();
  413. return;
  414. }
  415. ArrayIndex += TruncatedN;
  416. assert(ArrayIndex <= ArraySize &&
  417. "bounds check succeeded for out-of-bounds index");
  418. if (IsArray)
  419. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  420. else
  421. IsOnePastTheEnd = (ArrayIndex != 0);
  422. }
  423. };
  424. /// A stack frame in the constexpr call stack.
  425. class CallStackFrame : public interp::Frame {
  426. public:
  427. EvalInfo &Info;
  428. /// Parent - The caller of this stack frame.
  429. CallStackFrame *Caller;
  430. /// Callee - The function which was called.
  431. const FunctionDecl *Callee;
  432. /// This - The binding for the this pointer in this call, if any.
  433. const LValue *This;
  434. /// Arguments - Parameter bindings for this function call, indexed by
  435. /// parameters' function scope indices.
  436. APValue *Arguments;
  437. /// Source location information about the default argument or default
  438. /// initializer expression we're evaluating, if any.
  439. CurrentSourceLocExprScope CurSourceLocExprScope;
  440. // Note that we intentionally use std::map here so that references to
  441. // values are stable.
  442. typedef std::pair<const void *, unsigned> MapKeyTy;
  443. typedef std::map<MapKeyTy, APValue> MapTy;
  444. /// Temporaries - Temporary lvalues materialized within this stack frame.
  445. MapTy Temporaries;
  446. /// CallLoc - The location of the call expression for this call.
  447. SourceLocation CallLoc;
  448. /// Index - The call index of this call.
  449. unsigned Index;
  450. /// The stack of integers for tracking version numbers for temporaries.
  451. SmallVector<unsigned, 2> TempVersionStack = {1};
  452. unsigned CurTempVersion = TempVersionStack.back();
  453. unsigned getTempVersion() const { return TempVersionStack.back(); }
  454. void pushTempVersion() {
  455. TempVersionStack.push_back(++CurTempVersion);
  456. }
  457. void popTempVersion() {
  458. TempVersionStack.pop_back();
  459. }
  460. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  461. // on the overall stack usage of deeply-recursing constexpr evaluations.
  462. // (We should cache this map rather than recomputing it repeatedly.)
  463. // But let's try this and see how it goes; we can look into caching the map
  464. // as a later change.
  465. /// LambdaCaptureFields - Mapping from captured variables/this to
  466. /// corresponding data members in the closure class.
  467. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  468. FieldDecl *LambdaThisCaptureField;
  469. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  470. const FunctionDecl *Callee, const LValue *This,
  471. APValue *Arguments);
  472. ~CallStackFrame();
  473. // Return the temporary for Key whose version number is Version.
  474. APValue *getTemporary(const void *Key, unsigned Version) {
  475. MapKeyTy KV(Key, Version);
  476. auto LB = Temporaries.lower_bound(KV);
  477. if (LB != Temporaries.end() && LB->first == KV)
  478. return &LB->second;
  479. // Pair (Key,Version) wasn't found in the map. Check that no elements
  480. // in the map have 'Key' as their key.
  481. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  482. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  483. "Element with key 'Key' found in map");
  484. return nullptr;
  485. }
  486. // Return the current temporary for Key in the map.
  487. APValue *getCurrentTemporary(const void *Key) {
  488. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  489. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  490. return &std::prev(UB)->second;
  491. return nullptr;
  492. }
  493. // Return the version number of the current temporary for Key.
  494. unsigned getCurrentTemporaryVersion(const void *Key) const {
  495. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  496. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  497. return std::prev(UB)->first.second;
  498. return 0;
  499. }
  500. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  501. void describe(llvm::raw_ostream &OS) override;
  502. Frame *getCaller() const override { return Caller; }
  503. SourceLocation getCallLocation() const override { return CallLoc; }
  504. const FunctionDecl *getCallee() const override { return Callee; }
  505. };
  506. /// Temporarily override 'this'.
  507. class ThisOverrideRAII {
  508. public:
  509. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  510. : Frame(Frame), OldThis(Frame.This) {
  511. if (Enable)
  512. Frame.This = NewThis;
  513. }
  514. ~ThisOverrideRAII() {
  515. Frame.This = OldThis;
  516. }
  517. private:
  518. CallStackFrame &Frame;
  519. const LValue *OldThis;
  520. };
  521. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  522. class Cleanup {
  523. llvm::PointerIntPair<APValue*, 1, bool> Value;
  524. public:
  525. Cleanup(APValue *Val, bool IsLifetimeExtended)
  526. : Value(Val, IsLifetimeExtended) {}
  527. bool isLifetimeExtended() const { return Value.getInt(); }
  528. void endLifetime() {
  529. *Value.getPointer() = APValue();
  530. }
  531. };
  532. /// A reference to an object whose construction we are currently evaluating.
  533. struct ObjectUnderConstruction {
  534. APValue::LValueBase Base;
  535. ArrayRef<APValue::LValuePathEntry> Path;
  536. friend bool operator==(const ObjectUnderConstruction &LHS,
  537. const ObjectUnderConstruction &RHS) {
  538. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  539. }
  540. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  541. return llvm::hash_combine(Obj.Base, Obj.Path);
  542. }
  543. };
  544. enum class ConstructionPhase { None, Bases, AfterBases };
  545. }
  546. namespace llvm {
  547. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  548. using Base = DenseMapInfo<APValue::LValueBase>;
  549. static ObjectUnderConstruction getEmptyKey() {
  550. return {Base::getEmptyKey(), {}}; }
  551. static ObjectUnderConstruction getTombstoneKey() {
  552. return {Base::getTombstoneKey(), {}};
  553. }
  554. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  555. return hash_value(Object);
  556. }
  557. static bool isEqual(const ObjectUnderConstruction &LHS,
  558. const ObjectUnderConstruction &RHS) {
  559. return LHS == RHS;
  560. }
  561. };
  562. }
  563. namespace {
  564. /// EvalInfo - This is a private struct used by the evaluator to capture
  565. /// information about a subexpression as it is folded. It retains information
  566. /// about the AST context, but also maintains information about the folded
  567. /// expression.
  568. ///
  569. /// If an expression could be evaluated, it is still possible it is not a C
  570. /// "integer constant expression" or constant expression. If not, this struct
  571. /// captures information about how and why not.
  572. ///
  573. /// One bit of information passed *into* the request for constant folding
  574. /// indicates whether the subexpression is "evaluated" or not according to C
  575. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  576. /// evaluate the expression regardless of what the RHS is, but C only allows
  577. /// certain things in certain situations.
  578. class EvalInfo : public interp::State {
  579. public:
  580. ASTContext &Ctx;
  581. /// EvalStatus - Contains information about the evaluation.
  582. Expr::EvalStatus &EvalStatus;
  583. /// CurrentCall - The top of the constexpr call stack.
  584. CallStackFrame *CurrentCall;
  585. /// CallStackDepth - The number of calls in the call stack right now.
  586. unsigned CallStackDepth;
  587. /// NextCallIndex - The next call index to assign.
  588. unsigned NextCallIndex;
  589. /// StepsLeft - The remaining number of evaluation steps we're permitted
  590. /// to perform. This is essentially a limit for the number of statements
  591. /// we will evaluate.
  592. unsigned StepsLeft;
  593. /// Force the use of the experimental new constant interpreter, bailing out
  594. /// with an error if a feature is not supported.
  595. bool ForceNewConstInterp;
  596. /// Enable the experimental new constant interpreter.
  597. bool EnableNewConstInterp;
  598. /// BottomFrame - The frame in which evaluation started. This must be
  599. /// initialized after CurrentCall and CallStackDepth.
  600. CallStackFrame BottomFrame;
  601. /// A stack of values whose lifetimes end at the end of some surrounding
  602. /// evaluation frame.
  603. llvm::SmallVector<Cleanup, 16> CleanupStack;
  604. /// EvaluatingDecl - This is the declaration whose initializer is being
  605. /// evaluated, if any.
  606. APValue::LValueBase EvaluatingDecl;
  607. /// EvaluatingDeclValue - This is the value being constructed for the
  608. /// declaration whose initializer is being evaluated, if any.
  609. APValue *EvaluatingDeclValue;
  610. /// Set of objects that are currently being constructed.
  611. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  612. ObjectsUnderConstruction;
  613. struct EvaluatingConstructorRAII {
  614. EvalInfo &EI;
  615. ObjectUnderConstruction Object;
  616. bool DidInsert;
  617. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  618. bool HasBases)
  619. : EI(EI), Object(Object) {
  620. DidInsert =
  621. EI.ObjectsUnderConstruction
  622. .insert({Object, HasBases ? ConstructionPhase::Bases
  623. : ConstructionPhase::AfterBases})
  624. .second;
  625. }
  626. void finishedConstructingBases() {
  627. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  628. }
  629. ~EvaluatingConstructorRAII() {
  630. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  631. }
  632. };
  633. ConstructionPhase
  634. isEvaluatingConstructor(APValue::LValueBase Base,
  635. ArrayRef<APValue::LValuePathEntry> Path) {
  636. return ObjectsUnderConstruction.lookup({Base, Path});
  637. }
  638. /// If we're currently speculatively evaluating, the outermost call stack
  639. /// depth at which we can mutate state, otherwise 0.
  640. unsigned SpeculativeEvaluationDepth = 0;
  641. /// The current array initialization index, if we're performing array
  642. /// initialization.
  643. uint64_t ArrayInitIndex = -1;
  644. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  645. /// notes attached to it will also be stored, otherwise they will not be.
  646. bool HasActiveDiagnostic;
  647. /// Have we emitted a diagnostic explaining why we couldn't constant
  648. /// fold (not just why it's not strictly a constant expression)?
  649. bool HasFoldFailureDiagnostic;
  650. /// Whether or not we're in a context where the front end requires a
  651. /// constant value.
  652. bool InConstantContext;
  653. enum EvaluationMode {
  654. /// Evaluate as a constant expression. Stop if we find that the expression
  655. /// is not a constant expression.
  656. EM_ConstantExpression,
  657. /// Evaluate as a potential constant expression. Keep going if we hit a
  658. /// construct that we can't evaluate yet (because we don't yet know the
  659. /// value of something) but stop if we hit something that could never be
  660. /// a constant expression.
  661. EM_PotentialConstantExpression,
  662. /// Fold the expression to a constant. Stop if we hit a side-effect that
  663. /// we can't model.
  664. EM_ConstantFold,
  665. /// Evaluate the expression looking for integer overflow and similar
  666. /// issues. Don't worry about side-effects, and try to visit all
  667. /// subexpressions.
  668. EM_EvaluateForOverflow,
  669. /// Evaluate in any way we know how. Don't worry about side-effects that
  670. /// can't be modeled.
  671. EM_IgnoreSideEffects,
  672. /// Evaluate as a constant expression. Stop if we find that the expression
  673. /// is not a constant expression. Some expressions can be retried in the
  674. /// optimizer if we don't constant fold them here, but in an unevaluated
  675. /// context we try to fold them immediately since the optimizer never
  676. /// gets a chance to look at it.
  677. EM_ConstantExpressionUnevaluated,
  678. /// Evaluate as a potential constant expression. Keep going if we hit a
  679. /// construct that we can't evaluate yet (because we don't yet know the
  680. /// value of something) but stop if we hit something that could never be
  681. /// a constant expression. Some expressions can be retried in the
  682. /// optimizer if we don't constant fold them here, but in an unevaluated
  683. /// context we try to fold them immediately since the optimizer never
  684. /// gets a chance to look at it.
  685. EM_PotentialConstantExpressionUnevaluated,
  686. } EvalMode;
  687. /// Are we checking whether the expression is a potential constant
  688. /// expression?
  689. bool checkingPotentialConstantExpression() const override {
  690. return EvalMode == EM_PotentialConstantExpression ||
  691. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  692. }
  693. /// Are we checking an expression for overflow?
  694. // FIXME: We should check for any kind of undefined or suspicious behavior
  695. // in such constructs, not just overflow.
  696. bool checkingForOverflow() const override {
  697. return EvalMode == EM_EvaluateForOverflow;
  698. }
  699. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  700. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  701. CallStackDepth(0), NextCallIndex(1),
  702. StepsLeft(getLangOpts().ConstexprStepLimit),
  703. ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
  704. EnableNewConstInterp(ForceNewConstInterp ||
  705. getLangOpts().EnableNewConstInterp),
  706. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  707. EvaluatingDecl((const ValueDecl *)nullptr),
  708. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  709. HasFoldFailureDiagnostic(false), InConstantContext(false),
  710. EvalMode(Mode) {}
  711. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  712. EvaluatingDecl = Base;
  713. EvaluatingDeclValue = &Value;
  714. }
  715. bool CheckCallLimit(SourceLocation Loc) {
  716. // Don't perform any constexpr calls (other than the call we're checking)
  717. // when checking a potential constant expression.
  718. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  719. return false;
  720. if (NextCallIndex == 0) {
  721. // NextCallIndex has wrapped around.
  722. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  723. return false;
  724. }
  725. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  726. return true;
  727. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  728. << getLangOpts().ConstexprCallDepth;
  729. return false;
  730. }
  731. std::pair<CallStackFrame *, unsigned>
  732. getCallFrameAndDepth(unsigned CallIndex) {
  733. assert(CallIndex && "no call index in getCallFrameAndDepth");
  734. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  735. // be null in this loop.
  736. unsigned Depth = CallStackDepth;
  737. CallStackFrame *Frame = CurrentCall;
  738. while (Frame->Index > CallIndex) {
  739. Frame = Frame->Caller;
  740. --Depth;
  741. }
  742. if (Frame->Index == CallIndex)
  743. return {Frame, Depth};
  744. return {nullptr, 0};
  745. }
  746. bool nextStep(const Stmt *S) {
  747. if (!StepsLeft) {
  748. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  749. return false;
  750. }
  751. --StepsLeft;
  752. return true;
  753. }
  754. private:
  755. interp::Frame *getCurrentFrame() override { return CurrentCall; }
  756. const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
  757. bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
  758. void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
  759. void setFoldFailureDiagnostic(bool Flag) override {
  760. HasFoldFailureDiagnostic = Flag;
  761. }
  762. Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
  763. ASTContext &getCtx() const override { return Ctx; }
  764. // If we have a prior diagnostic, it will be noting that the expression
  765. // isn't a constant expression. This diagnostic is more important,
  766. // unless we require this evaluation to produce a constant expression.
  767. //
  768. // FIXME: We might want to show both diagnostics to the user in
  769. // EM_ConstantFold mode.
  770. bool hasPriorDiagnostic() override {
  771. if (!EvalStatus.Diag->empty()) {
  772. switch (EvalMode) {
  773. case EM_ConstantFold:
  774. case EM_IgnoreSideEffects:
  775. case EM_EvaluateForOverflow:
  776. if (!HasFoldFailureDiagnostic)
  777. break;
  778. // We've already failed to fold something. Keep that diagnostic.
  779. LLVM_FALLTHROUGH;
  780. case EM_ConstantExpression:
  781. case EM_PotentialConstantExpression:
  782. case EM_ConstantExpressionUnevaluated:
  783. case EM_PotentialConstantExpressionUnevaluated:
  784. setActiveDiagnostic(false);
  785. return true;
  786. }
  787. }
  788. return false;
  789. }
  790. unsigned getCallStackDepth() override {
  791. return CallStackDepth;
  792. }
  793. public:
  794. /// Should we continue evaluation after encountering a side-effect that we
  795. /// couldn't model?
  796. bool keepEvaluatingAfterSideEffect() {
  797. switch (EvalMode) {
  798. case EM_PotentialConstantExpression:
  799. case EM_PotentialConstantExpressionUnevaluated:
  800. case EM_EvaluateForOverflow:
  801. case EM_IgnoreSideEffects:
  802. return true;
  803. case EM_ConstantExpression:
  804. case EM_ConstantExpressionUnevaluated:
  805. case EM_ConstantFold:
  806. return false;
  807. }
  808. llvm_unreachable("Missed EvalMode case");
  809. }
  810. /// Note that we have had a side-effect, and determine whether we should
  811. /// keep evaluating.
  812. bool noteSideEffect() {
  813. EvalStatus.HasSideEffects = true;
  814. return keepEvaluatingAfterSideEffect();
  815. }
  816. /// Should we continue evaluation after encountering undefined behavior?
  817. bool keepEvaluatingAfterUndefinedBehavior() {
  818. switch (EvalMode) {
  819. case EM_EvaluateForOverflow:
  820. case EM_IgnoreSideEffects:
  821. case EM_ConstantFold:
  822. return true;
  823. case EM_PotentialConstantExpression:
  824. case EM_PotentialConstantExpressionUnevaluated:
  825. case EM_ConstantExpression:
  826. case EM_ConstantExpressionUnevaluated:
  827. return false;
  828. }
  829. llvm_unreachable("Missed EvalMode case");
  830. }
  831. /// Note that we hit something that was technically undefined behavior, but
  832. /// that we can evaluate past it (such as signed overflow or floating-point
  833. /// division by zero.)
  834. bool noteUndefinedBehavior() override {
  835. EvalStatus.HasUndefinedBehavior = true;
  836. return keepEvaluatingAfterUndefinedBehavior();
  837. }
  838. /// Should we continue evaluation as much as possible after encountering a
  839. /// construct which can't be reduced to a value?
  840. bool keepEvaluatingAfterFailure() const override {
  841. if (!StepsLeft)
  842. return false;
  843. switch (EvalMode) {
  844. case EM_PotentialConstantExpression:
  845. case EM_PotentialConstantExpressionUnevaluated:
  846. case EM_EvaluateForOverflow:
  847. return true;
  848. case EM_ConstantExpression:
  849. case EM_ConstantExpressionUnevaluated:
  850. case EM_ConstantFold:
  851. case EM_IgnoreSideEffects:
  852. return false;
  853. }
  854. llvm_unreachable("Missed EvalMode case");
  855. }
  856. /// Notes that we failed to evaluate an expression that other expressions
  857. /// directly depend on, and determine if we should keep evaluating. This
  858. /// should only be called if we actually intend to keep evaluating.
  859. ///
  860. /// Call noteSideEffect() instead if we may be able to ignore the value that
  861. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  862. ///
  863. /// (Foo(), 1) // use noteSideEffect
  864. /// (Foo() || true) // use noteSideEffect
  865. /// Foo() + 1 // use noteFailure
  866. LLVM_NODISCARD bool noteFailure() {
  867. // Failure when evaluating some expression often means there is some
  868. // subexpression whose evaluation was skipped. Therefore, (because we
  869. // don't track whether we skipped an expression when unwinding after an
  870. // evaluation failure) every evaluation failure that bubbles up from a
  871. // subexpression implies that a side-effect has potentially happened. We
  872. // skip setting the HasSideEffects flag to true until we decide to
  873. // continue evaluating after that point, which happens here.
  874. bool KeepGoing = keepEvaluatingAfterFailure();
  875. EvalStatus.HasSideEffects |= KeepGoing;
  876. return KeepGoing;
  877. }
  878. class ArrayInitLoopIndex {
  879. EvalInfo &Info;
  880. uint64_t OuterIndex;
  881. public:
  882. ArrayInitLoopIndex(EvalInfo &Info)
  883. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  884. Info.ArrayInitIndex = 0;
  885. }
  886. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  887. operator uint64_t&() { return Info.ArrayInitIndex; }
  888. };
  889. };
  890. /// Object used to treat all foldable expressions as constant expressions.
  891. struct FoldConstant {
  892. EvalInfo &Info;
  893. bool Enabled;
  894. bool HadNoPriorDiags;
  895. EvalInfo::EvaluationMode OldMode;
  896. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  897. : Info(Info),
  898. Enabled(Enabled),
  899. HadNoPriorDiags(Info.EvalStatus.Diag &&
  900. Info.EvalStatus.Diag->empty() &&
  901. !Info.EvalStatus.HasSideEffects),
  902. OldMode(Info.EvalMode) {
  903. if (Enabled &&
  904. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  905. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  906. Info.EvalMode = EvalInfo::EM_ConstantFold;
  907. }
  908. void keepDiagnostics() { Enabled = false; }
  909. ~FoldConstant() {
  910. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  911. !Info.EvalStatus.HasSideEffects)
  912. Info.EvalStatus.Diag->clear();
  913. Info.EvalMode = OldMode;
  914. }
  915. };
  916. /// RAII object used to set the current evaluation mode to ignore
  917. /// side-effects.
  918. struct IgnoreSideEffectsRAII {
  919. EvalInfo &Info;
  920. EvalInfo::EvaluationMode OldMode;
  921. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  922. : Info(Info), OldMode(Info.EvalMode) {
  923. if (!Info.checkingPotentialConstantExpression())
  924. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  925. }
  926. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  927. };
  928. /// RAII object used to optionally suppress diagnostics and side-effects from
  929. /// a speculative evaluation.
  930. class SpeculativeEvaluationRAII {
  931. EvalInfo *Info = nullptr;
  932. Expr::EvalStatus OldStatus;
  933. unsigned OldSpeculativeEvaluationDepth;
  934. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  935. Info = Other.Info;
  936. OldStatus = Other.OldStatus;
  937. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  938. Other.Info = nullptr;
  939. }
  940. void maybeRestoreState() {
  941. if (!Info)
  942. return;
  943. Info->EvalStatus = OldStatus;
  944. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  945. }
  946. public:
  947. SpeculativeEvaluationRAII() = default;
  948. SpeculativeEvaluationRAII(
  949. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  950. : Info(&Info), OldStatus(Info.EvalStatus),
  951. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  952. Info.EvalStatus.Diag = NewDiag;
  953. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  954. }
  955. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  956. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  957. moveFromAndCancel(std::move(Other));
  958. }
  959. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  960. maybeRestoreState();
  961. moveFromAndCancel(std::move(Other));
  962. return *this;
  963. }
  964. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  965. };
  966. /// RAII object wrapping a full-expression or block scope, and handling
  967. /// the ending of the lifetime of temporaries created within it.
  968. template<bool IsFullExpression>
  969. class ScopeRAII {
  970. EvalInfo &Info;
  971. unsigned OldStackSize;
  972. public:
  973. ScopeRAII(EvalInfo &Info)
  974. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  975. // Push a new temporary version. This is needed to distinguish between
  976. // temporaries created in different iterations of a loop.
  977. Info.CurrentCall->pushTempVersion();
  978. }
  979. ~ScopeRAII() {
  980. // Body moved to a static method to encourage the compiler to inline away
  981. // instances of this class.
  982. cleanup(Info, OldStackSize);
  983. Info.CurrentCall->popTempVersion();
  984. }
  985. private:
  986. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  987. unsigned NewEnd = OldStackSize;
  988. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  989. I != N; ++I) {
  990. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  991. // Full-expression cleanup of a lifetime-extended temporary: nothing
  992. // to do, just move this cleanup to the right place in the stack.
  993. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  994. ++NewEnd;
  995. } else {
  996. // End the lifetime of the object.
  997. Info.CleanupStack[I].endLifetime();
  998. }
  999. }
  1000. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1001. Info.CleanupStack.end());
  1002. }
  1003. };
  1004. typedef ScopeRAII<false> BlockScopeRAII;
  1005. typedef ScopeRAII<true> FullExpressionRAII;
  1006. }
  1007. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1008. CheckSubobjectKind CSK) {
  1009. if (Invalid)
  1010. return false;
  1011. if (isOnePastTheEnd()) {
  1012. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1013. << CSK;
  1014. setInvalid();
  1015. return false;
  1016. }
  1017. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1018. // must actually be at least one array element; even a VLA cannot have a
  1019. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1020. return true;
  1021. }
  1022. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1023. const Expr *E) {
  1024. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1025. // Do not set the designator as invalid: we can represent this situation,
  1026. // and correct handling of __builtin_object_size requires us to do so.
  1027. }
  1028. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1029. const Expr *E,
  1030. const APSInt &N) {
  1031. // If we're complaining, we must be able to statically determine the size of
  1032. // the most derived array.
  1033. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1034. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1035. << N << /*array*/ 0
  1036. << static_cast<unsigned>(getMostDerivedArraySize());
  1037. else
  1038. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1039. << N << /*non-array*/ 1;
  1040. setInvalid();
  1041. }
  1042. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1043. const FunctionDecl *Callee, const LValue *This,
  1044. APValue *Arguments)
  1045. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1046. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1047. Info.CurrentCall = this;
  1048. ++Info.CallStackDepth;
  1049. }
  1050. CallStackFrame::~CallStackFrame() {
  1051. assert(Info.CurrentCall == this && "calls retired out of order");
  1052. --Info.CallStackDepth;
  1053. Info.CurrentCall = Caller;
  1054. }
  1055. APValue &CallStackFrame::createTemporary(const void *Key,
  1056. bool IsLifetimeExtended) {
  1057. unsigned Version = Info.CurrentCall->getTempVersion();
  1058. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1059. assert(Result.isAbsent() && "temporary created multiple times");
  1060. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1061. return Result;
  1062. }
  1063. static bool isModification(AccessKinds AK) {
  1064. switch (AK) {
  1065. case AK_Read:
  1066. case AK_MemberCall:
  1067. case AK_DynamicCast:
  1068. case AK_TypeId:
  1069. return false;
  1070. case AK_Assign:
  1071. case AK_Increment:
  1072. case AK_Decrement:
  1073. return true;
  1074. }
  1075. llvm_unreachable("unknown access kind");
  1076. }
  1077. /// Is this an access per the C++ definition?
  1078. static bool isFormalAccess(AccessKinds AK) {
  1079. return AK == AK_Read || isModification(AK);
  1080. }
  1081. namespace {
  1082. struct ComplexValue {
  1083. private:
  1084. bool IsInt;
  1085. public:
  1086. APSInt IntReal, IntImag;
  1087. APFloat FloatReal, FloatImag;
  1088. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1089. void makeComplexFloat() { IsInt = false; }
  1090. bool isComplexFloat() const { return !IsInt; }
  1091. APFloat &getComplexFloatReal() { return FloatReal; }
  1092. APFloat &getComplexFloatImag() { return FloatImag; }
  1093. void makeComplexInt() { IsInt = true; }
  1094. bool isComplexInt() const { return IsInt; }
  1095. APSInt &getComplexIntReal() { return IntReal; }
  1096. APSInt &getComplexIntImag() { return IntImag; }
  1097. void moveInto(APValue &v) const {
  1098. if (isComplexFloat())
  1099. v = APValue(FloatReal, FloatImag);
  1100. else
  1101. v = APValue(IntReal, IntImag);
  1102. }
  1103. void setFrom(const APValue &v) {
  1104. assert(v.isComplexFloat() || v.isComplexInt());
  1105. if (v.isComplexFloat()) {
  1106. makeComplexFloat();
  1107. FloatReal = v.getComplexFloatReal();
  1108. FloatImag = v.getComplexFloatImag();
  1109. } else {
  1110. makeComplexInt();
  1111. IntReal = v.getComplexIntReal();
  1112. IntImag = v.getComplexIntImag();
  1113. }
  1114. }
  1115. };
  1116. struct LValue {
  1117. APValue::LValueBase Base;
  1118. CharUnits Offset;
  1119. SubobjectDesignator Designator;
  1120. bool IsNullPtr : 1;
  1121. bool InvalidBase : 1;
  1122. const APValue::LValueBase getLValueBase() const { return Base; }
  1123. CharUnits &getLValueOffset() { return Offset; }
  1124. const CharUnits &getLValueOffset() const { return Offset; }
  1125. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1126. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1127. bool isNullPointer() const { return IsNullPtr;}
  1128. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1129. unsigned getLValueVersion() const { return Base.getVersion(); }
  1130. void moveInto(APValue &V) const {
  1131. if (Designator.Invalid)
  1132. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1133. else {
  1134. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1135. V = APValue(Base, Offset, Designator.Entries,
  1136. Designator.IsOnePastTheEnd, IsNullPtr);
  1137. }
  1138. }
  1139. void setFrom(ASTContext &Ctx, const APValue &V) {
  1140. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1141. Base = V.getLValueBase();
  1142. Offset = V.getLValueOffset();
  1143. InvalidBase = false;
  1144. Designator = SubobjectDesignator(Ctx, V);
  1145. IsNullPtr = V.isNullPointer();
  1146. }
  1147. void set(APValue::LValueBase B, bool BInvalid = false) {
  1148. #ifndef NDEBUG
  1149. // We only allow a few types of invalid bases. Enforce that here.
  1150. if (BInvalid) {
  1151. const auto *E = B.get<const Expr *>();
  1152. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1153. "Unexpected type of invalid base");
  1154. }
  1155. #endif
  1156. Base = B;
  1157. Offset = CharUnits::fromQuantity(0);
  1158. InvalidBase = BInvalid;
  1159. Designator = SubobjectDesignator(getType(B));
  1160. IsNullPtr = false;
  1161. }
  1162. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1163. Base = (Expr *)nullptr;
  1164. Offset = CharUnits::fromQuantity(TargetVal);
  1165. InvalidBase = false;
  1166. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1167. IsNullPtr = true;
  1168. }
  1169. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1170. set(B, true);
  1171. }
  1172. private:
  1173. // Check that this LValue is not based on a null pointer. If it is, produce
  1174. // a diagnostic and mark the designator as invalid.
  1175. template <typename GenDiagType>
  1176. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1177. if (Designator.Invalid)
  1178. return false;
  1179. if (IsNullPtr) {
  1180. GenDiag();
  1181. Designator.setInvalid();
  1182. return false;
  1183. }
  1184. return true;
  1185. }
  1186. public:
  1187. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1188. CheckSubobjectKind CSK) {
  1189. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1190. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1191. });
  1192. }
  1193. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1194. AccessKinds AK) {
  1195. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1196. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1197. });
  1198. }
  1199. // Check this LValue refers to an object. If not, set the designator to be
  1200. // invalid and emit a diagnostic.
  1201. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1202. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1203. Designator.checkSubobject(Info, E, CSK);
  1204. }
  1205. void addDecl(EvalInfo &Info, const Expr *E,
  1206. const Decl *D, bool Virtual = false) {
  1207. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1208. Designator.addDeclUnchecked(D, Virtual);
  1209. }
  1210. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1211. if (!Designator.Entries.empty()) {
  1212. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1213. Designator.setInvalid();
  1214. return;
  1215. }
  1216. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1217. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1218. Designator.FirstEntryIsAnUnsizedArray = true;
  1219. Designator.addUnsizedArrayUnchecked(ElemTy);
  1220. }
  1221. }
  1222. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1223. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1224. Designator.addArrayUnchecked(CAT);
  1225. }
  1226. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1227. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1228. Designator.addComplexUnchecked(EltTy, Imag);
  1229. }
  1230. void clearIsNullPointer() {
  1231. IsNullPtr = false;
  1232. }
  1233. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1234. const APSInt &Index, CharUnits ElementSize) {
  1235. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1236. // but we're not required to diagnose it and it's valid in C++.)
  1237. if (!Index)
  1238. return;
  1239. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1240. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1241. // offsets.
  1242. uint64_t Offset64 = Offset.getQuantity();
  1243. uint64_t ElemSize64 = ElementSize.getQuantity();
  1244. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1245. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1246. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1247. Designator.adjustIndex(Info, E, Index);
  1248. clearIsNullPointer();
  1249. }
  1250. void adjustOffset(CharUnits N) {
  1251. Offset += N;
  1252. if (N.getQuantity())
  1253. clearIsNullPointer();
  1254. }
  1255. };
  1256. struct MemberPtr {
  1257. MemberPtr() {}
  1258. explicit MemberPtr(const ValueDecl *Decl) :
  1259. DeclAndIsDerivedMember(Decl, false), Path() {}
  1260. /// The member or (direct or indirect) field referred to by this member
  1261. /// pointer, or 0 if this is a null member pointer.
  1262. const ValueDecl *getDecl() const {
  1263. return DeclAndIsDerivedMember.getPointer();
  1264. }
  1265. /// Is this actually a member of some type derived from the relevant class?
  1266. bool isDerivedMember() const {
  1267. return DeclAndIsDerivedMember.getInt();
  1268. }
  1269. /// Get the class which the declaration actually lives in.
  1270. const CXXRecordDecl *getContainingRecord() const {
  1271. return cast<CXXRecordDecl>(
  1272. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1273. }
  1274. void moveInto(APValue &V) const {
  1275. V = APValue(getDecl(), isDerivedMember(), Path);
  1276. }
  1277. void setFrom(const APValue &V) {
  1278. assert(V.isMemberPointer());
  1279. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1280. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1281. Path.clear();
  1282. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1283. Path.insert(Path.end(), P.begin(), P.end());
  1284. }
  1285. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1286. /// whether the member is a member of some class derived from the class type
  1287. /// of the member pointer.
  1288. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1289. /// Path - The path of base/derived classes from the member declaration's
  1290. /// class (exclusive) to the class type of the member pointer (inclusive).
  1291. SmallVector<const CXXRecordDecl*, 4> Path;
  1292. /// Perform a cast towards the class of the Decl (either up or down the
  1293. /// hierarchy).
  1294. bool castBack(const CXXRecordDecl *Class) {
  1295. assert(!Path.empty());
  1296. const CXXRecordDecl *Expected;
  1297. if (Path.size() >= 2)
  1298. Expected = Path[Path.size() - 2];
  1299. else
  1300. Expected = getContainingRecord();
  1301. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1302. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1303. // if B does not contain the original member and is not a base or
  1304. // derived class of the class containing the original member, the result
  1305. // of the cast is undefined.
  1306. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1307. // (D::*). We consider that to be a language defect.
  1308. return false;
  1309. }
  1310. Path.pop_back();
  1311. return true;
  1312. }
  1313. /// Perform a base-to-derived member pointer cast.
  1314. bool castToDerived(const CXXRecordDecl *Derived) {
  1315. if (!getDecl())
  1316. return true;
  1317. if (!isDerivedMember()) {
  1318. Path.push_back(Derived);
  1319. return true;
  1320. }
  1321. if (!castBack(Derived))
  1322. return false;
  1323. if (Path.empty())
  1324. DeclAndIsDerivedMember.setInt(false);
  1325. return true;
  1326. }
  1327. /// Perform a derived-to-base member pointer cast.
  1328. bool castToBase(const CXXRecordDecl *Base) {
  1329. if (!getDecl())
  1330. return true;
  1331. if (Path.empty())
  1332. DeclAndIsDerivedMember.setInt(true);
  1333. if (isDerivedMember()) {
  1334. Path.push_back(Base);
  1335. return true;
  1336. }
  1337. return castBack(Base);
  1338. }
  1339. };
  1340. /// Compare two member pointers, which are assumed to be of the same type.
  1341. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1342. if (!LHS.getDecl() || !RHS.getDecl())
  1343. return !LHS.getDecl() && !RHS.getDecl();
  1344. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1345. return false;
  1346. return LHS.Path == RHS.Path;
  1347. }
  1348. }
  1349. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1350. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1351. const LValue &This, const Expr *E,
  1352. bool AllowNonLiteralTypes = false);
  1353. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1354. bool InvalidBaseOK = false);
  1355. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1356. bool InvalidBaseOK = false);
  1357. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1358. EvalInfo &Info);
  1359. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1360. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1361. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1362. EvalInfo &Info);
  1363. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1364. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1365. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1366. EvalInfo &Info);
  1367. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1368. /// Evaluate an integer or fixed point expression into an APResult.
  1369. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1370. EvalInfo &Info);
  1371. /// Evaluate only a fixed point expression into an APResult.
  1372. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1373. EvalInfo &Info);
  1374. //===----------------------------------------------------------------------===//
  1375. // Misc utilities
  1376. //===----------------------------------------------------------------------===//
  1377. /// A helper function to create a temporary and set an LValue.
  1378. template <class KeyTy>
  1379. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1380. LValue &LV, CallStackFrame &Frame) {
  1381. LV.set({Key, Frame.Info.CurrentCall->Index,
  1382. Frame.Info.CurrentCall->getTempVersion()});
  1383. return Frame.createTemporary(Key, IsLifetimeExtended);
  1384. }
  1385. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1386. /// preserving its value (by extending by up to one bit as needed).
  1387. static void negateAsSigned(APSInt &Int) {
  1388. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1389. Int = Int.extend(Int.getBitWidth() + 1);
  1390. Int.setIsSigned(true);
  1391. }
  1392. Int = -Int;
  1393. }
  1394. /// Produce a string describing the given constexpr call.
  1395. void CallStackFrame::describe(raw_ostream &Out) {
  1396. unsigned ArgIndex = 0;
  1397. bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
  1398. !isa<CXXConstructorDecl>(Callee) &&
  1399. cast<CXXMethodDecl>(Callee)->isInstance();
  1400. if (!IsMemberCall)
  1401. Out << *Callee << '(';
  1402. if (This && IsMemberCall) {
  1403. APValue Val;
  1404. This->moveInto(Val);
  1405. Val.printPretty(Out, Info.Ctx,
  1406. This->Designator.MostDerivedType);
  1407. // FIXME: Add parens around Val if needed.
  1408. Out << "->" << *Callee << '(';
  1409. IsMemberCall = false;
  1410. }
  1411. for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
  1412. E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1413. if (ArgIndex > (unsigned)IsMemberCall)
  1414. Out << ", ";
  1415. const ParmVarDecl *Param = *I;
  1416. const APValue &Arg = Arguments[ArgIndex];
  1417. Arg.printPretty(Out, Info.Ctx, Param->getType());
  1418. if (ArgIndex == 0 && IsMemberCall)
  1419. Out << "->" << *Callee << '(';
  1420. }
  1421. Out << ')';
  1422. }
  1423. /// Evaluate an expression to see if it had side-effects, and discard its
  1424. /// result.
  1425. /// \return \c true if the caller should keep evaluating.
  1426. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1427. APValue Scratch;
  1428. if (!Evaluate(Scratch, Info, E))
  1429. // We don't need the value, but we might have skipped a side effect here.
  1430. return Info.noteSideEffect();
  1431. return true;
  1432. }
  1433. /// Should this call expression be treated as a string literal?
  1434. static bool IsStringLiteralCall(const CallExpr *E) {
  1435. unsigned Builtin = E->getBuiltinCallee();
  1436. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1437. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1438. }
  1439. static bool IsGlobalLValue(APValue::LValueBase B) {
  1440. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1441. // constant expression of pointer type that evaluates to...
  1442. // ... a null pointer value, or a prvalue core constant expression of type
  1443. // std::nullptr_t.
  1444. if (!B) return true;
  1445. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1446. // ... the address of an object with static storage duration,
  1447. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1448. return VD->hasGlobalStorage();
  1449. // ... the address of a function,
  1450. return isa<FunctionDecl>(D);
  1451. }
  1452. if (B.is<TypeInfoLValue>())
  1453. return true;
  1454. const Expr *E = B.get<const Expr*>();
  1455. switch (E->getStmtClass()) {
  1456. default:
  1457. return false;
  1458. case Expr::CompoundLiteralExprClass: {
  1459. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1460. return CLE->isFileScope() && CLE->isLValue();
  1461. }
  1462. case Expr::MaterializeTemporaryExprClass:
  1463. // A materialized temporary might have been lifetime-extended to static
  1464. // storage duration.
  1465. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1466. // A string literal has static storage duration.
  1467. case Expr::StringLiteralClass:
  1468. case Expr::PredefinedExprClass:
  1469. case Expr::ObjCStringLiteralClass:
  1470. case Expr::ObjCEncodeExprClass:
  1471. case Expr::CXXUuidofExprClass:
  1472. return true;
  1473. case Expr::ObjCBoxedExprClass:
  1474. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1475. case Expr::CallExprClass:
  1476. return IsStringLiteralCall(cast<CallExpr>(E));
  1477. // For GCC compatibility, &&label has static storage duration.
  1478. case Expr::AddrLabelExprClass:
  1479. return true;
  1480. // A Block literal expression may be used as the initialization value for
  1481. // Block variables at global or local static scope.
  1482. case Expr::BlockExprClass:
  1483. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1484. case Expr::ImplicitValueInitExprClass:
  1485. // FIXME:
  1486. // We can never form an lvalue with an implicit value initialization as its
  1487. // base through expression evaluation, so these only appear in one case: the
  1488. // implicit variable declaration we invent when checking whether a constexpr
  1489. // constructor can produce a constant expression. We must assume that such
  1490. // an expression might be a global lvalue.
  1491. return true;
  1492. }
  1493. }
  1494. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1495. return LVal.Base.dyn_cast<const ValueDecl*>();
  1496. }
  1497. static bool IsLiteralLValue(const LValue &Value) {
  1498. if (Value.getLValueCallIndex())
  1499. return false;
  1500. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1501. return E && !isa<MaterializeTemporaryExpr>(E);
  1502. }
  1503. static bool IsWeakLValue(const LValue &Value) {
  1504. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1505. return Decl && Decl->isWeak();
  1506. }
  1507. static bool isZeroSized(const LValue &Value) {
  1508. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1509. if (Decl && isa<VarDecl>(Decl)) {
  1510. QualType Ty = Decl->getType();
  1511. if (Ty->isArrayType())
  1512. return Ty->isIncompleteType() ||
  1513. Decl->getASTContext().getTypeSize(Ty) == 0;
  1514. }
  1515. return false;
  1516. }
  1517. static bool HasSameBase(const LValue &A, const LValue &B) {
  1518. if (!A.getLValueBase())
  1519. return !B.getLValueBase();
  1520. if (!B.getLValueBase())
  1521. return false;
  1522. if (A.getLValueBase().getOpaqueValue() !=
  1523. B.getLValueBase().getOpaqueValue()) {
  1524. const Decl *ADecl = GetLValueBaseDecl(A);
  1525. if (!ADecl)
  1526. return false;
  1527. const Decl *BDecl = GetLValueBaseDecl(B);
  1528. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1529. return false;
  1530. }
  1531. return IsGlobalLValue(A.getLValueBase()) ||
  1532. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1533. A.getLValueVersion() == B.getLValueVersion());
  1534. }
  1535. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1536. assert(Base && "no location for a null lvalue");
  1537. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1538. if (VD)
  1539. Info.Note(VD->getLocation(), diag::note_declared_at);
  1540. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1541. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1542. // We have no information to show for a typeid(T) object.
  1543. }
  1544. /// Check that this reference or pointer core constant expression is a valid
  1545. /// value for an address or reference constant expression. Return true if we
  1546. /// can fold this expression, whether or not it's a constant expression.
  1547. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1548. QualType Type, const LValue &LVal,
  1549. Expr::ConstExprUsage Usage) {
  1550. bool IsReferenceType = Type->isReferenceType();
  1551. APValue::LValueBase Base = LVal.getLValueBase();
  1552. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1553. // Check that the object is a global. Note that the fake 'this' object we
  1554. // manufacture when checking potential constant expressions is conservatively
  1555. // assumed to be global here.
  1556. if (!IsGlobalLValue(Base)) {
  1557. if (Info.getLangOpts().CPlusPlus11) {
  1558. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1559. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1560. << IsReferenceType << !Designator.Entries.empty()
  1561. << !!VD << VD;
  1562. NoteLValueLocation(Info, Base);
  1563. } else {
  1564. Info.FFDiag(Loc);
  1565. }
  1566. // Don't allow references to temporaries to escape.
  1567. return false;
  1568. }
  1569. assert((Info.checkingPotentialConstantExpression() ||
  1570. LVal.getLValueCallIndex() == 0) &&
  1571. "have call index for global lvalue");
  1572. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1573. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1574. // Check if this is a thread-local variable.
  1575. if (Var->getTLSKind())
  1576. return false;
  1577. // A dllimport variable never acts like a constant.
  1578. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1579. return false;
  1580. }
  1581. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1582. // __declspec(dllimport) must be handled very carefully:
  1583. // We must never initialize an expression with the thunk in C++.
  1584. // Doing otherwise would allow the same id-expression to yield
  1585. // different addresses for the same function in different translation
  1586. // units. However, this means that we must dynamically initialize the
  1587. // expression with the contents of the import address table at runtime.
  1588. //
  1589. // The C language has no notion of ODR; furthermore, it has no notion of
  1590. // dynamic initialization. This means that we are permitted to
  1591. // perform initialization with the address of the thunk.
  1592. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1593. FD->hasAttr<DLLImportAttr>())
  1594. return false;
  1595. }
  1596. }
  1597. // Allow address constant expressions to be past-the-end pointers. This is
  1598. // an extension: the standard requires them to point to an object.
  1599. if (!IsReferenceType)
  1600. return true;
  1601. // A reference constant expression must refer to an object.
  1602. if (!Base) {
  1603. // FIXME: diagnostic
  1604. Info.CCEDiag(Loc);
  1605. return true;
  1606. }
  1607. // Does this refer one past the end of some object?
  1608. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1609. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1610. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1611. << !Designator.Entries.empty() << !!VD << VD;
  1612. NoteLValueLocation(Info, Base);
  1613. }
  1614. return true;
  1615. }
  1616. /// Member pointers are constant expressions unless they point to a
  1617. /// non-virtual dllimport member function.
  1618. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1619. SourceLocation Loc,
  1620. QualType Type,
  1621. const APValue &Value,
  1622. Expr::ConstExprUsage Usage) {
  1623. const ValueDecl *Member = Value.getMemberPointerDecl();
  1624. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1625. if (!FD)
  1626. return true;
  1627. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1628. !FD->hasAttr<DLLImportAttr>();
  1629. }
  1630. /// Check that this core constant expression is of literal type, and if not,
  1631. /// produce an appropriate diagnostic.
  1632. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1633. const LValue *This = nullptr) {
  1634. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1635. return true;
  1636. // C++1y: A constant initializer for an object o [...] may also invoke
  1637. // constexpr constructors for o and its subobjects even if those objects
  1638. // are of non-literal class types.
  1639. //
  1640. // C++11 missed this detail for aggregates, so classes like this:
  1641. // struct foo_t { union { int i; volatile int j; } u; };
  1642. // are not (obviously) initializable like so:
  1643. // __attribute__((__require_constant_initialization__))
  1644. // static const foo_t x = {{0}};
  1645. // because "i" is a subobject with non-literal initialization (due to the
  1646. // volatile member of the union). See:
  1647. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1648. // Therefore, we use the C++1y behavior.
  1649. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1650. return true;
  1651. // Prvalue constant expressions must be of literal types.
  1652. if (Info.getLangOpts().CPlusPlus11)
  1653. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1654. << E->getType();
  1655. else
  1656. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1657. return false;
  1658. }
  1659. /// Check that this core constant expression value is a valid value for a
  1660. /// constant expression. If not, report an appropriate diagnostic. Does not
  1661. /// check that the expression is of literal type.
  1662. static bool
  1663. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1664. const APValue &Value,
  1665. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
  1666. SourceLocation SubobjectLoc = SourceLocation()) {
  1667. if (!Value.hasValue()) {
  1668. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1669. << true << Type;
  1670. if (SubobjectLoc.isValid())
  1671. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  1672. return false;
  1673. }
  1674. // We allow _Atomic(T) to be initialized from anything that T can be
  1675. // initialized from.
  1676. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1677. Type = AT->getValueType();
  1678. // Core issue 1454: For a literal constant expression of array or class type,
  1679. // each subobject of its value shall have been initialized by a constant
  1680. // expression.
  1681. if (Value.isArray()) {
  1682. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1683. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1684. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1685. Value.getArrayInitializedElt(I), Usage,
  1686. SubobjectLoc))
  1687. return false;
  1688. }
  1689. if (!Value.hasArrayFiller())
  1690. return true;
  1691. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1692. Usage, SubobjectLoc);
  1693. }
  1694. if (Value.isUnion() && Value.getUnionField()) {
  1695. return CheckConstantExpression(Info, DiagLoc,
  1696. Value.getUnionField()->getType(),
  1697. Value.getUnionValue(), Usage,
  1698. Value.getUnionField()->getLocation());
  1699. }
  1700. if (Value.isStruct()) {
  1701. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1702. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1703. unsigned BaseIndex = 0;
  1704. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1705. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1706. Value.getStructBase(BaseIndex), Usage,
  1707. BS.getBeginLoc()))
  1708. return false;
  1709. ++BaseIndex;
  1710. }
  1711. }
  1712. for (const auto *I : RD->fields()) {
  1713. if (I->isUnnamedBitfield())
  1714. continue;
  1715. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1716. Value.getStructField(I->getFieldIndex()),
  1717. Usage, I->getLocation()))
  1718. return false;
  1719. }
  1720. }
  1721. if (Value.isLValue()) {
  1722. LValue LVal;
  1723. LVal.setFrom(Info.Ctx, Value);
  1724. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1725. }
  1726. if (Value.isMemberPointer())
  1727. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1728. // Everything else is fine.
  1729. return true;
  1730. }
  1731. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1732. // A null base expression indicates a null pointer. These are always
  1733. // evaluatable, and they are false unless the offset is zero.
  1734. if (!Value.getLValueBase()) {
  1735. Result = !Value.getLValueOffset().isZero();
  1736. return true;
  1737. }
  1738. // We have a non-null base. These are generally known to be true, but if it's
  1739. // a weak declaration it can be null at runtime.
  1740. Result = true;
  1741. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1742. return !Decl || !Decl->isWeak();
  1743. }
  1744. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1745. switch (Val.getKind()) {
  1746. case APValue::None:
  1747. case APValue::Indeterminate:
  1748. return false;
  1749. case APValue::Int:
  1750. Result = Val.getInt().getBoolValue();
  1751. return true;
  1752. case APValue::FixedPoint:
  1753. Result = Val.getFixedPoint().getBoolValue();
  1754. return true;
  1755. case APValue::Float:
  1756. Result = !Val.getFloat().isZero();
  1757. return true;
  1758. case APValue::ComplexInt:
  1759. Result = Val.getComplexIntReal().getBoolValue() ||
  1760. Val.getComplexIntImag().getBoolValue();
  1761. return true;
  1762. case APValue::ComplexFloat:
  1763. Result = !Val.getComplexFloatReal().isZero() ||
  1764. !Val.getComplexFloatImag().isZero();
  1765. return true;
  1766. case APValue::LValue:
  1767. return EvalPointerValueAsBool(Val, Result);
  1768. case APValue::MemberPointer:
  1769. Result = Val.getMemberPointerDecl();
  1770. return true;
  1771. case APValue::Vector:
  1772. case APValue::Array:
  1773. case APValue::Struct:
  1774. case APValue::Union:
  1775. case APValue::AddrLabelDiff:
  1776. return false;
  1777. }
  1778. llvm_unreachable("unknown APValue kind");
  1779. }
  1780. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1781. EvalInfo &Info) {
  1782. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1783. APValue Val;
  1784. if (!Evaluate(Val, Info, E))
  1785. return false;
  1786. return HandleConversionToBool(Val, Result);
  1787. }
  1788. template<typename T>
  1789. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1790. const T &SrcValue, QualType DestType) {
  1791. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1792. << SrcValue << DestType;
  1793. return Info.noteUndefinedBehavior();
  1794. }
  1795. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1796. QualType SrcType, const APFloat &Value,
  1797. QualType DestType, APSInt &Result) {
  1798. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1799. // Determine whether we are converting to unsigned or signed.
  1800. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1801. Result = APSInt(DestWidth, !DestSigned);
  1802. bool ignored;
  1803. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1804. & APFloat::opInvalidOp)
  1805. return HandleOverflow(Info, E, Value, DestType);
  1806. return true;
  1807. }
  1808. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1809. QualType SrcType, QualType DestType,
  1810. APFloat &Result) {
  1811. APFloat Value = Result;
  1812. bool ignored;
  1813. Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1814. APFloat::rmNearestTiesToEven, &ignored);
  1815. return true;
  1816. }
  1817. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1818. QualType DestType, QualType SrcType,
  1819. const APSInt &Value) {
  1820. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1821. // Figure out if this is a truncate, extend or noop cast.
  1822. // If the input is signed, do a sign extend, noop, or truncate.
  1823. APSInt Result = Value.extOrTrunc(DestWidth);
  1824. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1825. if (DestType->isBooleanType())
  1826. Result = Value.getBoolValue();
  1827. return Result;
  1828. }
  1829. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1830. QualType SrcType, const APSInt &Value,
  1831. QualType DestType, APFloat &Result) {
  1832. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1833. Result.convertFromAPInt(Value, Value.isSigned(),
  1834. APFloat::rmNearestTiesToEven);
  1835. return true;
  1836. }
  1837. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1838. APValue &Value, const FieldDecl *FD) {
  1839. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1840. if (!Value.isInt()) {
  1841. // Trying to store a pointer-cast-to-integer into a bitfield.
  1842. // FIXME: In this case, we should provide the diagnostic for casting
  1843. // a pointer to an integer.
  1844. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1845. Info.FFDiag(E);
  1846. return false;
  1847. }
  1848. APSInt &Int = Value.getInt();
  1849. unsigned OldBitWidth = Int.getBitWidth();
  1850. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1851. if (NewBitWidth < OldBitWidth)
  1852. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1853. return true;
  1854. }
  1855. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1856. llvm::APInt &Res) {
  1857. APValue SVal;
  1858. if (!Evaluate(SVal, Info, E))
  1859. return false;
  1860. if (SVal.isInt()) {
  1861. Res = SVal.getInt();
  1862. return true;
  1863. }
  1864. if (SVal.isFloat()) {
  1865. Res = SVal.getFloat().bitcastToAPInt();
  1866. return true;
  1867. }
  1868. if (SVal.isVector()) {
  1869. QualType VecTy = E->getType();
  1870. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1871. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1872. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1873. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1874. Res = llvm::APInt::getNullValue(VecSize);
  1875. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1876. APValue &Elt = SVal.getVectorElt(i);
  1877. llvm::APInt EltAsInt;
  1878. if (Elt.isInt()) {
  1879. EltAsInt = Elt.getInt();
  1880. } else if (Elt.isFloat()) {
  1881. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1882. } else {
  1883. // Don't try to handle vectors of anything other than int or float
  1884. // (not sure if it's possible to hit this case).
  1885. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1886. return false;
  1887. }
  1888. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1889. if (BigEndian)
  1890. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1891. else
  1892. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1893. }
  1894. return true;
  1895. }
  1896. // Give up if the input isn't an int, float, or vector. For example, we
  1897. // reject "(v4i16)(intptr_t)&a".
  1898. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1899. return false;
  1900. }
  1901. /// Perform the given integer operation, which is known to need at most BitWidth
  1902. /// bits, and check for overflow in the original type (if that type was not an
  1903. /// unsigned type).
  1904. template<typename Operation>
  1905. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1906. const APSInt &LHS, const APSInt &RHS,
  1907. unsigned BitWidth, Operation Op,
  1908. APSInt &Result) {
  1909. if (LHS.isUnsigned()) {
  1910. Result = Op(LHS, RHS);
  1911. return true;
  1912. }
  1913. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1914. Result = Value.trunc(LHS.getBitWidth());
  1915. if (Result.extend(BitWidth) != Value) {
  1916. if (Info.checkingForOverflow())
  1917. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1918. diag::warn_integer_constant_overflow)
  1919. << Result.toString(10) << E->getType();
  1920. else
  1921. return HandleOverflow(Info, E, Value, E->getType());
  1922. }
  1923. return true;
  1924. }
  1925. /// Perform the given binary integer operation.
  1926. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1927. BinaryOperatorKind Opcode, APSInt RHS,
  1928. APSInt &Result) {
  1929. switch (Opcode) {
  1930. default:
  1931. Info.FFDiag(E);
  1932. return false;
  1933. case BO_Mul:
  1934. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1935. std::multiplies<APSInt>(), Result);
  1936. case BO_Add:
  1937. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1938. std::plus<APSInt>(), Result);
  1939. case BO_Sub:
  1940. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1941. std::minus<APSInt>(), Result);
  1942. case BO_And: Result = LHS & RHS; return true;
  1943. case BO_Xor: Result = LHS ^ RHS; return true;
  1944. case BO_Or: Result = LHS | RHS; return true;
  1945. case BO_Div:
  1946. case BO_Rem:
  1947. if (RHS == 0) {
  1948. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  1949. return false;
  1950. }
  1951. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1952. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  1953. // this operation and gives the two's complement result.
  1954. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1955. LHS.isSigned() && LHS.isMinSignedValue())
  1956. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  1957. E->getType());
  1958. return true;
  1959. case BO_Shl: {
  1960. if (Info.getLangOpts().OpenCL)
  1961. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1962. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1963. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1964. RHS.isUnsigned());
  1965. else if (RHS.isSigned() && RHS.isNegative()) {
  1966. // During constant-folding, a negative shift is an opposite shift. Such
  1967. // a shift is not a constant expression.
  1968. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1969. RHS = -RHS;
  1970. goto shift_right;
  1971. }
  1972. shift_left:
  1973. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  1974. // the shifted type.
  1975. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1976. if (SA != RHS) {
  1977. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1978. << RHS << E->getType() << LHS.getBitWidth();
  1979. } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
  1980. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  1981. // operand, and must not overflow the corresponding unsigned type.
  1982. // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
  1983. // E1 x 2^E2 module 2^N.
  1984. if (LHS.isNegative())
  1985. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  1986. else if (LHS.countLeadingZeros() < SA)
  1987. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  1988. }
  1989. Result = LHS << SA;
  1990. return true;
  1991. }
  1992. case BO_Shr: {
  1993. if (Info.getLangOpts().OpenCL)
  1994. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1995. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1996. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1997. RHS.isUnsigned());
  1998. else if (RHS.isSigned() && RHS.isNegative()) {
  1999. // During constant-folding, a negative shift is an opposite shift. Such a
  2000. // shift is not a constant expression.
  2001. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2002. RHS = -RHS;
  2003. goto shift_left;
  2004. }
  2005. shift_right:
  2006. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2007. // shifted type.
  2008. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2009. if (SA != RHS)
  2010. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2011. << RHS << E->getType() << LHS.getBitWidth();
  2012. Result = LHS >> SA;
  2013. return true;
  2014. }
  2015. case BO_LT: Result = LHS < RHS; return true;
  2016. case BO_GT: Result = LHS > RHS; return true;
  2017. case BO_LE: Result = LHS <= RHS; return true;
  2018. case BO_GE: Result = LHS >= RHS; return true;
  2019. case BO_EQ: Result = LHS == RHS; return true;
  2020. case BO_NE: Result = LHS != RHS; return true;
  2021. case BO_Cmp:
  2022. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2023. }
  2024. }
  2025. /// Perform the given binary floating-point operation, in-place, on LHS.
  2026. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2027. APFloat &LHS, BinaryOperatorKind Opcode,
  2028. const APFloat &RHS) {
  2029. switch (Opcode) {
  2030. default:
  2031. Info.FFDiag(E);
  2032. return false;
  2033. case BO_Mul:
  2034. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2035. break;
  2036. case BO_Add:
  2037. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2038. break;
  2039. case BO_Sub:
  2040. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2041. break;
  2042. case BO_Div:
  2043. // [expr.mul]p4:
  2044. // If the second operand of / or % is zero the behavior is undefined.
  2045. if (RHS.isZero())
  2046. Info.CCEDiag(E, diag::note_expr_divide_by_zero);
  2047. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2048. break;
  2049. }
  2050. // [expr.pre]p4:
  2051. // If during the evaluation of an expression, the result is not
  2052. // mathematically defined [...], the behavior is undefined.
  2053. // FIXME: C++ rules require us to not conform to IEEE 754 here.
  2054. if (LHS.isNaN()) {
  2055. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2056. return Info.noteUndefinedBehavior();
  2057. }
  2058. return true;
  2059. }
  2060. /// Cast an lvalue referring to a base subobject to a derived class, by
  2061. /// truncating the lvalue's path to the given length.
  2062. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2063. const RecordDecl *TruncatedType,
  2064. unsigned TruncatedElements) {
  2065. SubobjectDesignator &D = Result.Designator;
  2066. // Check we actually point to a derived class object.
  2067. if (TruncatedElements == D.Entries.size())
  2068. return true;
  2069. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2070. "not casting to a derived class");
  2071. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2072. return false;
  2073. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2074. const RecordDecl *RD = TruncatedType;
  2075. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2076. if (RD->isInvalidDecl()) return false;
  2077. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2078. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2079. if (isVirtualBaseClass(D.Entries[I]))
  2080. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2081. else
  2082. Result.Offset -= Layout.getBaseClassOffset(Base);
  2083. RD = Base;
  2084. }
  2085. D.Entries.resize(TruncatedElements);
  2086. return true;
  2087. }
  2088. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2089. const CXXRecordDecl *Derived,
  2090. const CXXRecordDecl *Base,
  2091. const ASTRecordLayout *RL = nullptr) {
  2092. if (!RL) {
  2093. if (Derived->isInvalidDecl()) return false;
  2094. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2095. }
  2096. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2097. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2098. return true;
  2099. }
  2100. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2101. const CXXRecordDecl *DerivedDecl,
  2102. const CXXBaseSpecifier *Base) {
  2103. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2104. if (!Base->isVirtual())
  2105. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2106. SubobjectDesignator &D = Obj.Designator;
  2107. if (D.Invalid)
  2108. return false;
  2109. // Extract most-derived object and corresponding type.
  2110. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2111. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2112. return false;
  2113. // Find the virtual base class.
  2114. if (DerivedDecl->isInvalidDecl()) return false;
  2115. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2116. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2117. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2118. return true;
  2119. }
  2120. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2121. QualType Type, LValue &Result) {
  2122. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2123. PathE = E->path_end();
  2124. PathI != PathE; ++PathI) {
  2125. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2126. *PathI))
  2127. return false;
  2128. Type = (*PathI)->getType();
  2129. }
  2130. return true;
  2131. }
  2132. /// Cast an lvalue referring to a derived class to a known base subobject.
  2133. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2134. const CXXRecordDecl *DerivedRD,
  2135. const CXXRecordDecl *BaseRD) {
  2136. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2137. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2138. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2139. llvm_unreachable("Class must be derived from the passed in base class!");
  2140. for (CXXBasePathElement &Elem : Paths.front())
  2141. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2142. return false;
  2143. return true;
  2144. }
  2145. /// Update LVal to refer to the given field, which must be a member of the type
  2146. /// currently described by LVal.
  2147. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2148. const FieldDecl *FD,
  2149. const ASTRecordLayout *RL = nullptr) {
  2150. if (!RL) {
  2151. if (FD->getParent()->isInvalidDecl()) return false;
  2152. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2153. }
  2154. unsigned I = FD->getFieldIndex();
  2155. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2156. LVal.addDecl(Info, E, FD);
  2157. return true;
  2158. }
  2159. /// Update LVal to refer to the given indirect field.
  2160. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2161. LValue &LVal,
  2162. const IndirectFieldDecl *IFD) {
  2163. for (const auto *C : IFD->chain())
  2164. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2165. return false;
  2166. return true;
  2167. }
  2168. /// Get the size of the given type in char units.
  2169. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2170. QualType Type, CharUnits &Size) {
  2171. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2172. // extension.
  2173. if (Type->isVoidType() || Type->isFunctionType()) {
  2174. Size = CharUnits::One();
  2175. return true;
  2176. }
  2177. if (Type->isDependentType()) {
  2178. Info.FFDiag(Loc);
  2179. return false;
  2180. }
  2181. if (!Type->isConstantSizeType()) {
  2182. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2183. // FIXME: Better diagnostic.
  2184. Info.FFDiag(Loc);
  2185. return false;
  2186. }
  2187. Size = Info.Ctx.getTypeSizeInChars(Type);
  2188. return true;
  2189. }
  2190. /// Update a pointer value to model pointer arithmetic.
  2191. /// \param Info - Information about the ongoing evaluation.
  2192. /// \param E - The expression being evaluated, for diagnostic purposes.
  2193. /// \param LVal - The pointer value to be updated.
  2194. /// \param EltTy - The pointee type represented by LVal.
  2195. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2196. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2197. LValue &LVal, QualType EltTy,
  2198. APSInt Adjustment) {
  2199. CharUnits SizeOfPointee;
  2200. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2201. return false;
  2202. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2203. return true;
  2204. }
  2205. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2206. LValue &LVal, QualType EltTy,
  2207. int64_t Adjustment) {
  2208. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2209. APSInt::get(Adjustment));
  2210. }
  2211. /// Update an lvalue to refer to a component of a complex number.
  2212. /// \param Info - Information about the ongoing evaluation.
  2213. /// \param LVal - The lvalue to be updated.
  2214. /// \param EltTy - The complex number's component type.
  2215. /// \param Imag - False for the real component, true for the imaginary.
  2216. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2217. LValue &LVal, QualType EltTy,
  2218. bool Imag) {
  2219. if (Imag) {
  2220. CharUnits SizeOfComponent;
  2221. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2222. return false;
  2223. LVal.Offset += SizeOfComponent;
  2224. }
  2225. LVal.addComplex(Info, E, EltTy, Imag);
  2226. return true;
  2227. }
  2228. /// Try to evaluate the initializer for a variable declaration.
  2229. ///
  2230. /// \param Info Information about the ongoing evaluation.
  2231. /// \param E An expression to be used when printing diagnostics.
  2232. /// \param VD The variable whose initializer should be obtained.
  2233. /// \param Frame The frame in which the variable was created. Must be null
  2234. /// if this variable is not local to the evaluation.
  2235. /// \param Result Filled in with a pointer to the value of the variable.
  2236. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2237. const VarDecl *VD, CallStackFrame *Frame,
  2238. APValue *&Result, const LValue *LVal) {
  2239. // If this is a parameter to an active constexpr function call, perform
  2240. // argument substitution.
  2241. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2242. // Assume arguments of a potential constant expression are unknown
  2243. // constant expressions.
  2244. if (Info.checkingPotentialConstantExpression())
  2245. return false;
  2246. if (!Frame || !Frame->Arguments) {
  2247. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2248. return false;
  2249. }
  2250. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2251. return true;
  2252. }
  2253. // If this is a local variable, dig out its value.
  2254. if (Frame) {
  2255. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2256. : Frame->getCurrentTemporary(VD);
  2257. if (!Result) {
  2258. // Assume variables referenced within a lambda's call operator that were
  2259. // not declared within the call operator are captures and during checking
  2260. // of a potential constant expression, assume they are unknown constant
  2261. // expressions.
  2262. assert(isLambdaCallOperator(Frame->Callee) &&
  2263. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2264. "missing value for local variable");
  2265. if (Info.checkingPotentialConstantExpression())
  2266. return false;
  2267. // FIXME: implement capture evaluation during constant expr evaluation.
  2268. Info.FFDiag(E->getBeginLoc(),
  2269. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2270. << "captures not currently allowed";
  2271. return false;
  2272. }
  2273. return true;
  2274. }
  2275. // Dig out the initializer, and use the declaration which it's attached to.
  2276. const Expr *Init = VD->getAnyInitializer(VD);
  2277. if (!Init || Init->isValueDependent()) {
  2278. // If we're checking a potential constant expression, the variable could be
  2279. // initialized later.
  2280. if (!Info.checkingPotentialConstantExpression())
  2281. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2282. return false;
  2283. }
  2284. // If we're currently evaluating the initializer of this declaration, use that
  2285. // in-flight value.
  2286. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2287. Result = Info.EvaluatingDeclValue;
  2288. return true;
  2289. }
  2290. // Never evaluate the initializer of a weak variable. We can't be sure that
  2291. // this is the definition which will be used.
  2292. if (VD->isWeak()) {
  2293. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2294. return false;
  2295. }
  2296. // Check that we can fold the initializer. In C++, we will have already done
  2297. // this in the cases where it matters for conformance.
  2298. SmallVector<PartialDiagnosticAt, 8> Notes;
  2299. if (!VD->evaluateValue(Notes)) {
  2300. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2301. Notes.size() + 1) << VD;
  2302. Info.Note(VD->getLocation(), diag::note_declared_at);
  2303. Info.addNotes(Notes);
  2304. return false;
  2305. } else if (!VD->checkInitIsICE()) {
  2306. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2307. Notes.size() + 1) << VD;
  2308. Info.Note(VD->getLocation(), diag::note_declared_at);
  2309. Info.addNotes(Notes);
  2310. }
  2311. Result = VD->getEvaluatedValue();
  2312. return true;
  2313. }
  2314. static bool IsConstNonVolatile(QualType T) {
  2315. Qualifiers Quals = T.getQualifiers();
  2316. return Quals.hasConst() && !Quals.hasVolatile();
  2317. }
  2318. /// Get the base index of the given base class within an APValue representing
  2319. /// the given derived class.
  2320. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2321. const CXXRecordDecl *Base) {
  2322. Base = Base->getCanonicalDecl();
  2323. unsigned Index = 0;
  2324. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2325. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2326. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2327. return Index;
  2328. }
  2329. llvm_unreachable("base class missing from derived class's bases list");
  2330. }
  2331. /// Extract the value of a character from a string literal.
  2332. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2333. uint64_t Index) {
  2334. assert(!isa<SourceLocExpr>(Lit) &&
  2335. "SourceLocExpr should have already been converted to a StringLiteral");
  2336. // FIXME: Support MakeStringConstant
  2337. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2338. std::string Str;
  2339. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2340. assert(Index <= Str.size() && "Index too large");
  2341. return APSInt::getUnsigned(Str.c_str()[Index]);
  2342. }
  2343. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2344. Lit = PE->getFunctionName();
  2345. const StringLiteral *S = cast<StringLiteral>(Lit);
  2346. const ConstantArrayType *CAT =
  2347. Info.Ctx.getAsConstantArrayType(S->getType());
  2348. assert(CAT && "string literal isn't an array");
  2349. QualType CharType = CAT->getElementType();
  2350. assert(CharType->isIntegerType() && "unexpected character type");
  2351. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2352. CharType->isUnsignedIntegerType());
  2353. if (Index < S->getLength())
  2354. Value = S->getCodeUnit(Index);
  2355. return Value;
  2356. }
  2357. // Expand a string literal into an array of characters.
  2358. //
  2359. // FIXME: This is inefficient; we should probably introduce something similar
  2360. // to the LLVM ConstantDataArray to make this cheaper.
  2361. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  2362. APValue &Result) {
  2363. const ConstantArrayType *CAT =
  2364. Info.Ctx.getAsConstantArrayType(S->getType());
  2365. assert(CAT && "string literal isn't an array");
  2366. QualType CharType = CAT->getElementType();
  2367. assert(CharType->isIntegerType() && "unexpected character type");
  2368. unsigned Elts = CAT->getSize().getZExtValue();
  2369. Result = APValue(APValue::UninitArray(),
  2370. std::min(S->getLength(), Elts), Elts);
  2371. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2372. CharType->isUnsignedIntegerType());
  2373. if (Result.hasArrayFiller())
  2374. Result.getArrayFiller() = APValue(Value);
  2375. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2376. Value = S->getCodeUnit(I);
  2377. Result.getArrayInitializedElt(I) = APValue(Value);
  2378. }
  2379. }
  2380. // Expand an array so that it has more than Index filled elements.
  2381. static void expandArray(APValue &Array, unsigned Index) {
  2382. unsigned Size = Array.getArraySize();
  2383. assert(Index < Size);
  2384. // Always at least double the number of elements for which we store a value.
  2385. unsigned OldElts = Array.getArrayInitializedElts();
  2386. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2387. NewElts = std::min(Size, std::max(NewElts, 8u));
  2388. // Copy the data across.
  2389. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2390. for (unsigned I = 0; I != OldElts; ++I)
  2391. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2392. for (unsigned I = OldElts; I != NewElts; ++I)
  2393. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2394. if (NewValue.hasArrayFiller())
  2395. NewValue.getArrayFiller() = Array.getArrayFiller();
  2396. Array.swap(NewValue);
  2397. }
  2398. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2399. /// conversion. If it's of class type, we may assume that the copy operation
  2400. /// is trivial. Note that this is never true for a union type with fields
  2401. /// (because the copy always "reads" the active member) and always true for
  2402. /// a non-class type.
  2403. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2404. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2405. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2406. return true;
  2407. if (RD->isEmpty())
  2408. return false;
  2409. for (auto *Field : RD->fields())
  2410. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2411. return true;
  2412. for (auto &BaseSpec : RD->bases())
  2413. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2414. return true;
  2415. return false;
  2416. }
  2417. /// Diagnose an attempt to read from any unreadable field within the specified
  2418. /// type, which might be a class type.
  2419. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2420. QualType T) {
  2421. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2422. if (!RD)
  2423. return false;
  2424. if (!RD->hasMutableFields())
  2425. return false;
  2426. for (auto *Field : RD->fields()) {
  2427. // If we're actually going to read this field in some way, then it can't
  2428. // be mutable. If we're in a union, then assigning to a mutable field
  2429. // (even an empty one) can change the active member, so that's not OK.
  2430. // FIXME: Add core issue number for the union case.
  2431. if (Field->isMutable() &&
  2432. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2433. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2434. Info.Note(Field->getLocation(), diag::note_declared_at);
  2435. return true;
  2436. }
  2437. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2438. return true;
  2439. }
  2440. for (auto &BaseSpec : RD->bases())
  2441. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2442. return true;
  2443. // All mutable fields were empty, and thus not actually read.
  2444. return false;
  2445. }
  2446. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  2447. APValue::LValueBase Base) {
  2448. // A temporary we created.
  2449. if (Base.getCallIndex())
  2450. return true;
  2451. auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2452. if (!Evaluating)
  2453. return false;
  2454. // The variable whose initializer we're evaluating.
  2455. if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
  2456. if (declaresSameEntity(Evaluating, BaseD))
  2457. return true;
  2458. // A temporary lifetime-extended by the variable whose initializer we're
  2459. // evaluating.
  2460. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  2461. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  2462. if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
  2463. return true;
  2464. return false;
  2465. }
  2466. namespace {
  2467. /// A handle to a complete object (an object that is not a subobject of
  2468. /// another object).
  2469. struct CompleteObject {
  2470. /// The identity of the object.
  2471. APValue::LValueBase Base;
  2472. /// The value of the complete object.
  2473. APValue *Value;
  2474. /// The type of the complete object.
  2475. QualType Type;
  2476. CompleteObject() : Value(nullptr) {}
  2477. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  2478. : Base(Base), Value(Value), Type(Type) {}
  2479. bool mayReadMutableMembers(EvalInfo &Info) const {
  2480. // In C++14 onwards, it is permitted to read a mutable member whose
  2481. // lifetime began within the evaluation.
  2482. // FIXME: Should we also allow this in C++11?
  2483. if (!Info.getLangOpts().CPlusPlus14)
  2484. return false;
  2485. return lifetimeStartedInEvaluation(Info, Base);
  2486. }
  2487. explicit operator bool() const { return !Type.isNull(); }
  2488. };
  2489. } // end anonymous namespace
  2490. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  2491. bool IsMutable = false) {
  2492. // C++ [basic.type.qualifier]p1:
  2493. // - A const object is an object of type const T or a non-mutable subobject
  2494. // of a const object.
  2495. if (ObjType.isConstQualified() && !IsMutable)
  2496. SubobjType.addConst();
  2497. // - A volatile object is an object of type const T or a subobject of a
  2498. // volatile object.
  2499. if (ObjType.isVolatileQualified())
  2500. SubobjType.addVolatile();
  2501. return SubobjType;
  2502. }
  2503. /// Find the designated sub-object of an rvalue.
  2504. template<typename SubobjectHandler>
  2505. typename SubobjectHandler::result_type
  2506. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2507. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2508. if (Sub.Invalid)
  2509. // A diagnostic will have already been produced.
  2510. return handler.failed();
  2511. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2512. if (Info.getLangOpts().CPlusPlus11)
  2513. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2514. ? diag::note_constexpr_access_past_end
  2515. : diag::note_constexpr_access_unsized_array)
  2516. << handler.AccessKind;
  2517. else
  2518. Info.FFDiag(E);
  2519. return handler.failed();
  2520. }
  2521. APValue *O = Obj.Value;
  2522. QualType ObjType = Obj.Type;
  2523. const FieldDecl *LastField = nullptr;
  2524. const FieldDecl *VolatileField = nullptr;
  2525. // Walk the designator's path to find the subobject.
  2526. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2527. // Reading an indeterminate value is undefined, but assigning over one is OK.
  2528. if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
  2529. if (!Info.checkingPotentialConstantExpression())
  2530. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  2531. << handler.AccessKind << O->isIndeterminate();
  2532. return handler.failed();
  2533. }
  2534. // C++ [class.ctor]p5:
  2535. // const and volatile semantics are not applied on an object under
  2536. // construction.
  2537. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  2538. ObjType->isRecordType() &&
  2539. Info.isEvaluatingConstructor(
  2540. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  2541. Sub.Entries.begin() + I)) !=
  2542. ConstructionPhase::None) {
  2543. ObjType = Info.Ctx.getCanonicalType(ObjType);
  2544. ObjType.removeLocalConst();
  2545. ObjType.removeLocalVolatile();
  2546. }
  2547. // If this is our last pass, check that the final object type is OK.
  2548. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  2549. // Accesses to volatile objects are prohibited.
  2550. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  2551. if (Info.getLangOpts().CPlusPlus) {
  2552. int DiagKind;
  2553. SourceLocation Loc;
  2554. const NamedDecl *Decl = nullptr;
  2555. if (VolatileField) {
  2556. DiagKind = 2;
  2557. Loc = VolatileField->getLocation();
  2558. Decl = VolatileField;
  2559. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  2560. DiagKind = 1;
  2561. Loc = VD->getLocation();
  2562. Decl = VD;
  2563. } else {
  2564. DiagKind = 0;
  2565. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  2566. Loc = E->getExprLoc();
  2567. }
  2568. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2569. << handler.AccessKind << DiagKind << Decl;
  2570. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  2571. } else {
  2572. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2573. }
  2574. return handler.failed();
  2575. }
  2576. // If we are reading an object of class type, there may still be more
  2577. // things we need to check: if there are any mutable subobjects, we
  2578. // cannot perform this read. (This only happens when performing a trivial
  2579. // copy or assignment.)
  2580. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2581. !Obj.mayReadMutableMembers(Info) &&
  2582. diagnoseUnreadableFields(Info, E, ObjType))
  2583. return handler.failed();
  2584. }
  2585. if (I == N) {
  2586. if (!handler.found(*O, ObjType))
  2587. return false;
  2588. // If we modified a bit-field, truncate it to the right width.
  2589. if (isModification(handler.AccessKind) &&
  2590. LastField && LastField->isBitField() &&
  2591. !truncateBitfieldValue(Info, E, *O, LastField))
  2592. return false;
  2593. return true;
  2594. }
  2595. LastField = nullptr;
  2596. if (ObjType->isArrayType()) {
  2597. // Next subobject is an array element.
  2598. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2599. assert(CAT && "vla in literal type?");
  2600. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2601. if (CAT->getSize().ule(Index)) {
  2602. // Note, it should not be possible to form a pointer with a valid
  2603. // designator which points more than one past the end of the array.
  2604. if (Info.getLangOpts().CPlusPlus11)
  2605. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2606. << handler.AccessKind;
  2607. else
  2608. Info.FFDiag(E);
  2609. return handler.failed();
  2610. }
  2611. ObjType = CAT->getElementType();
  2612. if (O->getArrayInitializedElts() > Index)
  2613. O = &O->getArrayInitializedElt(Index);
  2614. else if (handler.AccessKind != AK_Read) {
  2615. expandArray(*O, Index);
  2616. O = &O->getArrayInitializedElt(Index);
  2617. } else
  2618. O = &O->getArrayFiller();
  2619. } else if (ObjType->isAnyComplexType()) {
  2620. // Next subobject is a complex number.
  2621. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2622. if (Index > 1) {
  2623. if (Info.getLangOpts().CPlusPlus11)
  2624. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2625. << handler.AccessKind;
  2626. else
  2627. Info.FFDiag(E);
  2628. return handler.failed();
  2629. }
  2630. ObjType = getSubobjectType(
  2631. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  2632. assert(I == N - 1 && "extracting subobject of scalar?");
  2633. if (O->isComplexInt()) {
  2634. return handler.found(Index ? O->getComplexIntImag()
  2635. : O->getComplexIntReal(), ObjType);
  2636. } else {
  2637. assert(O->isComplexFloat());
  2638. return handler.found(Index ? O->getComplexFloatImag()
  2639. : O->getComplexFloatReal(), ObjType);
  2640. }
  2641. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2642. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2643. !Obj.mayReadMutableMembers(Info)) {
  2644. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2645. << Field;
  2646. Info.Note(Field->getLocation(), diag::note_declared_at);
  2647. return handler.failed();
  2648. }
  2649. // Next subobject is a class, struct or union field.
  2650. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2651. if (RD->isUnion()) {
  2652. const FieldDecl *UnionField = O->getUnionField();
  2653. if (!UnionField ||
  2654. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2655. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2656. << handler.AccessKind << Field << !UnionField << UnionField;
  2657. return handler.failed();
  2658. }
  2659. O = &O->getUnionValue();
  2660. } else
  2661. O = &O->getStructField(Field->getFieldIndex());
  2662. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  2663. LastField = Field;
  2664. if (Field->getType().isVolatileQualified())
  2665. VolatileField = Field;
  2666. } else {
  2667. // Next subobject is a base class.
  2668. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2669. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2670. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2671. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  2672. }
  2673. }
  2674. }
  2675. namespace {
  2676. struct ExtractSubobjectHandler {
  2677. EvalInfo &Info;
  2678. APValue &Result;
  2679. static const AccessKinds AccessKind = AK_Read;
  2680. typedef bool result_type;
  2681. bool failed() { return false; }
  2682. bool found(APValue &Subobj, QualType SubobjType) {
  2683. Result = Subobj;
  2684. return true;
  2685. }
  2686. bool found(APSInt &Value, QualType SubobjType) {
  2687. Result = APValue(Value);
  2688. return true;
  2689. }
  2690. bool found(APFloat &Value, QualType SubobjType) {
  2691. Result = APValue(Value);
  2692. return true;
  2693. }
  2694. };
  2695. } // end anonymous namespace
  2696. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2697. /// Extract the designated sub-object of an rvalue.
  2698. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2699. const CompleteObject &Obj,
  2700. const SubobjectDesignator &Sub,
  2701. APValue &Result) {
  2702. ExtractSubobjectHandler Handler = { Info, Result };
  2703. return findSubobject(Info, E, Obj, Sub, Handler);
  2704. }
  2705. namespace {
  2706. struct ModifySubobjectHandler {
  2707. EvalInfo &Info;
  2708. APValue &NewVal;
  2709. const Expr *E;
  2710. typedef bool result_type;
  2711. static const AccessKinds AccessKind = AK_Assign;
  2712. bool checkConst(QualType QT) {
  2713. // Assigning to a const object has undefined behavior.
  2714. if (QT.isConstQualified()) {
  2715. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2716. return false;
  2717. }
  2718. return true;
  2719. }
  2720. bool failed() { return false; }
  2721. bool found(APValue &Subobj, QualType SubobjType) {
  2722. if (!checkConst(SubobjType))
  2723. return false;
  2724. // We've been given ownership of NewVal, so just swap it in.
  2725. Subobj.swap(NewVal);
  2726. return true;
  2727. }
  2728. bool found(APSInt &Value, QualType SubobjType) {
  2729. if (!checkConst(SubobjType))
  2730. return false;
  2731. if (!NewVal.isInt()) {
  2732. // Maybe trying to write a cast pointer value into a complex?
  2733. Info.FFDiag(E);
  2734. return false;
  2735. }
  2736. Value = NewVal.getInt();
  2737. return true;
  2738. }
  2739. bool found(APFloat &Value, QualType SubobjType) {
  2740. if (!checkConst(SubobjType))
  2741. return false;
  2742. Value = NewVal.getFloat();
  2743. return true;
  2744. }
  2745. };
  2746. } // end anonymous namespace
  2747. const AccessKinds ModifySubobjectHandler::AccessKind;
  2748. /// Update the designated sub-object of an rvalue to the given value.
  2749. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2750. const CompleteObject &Obj,
  2751. const SubobjectDesignator &Sub,
  2752. APValue &NewVal) {
  2753. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2754. return findSubobject(Info, E, Obj, Sub, Handler);
  2755. }
  2756. /// Find the position where two subobject designators diverge, or equivalently
  2757. /// the length of the common initial subsequence.
  2758. static unsigned FindDesignatorMismatch(QualType ObjType,
  2759. const SubobjectDesignator &A,
  2760. const SubobjectDesignator &B,
  2761. bool &WasArrayIndex) {
  2762. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2763. for (/**/; I != N; ++I) {
  2764. if (!ObjType.isNull() &&
  2765. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2766. // Next subobject is an array element.
  2767. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  2768. WasArrayIndex = true;
  2769. return I;
  2770. }
  2771. if (ObjType->isAnyComplexType())
  2772. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2773. else
  2774. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2775. } else {
  2776. if (A.Entries[I].getAsBaseOrMember() !=
  2777. B.Entries[I].getAsBaseOrMember()) {
  2778. WasArrayIndex = false;
  2779. return I;
  2780. }
  2781. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2782. // Next subobject is a field.
  2783. ObjType = FD->getType();
  2784. else
  2785. // Next subobject is a base class.
  2786. ObjType = QualType();
  2787. }
  2788. }
  2789. WasArrayIndex = false;
  2790. return I;
  2791. }
  2792. /// Determine whether the given subobject designators refer to elements of the
  2793. /// same array object.
  2794. static bool AreElementsOfSameArray(QualType ObjType,
  2795. const SubobjectDesignator &A,
  2796. const SubobjectDesignator &B) {
  2797. if (A.Entries.size() != B.Entries.size())
  2798. return false;
  2799. bool IsArray = A.MostDerivedIsArrayElement;
  2800. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2801. // A is a subobject of the array element.
  2802. return false;
  2803. // If A (and B) designates an array element, the last entry will be the array
  2804. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2805. // of length 1' case, and the entire path must match.
  2806. bool WasArrayIndex;
  2807. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2808. return CommonLength >= A.Entries.size() - IsArray;
  2809. }
  2810. /// Find the complete object to which an LValue refers.
  2811. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2812. AccessKinds AK, const LValue &LVal,
  2813. QualType LValType) {
  2814. if (LVal.InvalidBase) {
  2815. Info.FFDiag(E);
  2816. return CompleteObject();
  2817. }
  2818. if (!LVal.Base) {
  2819. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2820. return CompleteObject();
  2821. }
  2822. CallStackFrame *Frame = nullptr;
  2823. unsigned Depth = 0;
  2824. if (LVal.getLValueCallIndex()) {
  2825. std::tie(Frame, Depth) =
  2826. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  2827. if (!Frame) {
  2828. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2829. << AK << LVal.Base.is<const ValueDecl*>();
  2830. NoteLValueLocation(Info, LVal.Base);
  2831. return CompleteObject();
  2832. }
  2833. }
  2834. bool IsAccess = isFormalAccess(AK);
  2835. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2836. // is not a constant expression (even if the object is non-volatile). We also
  2837. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2838. // semantics.
  2839. if (IsAccess && LValType.isVolatileQualified()) {
  2840. if (Info.getLangOpts().CPlusPlus)
  2841. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2842. << AK << LValType;
  2843. else
  2844. Info.FFDiag(E);
  2845. return CompleteObject();
  2846. }
  2847. // Compute value storage location and type of base object.
  2848. APValue *BaseVal = nullptr;
  2849. QualType BaseType = getType(LVal.Base);
  2850. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2851. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2852. // In C++11, constexpr, non-volatile variables initialized with constant
  2853. // expressions are constant expressions too. Inside constexpr functions,
  2854. // parameters are constant expressions even if they're non-const.
  2855. // In C++1y, objects local to a constant expression (those with a Frame) are
  2856. // both readable and writable inside constant expressions.
  2857. // In C, such things can also be folded, although they are not ICEs.
  2858. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2859. if (VD) {
  2860. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2861. VD = VDef;
  2862. }
  2863. if (!VD || VD->isInvalidDecl()) {
  2864. Info.FFDiag(E);
  2865. return CompleteObject();
  2866. }
  2867. // Unless we're looking at a local variable or argument in a constexpr call,
  2868. // the variable we're reading must be const.
  2869. if (!Frame) {
  2870. if (Info.getLangOpts().CPlusPlus14 &&
  2871. declaresSameEntity(
  2872. VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
  2873. // OK, we can read and modify an object if we're in the process of
  2874. // evaluating its initializer, because its lifetime began in this
  2875. // evaluation.
  2876. } else if (isModification(AK)) {
  2877. // All the remaining cases do not permit modification of the object.
  2878. Info.FFDiag(E, diag::note_constexpr_modify_global);
  2879. return CompleteObject();
  2880. } else if (VD->isConstexpr()) {
  2881. // OK, we can read this variable.
  2882. } else if (BaseType->isIntegralOrEnumerationType()) {
  2883. // In OpenCL if a variable is in constant address space it is a const
  2884. // value.
  2885. if (!(BaseType.isConstQualified() ||
  2886. (Info.getLangOpts().OpenCL &&
  2887. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  2888. if (!IsAccess)
  2889. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  2890. if (Info.getLangOpts().CPlusPlus) {
  2891. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2892. Info.Note(VD->getLocation(), diag::note_declared_at);
  2893. } else {
  2894. Info.FFDiag(E);
  2895. }
  2896. return CompleteObject();
  2897. }
  2898. } else if (!IsAccess) {
  2899. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  2900. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2901. // We support folding of const floating-point types, in order to make
  2902. // static const data members of such types (supported as an extension)
  2903. // more useful.
  2904. if (Info.getLangOpts().CPlusPlus11) {
  2905. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2906. Info.Note(VD->getLocation(), diag::note_declared_at);
  2907. } else {
  2908. Info.CCEDiag(E);
  2909. }
  2910. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  2911. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  2912. // Keep evaluating to see what we can do.
  2913. } else {
  2914. // FIXME: Allow folding of values of any literal type in all languages.
  2915. if (Info.checkingPotentialConstantExpression() &&
  2916. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  2917. // The definition of this variable could be constexpr. We can't
  2918. // access it right now, but may be able to in future.
  2919. } else if (Info.getLangOpts().CPlusPlus11) {
  2920. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2921. Info.Note(VD->getLocation(), diag::note_declared_at);
  2922. } else {
  2923. Info.FFDiag(E);
  2924. }
  2925. return CompleteObject();
  2926. }
  2927. }
  2928. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  2929. return CompleteObject();
  2930. } else {
  2931. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2932. if (!Frame) {
  2933. if (const MaterializeTemporaryExpr *MTE =
  2934. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  2935. assert(MTE->getStorageDuration() == SD_Static &&
  2936. "should have a frame for a non-global materialized temporary");
  2937. // Per C++1y [expr.const]p2:
  2938. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2939. // - a [...] glvalue of integral or enumeration type that refers to
  2940. // a non-volatile const object [...]
  2941. // [...]
  2942. // - a [...] glvalue of literal type that refers to a non-volatile
  2943. // object whose lifetime began within the evaluation of e.
  2944. //
  2945. // C++11 misses the 'began within the evaluation of e' check and
  2946. // instead allows all temporaries, including things like:
  2947. // int &&r = 1;
  2948. // int x = ++r;
  2949. // constexpr int k = r;
  2950. // Therefore we use the C++14 rules in C++11 too.
  2951. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2952. const ValueDecl *ED = MTE->getExtendingDecl();
  2953. if (!(BaseType.isConstQualified() &&
  2954. BaseType->isIntegralOrEnumerationType()) &&
  2955. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2956. if (!IsAccess)
  2957. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  2958. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2959. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2960. return CompleteObject();
  2961. }
  2962. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2963. assert(BaseVal && "got reference to unevaluated temporary");
  2964. } else {
  2965. if (!IsAccess)
  2966. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  2967. APValue Val;
  2968. LVal.moveInto(Val);
  2969. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  2970. << AK
  2971. << Val.getAsString(Info.Ctx,
  2972. Info.Ctx.getLValueReferenceType(LValType));
  2973. NoteLValueLocation(Info, LVal.Base);
  2974. return CompleteObject();
  2975. }
  2976. } else {
  2977. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  2978. assert(BaseVal && "missing value for temporary");
  2979. }
  2980. }
  2981. // In C++14, we can't safely access any mutable state when we might be
  2982. // evaluating after an unmodeled side effect.
  2983. //
  2984. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2985. // to be read here (but take care with 'mutable' fields).
  2986. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  2987. Info.EvalStatus.HasSideEffects) ||
  2988. (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
  2989. return CompleteObject();
  2990. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  2991. }
  2992. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2993. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2994. /// glvalue referred to by an entity of reference type.
  2995. ///
  2996. /// \param Info - Information about the ongoing evaluation.
  2997. /// \param Conv - The expression for which we are performing the conversion.
  2998. /// Used for diagnostics.
  2999. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3000. /// case of a non-class type).
  3001. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3002. /// \param RVal - The produced value will be placed here.
  3003. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  3004. QualType Type,
  3005. const LValue &LVal, APValue &RVal) {
  3006. if (LVal.Designator.Invalid)
  3007. return false;
  3008. // Check for special cases where there is no existing APValue to look at.
  3009. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3010. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3011. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3012. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3013. // initializer until now for such expressions. Such an expression can't be
  3014. // an ICE in C, so this only matters for fold.
  3015. if (Type.isVolatileQualified()) {
  3016. Info.FFDiag(Conv);
  3017. return false;
  3018. }
  3019. APValue Lit;
  3020. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3021. return false;
  3022. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3023. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  3024. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3025. // Special-case character extraction so we don't have to construct an
  3026. // APValue for the whole string.
  3027. assert(LVal.Designator.Entries.size() <= 1 &&
  3028. "Can only read characters from string literals");
  3029. if (LVal.Designator.Entries.empty()) {
  3030. // Fail for now for LValue to RValue conversion of an array.
  3031. // (This shouldn't show up in C/C++, but it could be triggered by a
  3032. // weird EvaluateAsRValue call from a tool.)
  3033. Info.FFDiag(Conv);
  3034. return false;
  3035. }
  3036. if (LVal.Designator.isOnePastTheEnd()) {
  3037. if (Info.getLangOpts().CPlusPlus11)
  3038. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
  3039. else
  3040. Info.FFDiag(Conv);
  3041. return false;
  3042. }
  3043. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3044. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3045. return true;
  3046. }
  3047. }
  3048. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  3049. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  3050. }
  3051. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3052. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3053. QualType LValType, APValue &Val) {
  3054. if (LVal.Designator.Invalid)
  3055. return false;
  3056. if (!Info.getLangOpts().CPlusPlus14) {
  3057. Info.FFDiag(E);
  3058. return false;
  3059. }
  3060. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3061. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3062. }
  3063. namespace {
  3064. struct CompoundAssignSubobjectHandler {
  3065. EvalInfo &Info;
  3066. const Expr *E;
  3067. QualType PromotedLHSType;
  3068. BinaryOperatorKind Opcode;
  3069. const APValue &RHS;
  3070. static const AccessKinds AccessKind = AK_Assign;
  3071. typedef bool result_type;
  3072. bool checkConst(QualType QT) {
  3073. // Assigning to a const object has undefined behavior.
  3074. if (QT.isConstQualified()) {
  3075. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3076. return false;
  3077. }
  3078. return true;
  3079. }
  3080. bool failed() { return false; }
  3081. bool found(APValue &Subobj, QualType SubobjType) {
  3082. switch (Subobj.getKind()) {
  3083. case APValue::Int:
  3084. return found(Subobj.getInt(), SubobjType);
  3085. case APValue::Float:
  3086. return found(Subobj.getFloat(), SubobjType);
  3087. case APValue::ComplexInt:
  3088. case APValue::ComplexFloat:
  3089. // FIXME: Implement complex compound assignment.
  3090. Info.FFDiag(E);
  3091. return false;
  3092. case APValue::LValue:
  3093. return foundPointer(Subobj, SubobjType);
  3094. default:
  3095. // FIXME: can this happen?
  3096. Info.FFDiag(E);
  3097. return false;
  3098. }
  3099. }
  3100. bool found(APSInt &Value, QualType SubobjType) {
  3101. if (!checkConst(SubobjType))
  3102. return false;
  3103. if (!SubobjType->isIntegerType()) {
  3104. // We don't support compound assignment on integer-cast-to-pointer
  3105. // values.
  3106. Info.FFDiag(E);
  3107. return false;
  3108. }
  3109. if (RHS.isInt()) {
  3110. APSInt LHS =
  3111. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3112. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3113. return false;
  3114. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3115. return true;
  3116. } else if (RHS.isFloat()) {
  3117. APFloat FValue(0.0);
  3118. return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
  3119. FValue) &&
  3120. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3121. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3122. Value);
  3123. }
  3124. Info.FFDiag(E);
  3125. return false;
  3126. }
  3127. bool found(APFloat &Value, QualType SubobjType) {
  3128. return checkConst(SubobjType) &&
  3129. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3130. Value) &&
  3131. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3132. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3133. }
  3134. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3135. if (!checkConst(SubobjType))
  3136. return false;
  3137. QualType PointeeType;
  3138. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3139. PointeeType = PT->getPointeeType();
  3140. if (PointeeType.isNull() || !RHS.isInt() ||
  3141. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3142. Info.FFDiag(E);
  3143. return false;
  3144. }
  3145. APSInt Offset = RHS.getInt();
  3146. if (Opcode == BO_Sub)
  3147. negateAsSigned(Offset);
  3148. LValue LVal;
  3149. LVal.setFrom(Info.Ctx, Subobj);
  3150. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3151. return false;
  3152. LVal.moveInto(Subobj);
  3153. return true;
  3154. }
  3155. };
  3156. } // end anonymous namespace
  3157. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3158. /// Perform a compound assignment of LVal <op>= RVal.
  3159. static bool handleCompoundAssignment(
  3160. EvalInfo &Info, const Expr *E,
  3161. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3162. BinaryOperatorKind Opcode, const APValue &RVal) {
  3163. if (LVal.Designator.Invalid)
  3164. return false;
  3165. if (!Info.getLangOpts().CPlusPlus14) {
  3166. Info.FFDiag(E);
  3167. return false;
  3168. }
  3169. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3170. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3171. RVal };
  3172. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3173. }
  3174. namespace {
  3175. struct IncDecSubobjectHandler {
  3176. EvalInfo &Info;
  3177. const UnaryOperator *E;
  3178. AccessKinds AccessKind;
  3179. APValue *Old;
  3180. typedef bool result_type;
  3181. bool checkConst(QualType QT) {
  3182. // Assigning to a const object has undefined behavior.
  3183. if (QT.isConstQualified()) {
  3184. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3185. return false;
  3186. }
  3187. return true;
  3188. }
  3189. bool failed() { return false; }
  3190. bool found(APValue &Subobj, QualType SubobjType) {
  3191. // Stash the old value. Also clear Old, so we don't clobber it later
  3192. // if we're post-incrementing a complex.
  3193. if (Old) {
  3194. *Old = Subobj;
  3195. Old = nullptr;
  3196. }
  3197. switch (Subobj.getKind()) {
  3198. case APValue::Int:
  3199. return found(Subobj.getInt(), SubobjType);
  3200. case APValue::Float:
  3201. return found(Subobj.getFloat(), SubobjType);
  3202. case APValue::ComplexInt:
  3203. return found(Subobj.getComplexIntReal(),
  3204. SubobjType->castAs<ComplexType>()->getElementType()
  3205. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3206. case APValue::ComplexFloat:
  3207. return found(Subobj.getComplexFloatReal(),
  3208. SubobjType->castAs<ComplexType>()->getElementType()
  3209. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3210. case APValue::LValue:
  3211. return foundPointer(Subobj, SubobjType);
  3212. default:
  3213. // FIXME: can this happen?
  3214. Info.FFDiag(E);
  3215. return false;
  3216. }
  3217. }
  3218. bool found(APSInt &Value, QualType SubobjType) {
  3219. if (!checkConst(SubobjType))
  3220. return false;
  3221. if (!SubobjType->isIntegerType()) {
  3222. // We don't support increment / decrement on integer-cast-to-pointer
  3223. // values.
  3224. Info.FFDiag(E);
  3225. return false;
  3226. }
  3227. if (Old) *Old = APValue(Value);
  3228. // bool arithmetic promotes to int, and the conversion back to bool
  3229. // doesn't reduce mod 2^n, so special-case it.
  3230. if (SubobjType->isBooleanType()) {
  3231. if (AccessKind == AK_Increment)
  3232. Value = 1;
  3233. else
  3234. Value = !Value;
  3235. return true;
  3236. }
  3237. bool WasNegative = Value.isNegative();
  3238. if (AccessKind == AK_Increment) {
  3239. ++Value;
  3240. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3241. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3242. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3243. }
  3244. } else {
  3245. --Value;
  3246. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3247. unsigned BitWidth = Value.getBitWidth();
  3248. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3249. ActualValue.setBit(BitWidth);
  3250. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3251. }
  3252. }
  3253. return true;
  3254. }
  3255. bool found(APFloat &Value, QualType SubobjType) {
  3256. if (!checkConst(SubobjType))
  3257. return false;
  3258. if (Old) *Old = APValue(Value);
  3259. APFloat One(Value.getSemantics(), 1);
  3260. if (AccessKind == AK_Increment)
  3261. Value.add(One, APFloat::rmNearestTiesToEven);
  3262. else
  3263. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3264. return true;
  3265. }
  3266. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3267. if (!checkConst(SubobjType))
  3268. return false;
  3269. QualType PointeeType;
  3270. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3271. PointeeType = PT->getPointeeType();
  3272. else {
  3273. Info.FFDiag(E);
  3274. return false;
  3275. }
  3276. LValue LVal;
  3277. LVal.setFrom(Info.Ctx, Subobj);
  3278. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3279. AccessKind == AK_Increment ? 1 : -1))
  3280. return false;
  3281. LVal.moveInto(Subobj);
  3282. return true;
  3283. }
  3284. };
  3285. } // end anonymous namespace
  3286. /// Perform an increment or decrement on LVal.
  3287. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3288. QualType LValType, bool IsIncrement, APValue *Old) {
  3289. if (LVal.Designator.Invalid)
  3290. return false;
  3291. if (!Info.getLangOpts().CPlusPlus14) {
  3292. Info.FFDiag(E);
  3293. return false;
  3294. }
  3295. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3296. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3297. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3298. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3299. }
  3300. /// Build an lvalue for the object argument of a member function call.
  3301. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3302. LValue &This) {
  3303. if (Object->getType()->isPointerType())
  3304. return EvaluatePointer(Object, This, Info);
  3305. if (Object->isGLValue())
  3306. return EvaluateLValue(Object, This, Info);
  3307. if (Object->getType()->isLiteralType(Info.Ctx))
  3308. return EvaluateTemporary(Object, This, Info);
  3309. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3310. return false;
  3311. }
  3312. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3313. /// lvalue referring to the result.
  3314. ///
  3315. /// \param Info - Information about the ongoing evaluation.
  3316. /// \param LV - An lvalue referring to the base of the member pointer.
  3317. /// \param RHS - The member pointer expression.
  3318. /// \param IncludeMember - Specifies whether the member itself is included in
  3319. /// the resulting LValue subobject designator. This is not possible when
  3320. /// creating a bound member function.
  3321. /// \return The field or method declaration to which the member pointer refers,
  3322. /// or 0 if evaluation fails.
  3323. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3324. QualType LVType,
  3325. LValue &LV,
  3326. const Expr *RHS,
  3327. bool IncludeMember = true) {
  3328. MemberPtr MemPtr;
  3329. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3330. return nullptr;
  3331. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3332. // member value, the behavior is undefined.
  3333. if (!MemPtr.getDecl()) {
  3334. // FIXME: Specific diagnostic.
  3335. Info.FFDiag(RHS);
  3336. return nullptr;
  3337. }
  3338. if (MemPtr.isDerivedMember()) {
  3339. // This is a member of some derived class. Truncate LV appropriately.
  3340. // The end of the derived-to-base path for the base object must match the
  3341. // derived-to-base path for the member pointer.
  3342. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3343. LV.Designator.Entries.size()) {
  3344. Info.FFDiag(RHS);
  3345. return nullptr;
  3346. }
  3347. unsigned PathLengthToMember =
  3348. LV.Designator.Entries.size() - MemPtr.Path.size();
  3349. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3350. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3351. LV.Designator.Entries[PathLengthToMember + I]);
  3352. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3353. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3354. Info.FFDiag(RHS);
  3355. return nullptr;
  3356. }
  3357. }
  3358. // Truncate the lvalue to the appropriate derived class.
  3359. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3360. PathLengthToMember))
  3361. return nullptr;
  3362. } else if (!MemPtr.Path.empty()) {
  3363. // Extend the LValue path with the member pointer's path.
  3364. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3365. MemPtr.Path.size() + IncludeMember);
  3366. // Walk down to the appropriate base class.
  3367. if (const PointerType *PT = LVType->getAs<PointerType>())
  3368. LVType = PT->getPointeeType();
  3369. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3370. assert(RD && "member pointer access on non-class-type expression");
  3371. // The first class in the path is that of the lvalue.
  3372. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3373. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3374. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3375. return nullptr;
  3376. RD = Base;
  3377. }
  3378. // Finally cast to the class containing the member.
  3379. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3380. MemPtr.getContainingRecord()))
  3381. return nullptr;
  3382. }
  3383. // Add the member. Note that we cannot build bound member functions here.
  3384. if (IncludeMember) {
  3385. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3386. if (!HandleLValueMember(Info, RHS, LV, FD))
  3387. return nullptr;
  3388. } else if (const IndirectFieldDecl *IFD =
  3389. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3390. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3391. return nullptr;
  3392. } else {
  3393. llvm_unreachable("can't construct reference to bound member function");
  3394. }
  3395. }
  3396. return MemPtr.getDecl();
  3397. }
  3398. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3399. const BinaryOperator *BO,
  3400. LValue &LV,
  3401. bool IncludeMember = true) {
  3402. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3403. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3404. if (Info.noteFailure()) {
  3405. MemberPtr MemPtr;
  3406. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3407. }
  3408. return nullptr;
  3409. }
  3410. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3411. BO->getRHS(), IncludeMember);
  3412. }
  3413. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3414. /// the provided lvalue, which currently refers to the base object.
  3415. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3416. LValue &Result) {
  3417. SubobjectDesignator &D = Result.Designator;
  3418. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3419. return false;
  3420. QualType TargetQT = E->getType();
  3421. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3422. TargetQT = PT->getPointeeType();
  3423. // Check this cast lands within the final derived-to-base subobject path.
  3424. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3425. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3426. << D.MostDerivedType << TargetQT;
  3427. return false;
  3428. }
  3429. // Check the type of the final cast. We don't need to check the path,
  3430. // since a cast can only be formed if the path is unique.
  3431. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3432. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3433. const CXXRecordDecl *FinalType;
  3434. if (NewEntriesSize == D.MostDerivedPathLength)
  3435. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3436. else
  3437. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3438. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3439. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3440. << D.MostDerivedType << TargetQT;
  3441. return false;
  3442. }
  3443. // Truncate the lvalue to the appropriate derived class.
  3444. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3445. }
  3446. namespace {
  3447. enum EvalStmtResult {
  3448. /// Evaluation failed.
  3449. ESR_Failed,
  3450. /// Hit a 'return' statement.
  3451. ESR_Returned,
  3452. /// Evaluation succeeded.
  3453. ESR_Succeeded,
  3454. /// Hit a 'continue' statement.
  3455. ESR_Continue,
  3456. /// Hit a 'break' statement.
  3457. ESR_Break,
  3458. /// Still scanning for 'case' or 'default' statement.
  3459. ESR_CaseNotFound
  3460. };
  3461. }
  3462. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3463. // We don't need to evaluate the initializer for a static local.
  3464. if (!VD->hasLocalStorage())
  3465. return true;
  3466. LValue Result;
  3467. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3468. const Expr *InitE = VD->getInit();
  3469. if (!InitE) {
  3470. Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
  3471. << false << VD->getType();
  3472. Val = APValue();
  3473. return false;
  3474. }
  3475. if (InitE->isValueDependent())
  3476. return false;
  3477. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3478. // Wipe out any partially-computed value, to allow tracking that this
  3479. // evaluation failed.
  3480. Val = APValue();
  3481. return false;
  3482. }
  3483. return true;
  3484. }
  3485. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3486. bool OK = true;
  3487. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3488. OK &= EvaluateVarDecl(Info, VD);
  3489. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3490. for (auto *BD : DD->bindings())
  3491. if (auto *VD = BD->getHoldingVar())
  3492. OK &= EvaluateDecl(Info, VD);
  3493. return OK;
  3494. }
  3495. /// Evaluate a condition (either a variable declaration or an expression).
  3496. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3497. const Expr *Cond, bool &Result) {
  3498. FullExpressionRAII Scope(Info);
  3499. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3500. return false;
  3501. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3502. }
  3503. namespace {
  3504. /// A location where the result (returned value) of evaluating a
  3505. /// statement should be stored.
  3506. struct StmtResult {
  3507. /// The APValue that should be filled in with the returned value.
  3508. APValue &Value;
  3509. /// The location containing the result, if any (used to support RVO).
  3510. const LValue *Slot;
  3511. };
  3512. struct TempVersionRAII {
  3513. CallStackFrame &Frame;
  3514. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3515. Frame.pushTempVersion();
  3516. }
  3517. ~TempVersionRAII() {
  3518. Frame.popTempVersion();
  3519. }
  3520. };
  3521. }
  3522. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3523. const Stmt *S,
  3524. const SwitchCase *SC = nullptr);
  3525. /// Evaluate the body of a loop, and translate the result as appropriate.
  3526. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3527. const Stmt *Body,
  3528. const SwitchCase *Case = nullptr) {
  3529. BlockScopeRAII Scope(Info);
  3530. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3531. case ESR_Break:
  3532. return ESR_Succeeded;
  3533. case ESR_Succeeded:
  3534. case ESR_Continue:
  3535. return ESR_Continue;
  3536. case ESR_Failed:
  3537. case ESR_Returned:
  3538. case ESR_CaseNotFound:
  3539. return ESR;
  3540. }
  3541. llvm_unreachable("Invalid EvalStmtResult!");
  3542. }
  3543. /// Evaluate a switch statement.
  3544. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3545. const SwitchStmt *SS) {
  3546. BlockScopeRAII Scope(Info);
  3547. // Evaluate the switch condition.
  3548. APSInt Value;
  3549. {
  3550. FullExpressionRAII Scope(Info);
  3551. if (const Stmt *Init = SS->getInit()) {
  3552. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3553. if (ESR != ESR_Succeeded)
  3554. return ESR;
  3555. }
  3556. if (SS->getConditionVariable() &&
  3557. !EvaluateDecl(Info, SS->getConditionVariable()))
  3558. return ESR_Failed;
  3559. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3560. return ESR_Failed;
  3561. }
  3562. // Find the switch case corresponding to the value of the condition.
  3563. // FIXME: Cache this lookup.
  3564. const SwitchCase *Found = nullptr;
  3565. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3566. SC = SC->getNextSwitchCase()) {
  3567. if (isa<DefaultStmt>(SC)) {
  3568. Found = SC;
  3569. continue;
  3570. }
  3571. const CaseStmt *CS = cast<CaseStmt>(SC);
  3572. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3573. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3574. : LHS;
  3575. if (LHS <= Value && Value <= RHS) {
  3576. Found = SC;
  3577. break;
  3578. }
  3579. }
  3580. if (!Found)
  3581. return ESR_Succeeded;
  3582. // Search the switch body for the switch case and evaluate it from there.
  3583. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3584. case ESR_Break:
  3585. return ESR_Succeeded;
  3586. case ESR_Succeeded:
  3587. case ESR_Continue:
  3588. case ESR_Failed:
  3589. case ESR_Returned:
  3590. return ESR;
  3591. case ESR_CaseNotFound:
  3592. // This can only happen if the switch case is nested within a statement
  3593. // expression. We have no intention of supporting that.
  3594. Info.FFDiag(Found->getBeginLoc(),
  3595. diag::note_constexpr_stmt_expr_unsupported);
  3596. return ESR_Failed;
  3597. }
  3598. llvm_unreachable("Invalid EvalStmtResult!");
  3599. }
  3600. // Evaluate a statement.
  3601. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3602. const Stmt *S, const SwitchCase *Case) {
  3603. if (!Info.nextStep(S))
  3604. return ESR_Failed;
  3605. // If we're hunting down a 'case' or 'default' label, recurse through
  3606. // substatements until we hit the label.
  3607. if (Case) {
  3608. // FIXME: We don't start the lifetime of objects whose initialization we
  3609. // jump over. However, such objects must be of class type with a trivial
  3610. // default constructor that initialize all subobjects, so must be empty,
  3611. // so this almost never matters.
  3612. switch (S->getStmtClass()) {
  3613. case Stmt::CompoundStmtClass:
  3614. // FIXME: Precompute which substatement of a compound statement we
  3615. // would jump to, and go straight there rather than performing a
  3616. // linear scan each time.
  3617. case Stmt::LabelStmtClass:
  3618. case Stmt::AttributedStmtClass:
  3619. case Stmt::DoStmtClass:
  3620. break;
  3621. case Stmt::CaseStmtClass:
  3622. case Stmt::DefaultStmtClass:
  3623. if (Case == S)
  3624. Case = nullptr;
  3625. break;
  3626. case Stmt::IfStmtClass: {
  3627. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3628. // straight there rather than scanning both sides.
  3629. const IfStmt *IS = cast<IfStmt>(S);
  3630. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3631. // preceded by our switch label.
  3632. BlockScopeRAII Scope(Info);
  3633. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3634. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3635. return ESR;
  3636. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3637. }
  3638. case Stmt::WhileStmtClass: {
  3639. EvalStmtResult ESR =
  3640. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3641. if (ESR != ESR_Continue)
  3642. return ESR;
  3643. break;
  3644. }
  3645. case Stmt::ForStmtClass: {
  3646. const ForStmt *FS = cast<ForStmt>(S);
  3647. EvalStmtResult ESR =
  3648. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3649. if (ESR != ESR_Continue)
  3650. return ESR;
  3651. if (FS->getInc()) {
  3652. FullExpressionRAII IncScope(Info);
  3653. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3654. return ESR_Failed;
  3655. }
  3656. break;
  3657. }
  3658. case Stmt::DeclStmtClass:
  3659. // FIXME: If the variable has initialization that can't be jumped over,
  3660. // bail out of any immediately-surrounding compound-statement too.
  3661. default:
  3662. return ESR_CaseNotFound;
  3663. }
  3664. }
  3665. switch (S->getStmtClass()) {
  3666. default:
  3667. if (const Expr *E = dyn_cast<Expr>(S)) {
  3668. // Don't bother evaluating beyond an expression-statement which couldn't
  3669. // be evaluated.
  3670. FullExpressionRAII Scope(Info);
  3671. if (!EvaluateIgnoredValue(Info, E))
  3672. return ESR_Failed;
  3673. return ESR_Succeeded;
  3674. }
  3675. Info.FFDiag(S->getBeginLoc());
  3676. return ESR_Failed;
  3677. case Stmt::NullStmtClass:
  3678. return ESR_Succeeded;
  3679. case Stmt::DeclStmtClass: {
  3680. const DeclStmt *DS = cast<DeclStmt>(S);
  3681. for (const auto *DclIt : DS->decls()) {
  3682. // Each declaration initialization is its own full-expression.
  3683. // FIXME: This isn't quite right; if we're performing aggregate
  3684. // initialization, each braced subexpression is its own full-expression.
  3685. FullExpressionRAII Scope(Info);
  3686. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3687. return ESR_Failed;
  3688. }
  3689. return ESR_Succeeded;
  3690. }
  3691. case Stmt::ReturnStmtClass: {
  3692. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3693. FullExpressionRAII Scope(Info);
  3694. if (RetExpr &&
  3695. !(Result.Slot
  3696. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3697. : Evaluate(Result.Value, Info, RetExpr)))
  3698. return ESR_Failed;
  3699. return ESR_Returned;
  3700. }
  3701. case Stmt::CompoundStmtClass: {
  3702. BlockScopeRAII Scope(Info);
  3703. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3704. for (const auto *BI : CS->body()) {
  3705. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3706. if (ESR == ESR_Succeeded)
  3707. Case = nullptr;
  3708. else if (ESR != ESR_CaseNotFound)
  3709. return ESR;
  3710. }
  3711. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3712. }
  3713. case Stmt::IfStmtClass: {
  3714. const IfStmt *IS = cast<IfStmt>(S);
  3715. // Evaluate the condition, as either a var decl or as an expression.
  3716. BlockScopeRAII Scope(Info);
  3717. if (const Stmt *Init = IS->getInit()) {
  3718. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3719. if (ESR != ESR_Succeeded)
  3720. return ESR;
  3721. }
  3722. bool Cond;
  3723. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3724. return ESR_Failed;
  3725. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3726. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3727. if (ESR != ESR_Succeeded)
  3728. return ESR;
  3729. }
  3730. return ESR_Succeeded;
  3731. }
  3732. case Stmt::WhileStmtClass: {
  3733. const WhileStmt *WS = cast<WhileStmt>(S);
  3734. while (true) {
  3735. BlockScopeRAII Scope(Info);
  3736. bool Continue;
  3737. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3738. Continue))
  3739. return ESR_Failed;
  3740. if (!Continue)
  3741. break;
  3742. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3743. if (ESR != ESR_Continue)
  3744. return ESR;
  3745. }
  3746. return ESR_Succeeded;
  3747. }
  3748. case Stmt::DoStmtClass: {
  3749. const DoStmt *DS = cast<DoStmt>(S);
  3750. bool Continue;
  3751. do {
  3752. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3753. if (ESR != ESR_Continue)
  3754. return ESR;
  3755. Case = nullptr;
  3756. FullExpressionRAII CondScope(Info);
  3757. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3758. return ESR_Failed;
  3759. } while (Continue);
  3760. return ESR_Succeeded;
  3761. }
  3762. case Stmt::ForStmtClass: {
  3763. const ForStmt *FS = cast<ForStmt>(S);
  3764. BlockScopeRAII Scope(Info);
  3765. if (FS->getInit()) {
  3766. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3767. if (ESR != ESR_Succeeded)
  3768. return ESR;
  3769. }
  3770. while (true) {
  3771. BlockScopeRAII Scope(Info);
  3772. bool Continue = true;
  3773. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3774. FS->getCond(), Continue))
  3775. return ESR_Failed;
  3776. if (!Continue)
  3777. break;
  3778. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3779. if (ESR != ESR_Continue)
  3780. return ESR;
  3781. if (FS->getInc()) {
  3782. FullExpressionRAII IncScope(Info);
  3783. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3784. return ESR_Failed;
  3785. }
  3786. }
  3787. return ESR_Succeeded;
  3788. }
  3789. case Stmt::CXXForRangeStmtClass: {
  3790. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3791. BlockScopeRAII Scope(Info);
  3792. // Evaluate the init-statement if present.
  3793. if (FS->getInit()) {
  3794. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3795. if (ESR != ESR_Succeeded)
  3796. return ESR;
  3797. }
  3798. // Initialize the __range variable.
  3799. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3800. if (ESR != ESR_Succeeded)
  3801. return ESR;
  3802. // Create the __begin and __end iterators.
  3803. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3804. if (ESR != ESR_Succeeded)
  3805. return ESR;
  3806. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3807. if (ESR != ESR_Succeeded)
  3808. return ESR;
  3809. while (true) {
  3810. // Condition: __begin != __end.
  3811. {
  3812. bool Continue = true;
  3813. FullExpressionRAII CondExpr(Info);
  3814. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3815. return ESR_Failed;
  3816. if (!Continue)
  3817. break;
  3818. }
  3819. // User's variable declaration, initialized by *__begin.
  3820. BlockScopeRAII InnerScope(Info);
  3821. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3822. if (ESR != ESR_Succeeded)
  3823. return ESR;
  3824. // Loop body.
  3825. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3826. if (ESR != ESR_Continue)
  3827. return ESR;
  3828. // Increment: ++__begin
  3829. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3830. return ESR_Failed;
  3831. }
  3832. return ESR_Succeeded;
  3833. }
  3834. case Stmt::SwitchStmtClass:
  3835. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3836. case Stmt::ContinueStmtClass:
  3837. return ESR_Continue;
  3838. case Stmt::BreakStmtClass:
  3839. return ESR_Break;
  3840. case Stmt::LabelStmtClass:
  3841. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3842. case Stmt::AttributedStmtClass:
  3843. // As a general principle, C++11 attributes can be ignored without
  3844. // any semantic impact.
  3845. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3846. Case);
  3847. case Stmt::CaseStmtClass:
  3848. case Stmt::DefaultStmtClass:
  3849. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3850. case Stmt::CXXTryStmtClass:
  3851. // Evaluate try blocks by evaluating all sub statements.
  3852. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  3853. }
  3854. }
  3855. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3856. /// default constructor. If so, we'll fold it whether or not it's marked as
  3857. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3858. /// so we need special handling.
  3859. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3860. const CXXConstructorDecl *CD,
  3861. bool IsValueInitialization) {
  3862. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3863. return false;
  3864. // Value-initialization does not call a trivial default constructor, so such a
  3865. // call is a core constant expression whether or not the constructor is
  3866. // constexpr.
  3867. if (!CD->isConstexpr() && !IsValueInitialization) {
  3868. if (Info.getLangOpts().CPlusPlus11) {
  3869. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3870. // we should be much more explicit about why it's not constexpr.
  3871. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3872. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3873. Info.Note(CD->getLocation(), diag::note_declared_at);
  3874. } else {
  3875. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3876. }
  3877. }
  3878. return true;
  3879. }
  3880. /// CheckConstexprFunction - Check that a function can be called in a constant
  3881. /// expression.
  3882. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3883. const FunctionDecl *Declaration,
  3884. const FunctionDecl *Definition,
  3885. const Stmt *Body) {
  3886. // Potential constant expressions can contain calls to declared, but not yet
  3887. // defined, constexpr functions.
  3888. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3889. Declaration->isConstexpr())
  3890. return false;
  3891. // Bail out if the function declaration itself is invalid. We will
  3892. // have produced a relevant diagnostic while parsing it, so just
  3893. // note the problematic sub-expression.
  3894. if (Declaration->isInvalidDecl()) {
  3895. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3896. return false;
  3897. }
  3898. // DR1872: An instantiated virtual constexpr function can't be called in a
  3899. // constant expression (prior to C++20). We can still constant-fold such a
  3900. // call.
  3901. if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
  3902. cast<CXXMethodDecl>(Declaration)->isVirtual())
  3903. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  3904. if (Definition && Definition->isInvalidDecl()) {
  3905. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3906. return false;
  3907. }
  3908. // Can we evaluate this function call?
  3909. if (Definition && Definition->isConstexpr() && Body)
  3910. return true;
  3911. if (Info.getLangOpts().CPlusPlus11) {
  3912. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3913. // If this function is not constexpr because it is an inherited
  3914. // non-constexpr constructor, diagnose that directly.
  3915. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  3916. if (CD && CD->isInheritingConstructor()) {
  3917. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  3918. if (!Inherited->isConstexpr())
  3919. DiagDecl = CD = Inherited;
  3920. }
  3921. // FIXME: If DiagDecl is an implicitly-declared special member function
  3922. // or an inheriting constructor, we should be much more explicit about why
  3923. // it's not constexpr.
  3924. if (CD && CD->isInheritingConstructor())
  3925. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  3926. << CD->getInheritedConstructor().getConstructor()->getParent();
  3927. else
  3928. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3929. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  3930. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3931. } else {
  3932. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3933. }
  3934. return false;
  3935. }
  3936. namespace {
  3937. struct CheckDynamicTypeHandler {
  3938. AccessKinds AccessKind;
  3939. typedef bool result_type;
  3940. bool failed() { return false; }
  3941. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  3942. bool found(APSInt &Value, QualType SubobjType) { return true; }
  3943. bool found(APFloat &Value, QualType SubobjType) { return true; }
  3944. };
  3945. } // end anonymous namespace
  3946. /// Check that we can access the notional vptr of an object / determine its
  3947. /// dynamic type.
  3948. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  3949. AccessKinds AK, bool Polymorphic) {
  3950. if (This.Designator.Invalid)
  3951. return false;
  3952. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  3953. if (!Obj)
  3954. return false;
  3955. if (!Obj.Value) {
  3956. // The object is not usable in constant expressions, so we can't inspect
  3957. // its value to see if it's in-lifetime or what the active union members
  3958. // are. We can still check for a one-past-the-end lvalue.
  3959. if (This.Designator.isOnePastTheEnd() ||
  3960. This.Designator.isMostDerivedAnUnsizedArray()) {
  3961. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  3962. ? diag::note_constexpr_access_past_end
  3963. : diag::note_constexpr_access_unsized_array)
  3964. << AK;
  3965. return false;
  3966. } else if (Polymorphic) {
  3967. // Conservatively refuse to perform a polymorphic operation if we would
  3968. // not be able to read a notional 'vptr' value.
  3969. APValue Val;
  3970. This.moveInto(Val);
  3971. QualType StarThisType =
  3972. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  3973. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  3974. << AK << Val.getAsString(Info.Ctx, StarThisType);
  3975. return false;
  3976. }
  3977. return true;
  3978. }
  3979. CheckDynamicTypeHandler Handler{AK};
  3980. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  3981. }
  3982. /// Check that the pointee of the 'this' pointer in a member function call is
  3983. /// either within its lifetime or in its period of construction or destruction.
  3984. static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  3985. const LValue &This) {
  3986. return checkDynamicType(Info, E, This, AK_MemberCall, false);
  3987. }
  3988. struct DynamicType {
  3989. /// The dynamic class type of the object.
  3990. const CXXRecordDecl *Type;
  3991. /// The corresponding path length in the lvalue.
  3992. unsigned PathLength;
  3993. };
  3994. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  3995. unsigned PathLength) {
  3996. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  3997. Designator.Entries.size() && "invalid path length");
  3998. return (PathLength == Designator.MostDerivedPathLength)
  3999. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4000. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4001. }
  4002. /// Determine the dynamic type of an object.
  4003. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4004. LValue &This, AccessKinds AK) {
  4005. // If we don't have an lvalue denoting an object of class type, there is no
  4006. // meaningful dynamic type. (We consider objects of non-class type to have no
  4007. // dynamic type.)
  4008. if (!checkDynamicType(Info, E, This, AK, true))
  4009. return None;
  4010. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4011. // shouldn't happen other than in constant-folding situations, since literal
  4012. // types can't have virtual bases.
  4013. //
  4014. // Note that consumers of DynamicType assume that the type has no virtual
  4015. // bases, and will need modifications if this restriction is relaxed.
  4016. const CXXRecordDecl *Class =
  4017. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  4018. if (!Class || Class->getNumVBases()) {
  4019. Info.FFDiag(E);
  4020. return None;
  4021. }
  4022. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  4023. // binary search here instead. But the overwhelmingly common case is that
  4024. // we're not in the middle of a constructor, so it probably doesn't matter
  4025. // in practice.
  4026. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  4027. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  4028. PathLength <= Path.size(); ++PathLength) {
  4029. switch (Info.isEvaluatingConstructor(This.getLValueBase(),
  4030. Path.slice(0, PathLength))) {
  4031. case ConstructionPhase::Bases:
  4032. // We're constructing a base class. This is not the dynamic type.
  4033. break;
  4034. case ConstructionPhase::None:
  4035. case ConstructionPhase::AfterBases:
  4036. // We've finished constructing the base classes, so this is the dynamic
  4037. // type.
  4038. return DynamicType{getBaseClassType(This.Designator, PathLength),
  4039. PathLength};
  4040. }
  4041. }
  4042. // CWG issue 1517: we're constructing a base class of the object described by
  4043. // 'This', so that object has not yet begun its period of construction and
  4044. // any polymorphic operation on it results in undefined behavior.
  4045. Info.FFDiag(E);
  4046. return None;
  4047. }
  4048. /// Perform virtual dispatch.
  4049. static const CXXMethodDecl *HandleVirtualDispatch(
  4050. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  4051. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  4052. Optional<DynamicType> DynType =
  4053. ComputeDynamicType(Info, E, This, AK_MemberCall);
  4054. if (!DynType)
  4055. return nullptr;
  4056. // Find the final overrider. It must be declared in one of the classes on the
  4057. // path from the dynamic type to the static type.
  4058. // FIXME: If we ever allow literal types to have virtual base classes, that
  4059. // won't be true.
  4060. const CXXMethodDecl *Callee = Found;
  4061. unsigned PathLength = DynType->PathLength;
  4062. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  4063. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  4064. const CXXMethodDecl *Overrider =
  4065. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  4066. if (Overrider) {
  4067. Callee = Overrider;
  4068. break;
  4069. }
  4070. }
  4071. // C++2a [class.abstract]p6:
  4072. // the effect of making a virtual call to a pure virtual function [...] is
  4073. // undefined
  4074. if (Callee->isPure()) {
  4075. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  4076. Info.Note(Callee->getLocation(), diag::note_declared_at);
  4077. return nullptr;
  4078. }
  4079. // If necessary, walk the rest of the path to determine the sequence of
  4080. // covariant adjustment steps to apply.
  4081. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  4082. Found->getReturnType())) {
  4083. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  4084. for (unsigned CovariantPathLength = PathLength + 1;
  4085. CovariantPathLength != This.Designator.Entries.size();
  4086. ++CovariantPathLength) {
  4087. const CXXRecordDecl *NextClass =
  4088. getBaseClassType(This.Designator, CovariantPathLength);
  4089. const CXXMethodDecl *Next =
  4090. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  4091. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  4092. Next->getReturnType(), CovariantAdjustmentPath.back()))
  4093. CovariantAdjustmentPath.push_back(Next->getReturnType());
  4094. }
  4095. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  4096. CovariantAdjustmentPath.back()))
  4097. CovariantAdjustmentPath.push_back(Found->getReturnType());
  4098. }
  4099. // Perform 'this' adjustment.
  4100. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  4101. return nullptr;
  4102. return Callee;
  4103. }
  4104. /// Perform the adjustment from a value returned by a virtual function to
  4105. /// a value of the statically expected type, which may be a pointer or
  4106. /// reference to a base class of the returned type.
  4107. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  4108. APValue &Result,
  4109. ArrayRef<QualType> Path) {
  4110. assert(Result.isLValue() &&
  4111. "unexpected kind of APValue for covariant return");
  4112. if (Result.isNullPointer())
  4113. return true;
  4114. LValue LVal;
  4115. LVal.setFrom(Info.Ctx, Result);
  4116. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  4117. for (unsigned I = 1; I != Path.size(); ++I) {
  4118. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  4119. assert(OldClass && NewClass && "unexpected kind of covariant return");
  4120. if (OldClass != NewClass &&
  4121. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  4122. return false;
  4123. OldClass = NewClass;
  4124. }
  4125. LVal.moveInto(Result);
  4126. return true;
  4127. }
  4128. /// Determine whether \p Base, which is known to be a direct base class of
  4129. /// \p Derived, is a public base class.
  4130. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  4131. const CXXRecordDecl *Base) {
  4132. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  4133. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  4134. if (BaseClass && declaresSameEntity(BaseClass, Base))
  4135. return BaseSpec.getAccessSpecifier() == AS_public;
  4136. }
  4137. llvm_unreachable("Base is not a direct base of Derived");
  4138. }
  4139. /// Apply the given dynamic cast operation on the provided lvalue.
  4140. ///
  4141. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  4142. /// to find a suitable target subobject.
  4143. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  4144. LValue &Ptr) {
  4145. // We can't do anything with a non-symbolic pointer value.
  4146. SubobjectDesignator &D = Ptr.Designator;
  4147. if (D.Invalid)
  4148. return false;
  4149. // C++ [expr.dynamic.cast]p6:
  4150. // If v is a null pointer value, the result is a null pointer value.
  4151. if (Ptr.isNullPointer() && !E->isGLValue())
  4152. return true;
  4153. // For all the other cases, we need the pointer to point to an object within
  4154. // its lifetime / period of construction / destruction, and we need to know
  4155. // its dynamic type.
  4156. Optional<DynamicType> DynType =
  4157. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  4158. if (!DynType)
  4159. return false;
  4160. // C++ [expr.dynamic.cast]p7:
  4161. // If T is "pointer to cv void", then the result is a pointer to the most
  4162. // derived object
  4163. if (E->getType()->isVoidPointerType())
  4164. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  4165. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  4166. assert(C && "dynamic_cast target is not void pointer nor class");
  4167. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  4168. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  4169. // C++ [expr.dynamic.cast]p9:
  4170. if (!E->isGLValue()) {
  4171. // The value of a failed cast to pointer type is the null pointer value
  4172. // of the required result type.
  4173. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  4174. Ptr.setNull(E->getType(), TargetVal);
  4175. return true;
  4176. }
  4177. // A failed cast to reference type throws [...] std::bad_cast.
  4178. unsigned DiagKind;
  4179. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  4180. DynType->Type->isDerivedFrom(C)))
  4181. DiagKind = 0;
  4182. else if (!Paths || Paths->begin() == Paths->end())
  4183. DiagKind = 1;
  4184. else if (Paths->isAmbiguous(CQT))
  4185. DiagKind = 2;
  4186. else {
  4187. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  4188. DiagKind = 3;
  4189. }
  4190. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  4191. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  4192. << Info.Ctx.getRecordType(DynType->Type)
  4193. << E->getType().getUnqualifiedType();
  4194. return false;
  4195. };
  4196. // Runtime check, phase 1:
  4197. // Walk from the base subobject towards the derived object looking for the
  4198. // target type.
  4199. for (int PathLength = Ptr.Designator.Entries.size();
  4200. PathLength >= (int)DynType->PathLength; --PathLength) {
  4201. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  4202. if (declaresSameEntity(Class, C))
  4203. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  4204. // We can only walk across public inheritance edges.
  4205. if (PathLength > (int)DynType->PathLength &&
  4206. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  4207. Class))
  4208. return RuntimeCheckFailed(nullptr);
  4209. }
  4210. // Runtime check, phase 2:
  4211. // Search the dynamic type for an unambiguous public base of type C.
  4212. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  4213. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  4214. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  4215. Paths.front().Access == AS_public) {
  4216. // Downcast to the dynamic type...
  4217. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  4218. return false;
  4219. // ... then upcast to the chosen base class subobject.
  4220. for (CXXBasePathElement &Elem : Paths.front())
  4221. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  4222. return false;
  4223. return true;
  4224. }
  4225. // Otherwise, the runtime check fails.
  4226. return RuntimeCheckFailed(&Paths);
  4227. }
  4228. namespace {
  4229. struct StartLifetimeOfUnionMemberHandler {
  4230. const FieldDecl *Field;
  4231. static const AccessKinds AccessKind = AK_Assign;
  4232. APValue getDefaultInitValue(QualType SubobjType) {
  4233. if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
  4234. if (RD->isUnion())
  4235. return APValue((const FieldDecl*)nullptr);
  4236. APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
  4237. std::distance(RD->field_begin(), RD->field_end()));
  4238. unsigned Index = 0;
  4239. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  4240. End = RD->bases_end(); I != End; ++I, ++Index)
  4241. Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
  4242. for (const auto *I : RD->fields()) {
  4243. if (I->isUnnamedBitfield())
  4244. continue;
  4245. Struct.getStructField(I->getFieldIndex()) =
  4246. getDefaultInitValue(I->getType());
  4247. }
  4248. return Struct;
  4249. }
  4250. if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
  4251. SubobjType->getAsArrayTypeUnsafe())) {
  4252. APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  4253. if (Array.hasArrayFiller())
  4254. Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
  4255. return Array;
  4256. }
  4257. return APValue::IndeterminateValue();
  4258. }
  4259. typedef bool result_type;
  4260. bool failed() { return false; }
  4261. bool found(APValue &Subobj, QualType SubobjType) {
  4262. // We are supposed to perform no initialization but begin the lifetime of
  4263. // the object. We interpret that as meaning to do what default
  4264. // initialization of the object would do if all constructors involved were
  4265. // trivial:
  4266. // * All base, non-variant member, and array element subobjects' lifetimes
  4267. // begin
  4268. // * No variant members' lifetimes begin
  4269. // * All scalar subobjects whose lifetimes begin have indeterminate values
  4270. assert(SubobjType->isUnionType());
  4271. if (!declaresSameEntity(Subobj.getUnionField(), Field))
  4272. Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
  4273. return true;
  4274. }
  4275. bool found(APSInt &Value, QualType SubobjType) {
  4276. llvm_unreachable("wrong value kind for union object");
  4277. }
  4278. bool found(APFloat &Value, QualType SubobjType) {
  4279. llvm_unreachable("wrong value kind for union object");
  4280. }
  4281. };
  4282. } // end anonymous namespace
  4283. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  4284. /// Handle a builtin simple-assignment or a call to a trivial assignment
  4285. /// operator whose left-hand side might involve a union member access. If it
  4286. /// does, implicitly start the lifetime of any accessed union elements per
  4287. /// C++20 [class.union]5.
  4288. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  4289. const LValue &LHS) {
  4290. if (LHS.InvalidBase || LHS.Designator.Invalid)
  4291. return false;
  4292. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  4293. // C++ [class.union]p5:
  4294. // define the set S(E) of subexpressions of E as follows:
  4295. unsigned PathLength = LHS.Designator.Entries.size();
  4296. for (const Expr *E = LHSExpr; E != nullptr;) {
  4297. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  4298. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  4299. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  4300. if (!FD)
  4301. break;
  4302. // ... and also contains A.B if B names a union member
  4303. if (FD->getParent()->isUnion())
  4304. UnionPathLengths.push_back({PathLength - 1, FD});
  4305. E = ME->getBase();
  4306. --PathLength;
  4307. assert(declaresSameEntity(FD,
  4308. LHS.Designator.Entries[PathLength]
  4309. .getAsBaseOrMember().getPointer()));
  4310. // -- If E is of the form A[B] and is interpreted as a built-in array
  4311. // subscripting operator, S(E) is [S(the array operand, if any)].
  4312. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  4313. // Step over an ArrayToPointerDecay implicit cast.
  4314. auto *Base = ASE->getBase()->IgnoreImplicit();
  4315. if (!Base->getType()->isArrayType())
  4316. break;
  4317. E = Base;
  4318. --PathLength;
  4319. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4320. // Step over a derived-to-base conversion.
  4321. E = ICE->getSubExpr();
  4322. if (ICE->getCastKind() == CK_NoOp)
  4323. continue;
  4324. if (ICE->getCastKind() != CK_DerivedToBase &&
  4325. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  4326. break;
  4327. // Walk path backwards as we walk up from the base to the derived class.
  4328. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  4329. --PathLength;
  4330. (void)Elt;
  4331. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  4332. LHS.Designator.Entries[PathLength]
  4333. .getAsBaseOrMember().getPointer()));
  4334. }
  4335. // -- Otherwise, S(E) is empty.
  4336. } else {
  4337. break;
  4338. }
  4339. }
  4340. // Common case: no unions' lifetimes are started.
  4341. if (UnionPathLengths.empty())
  4342. return true;
  4343. // if modification of X [would access an inactive union member], an object
  4344. // of the type of X is implicitly created
  4345. CompleteObject Obj =
  4346. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  4347. if (!Obj)
  4348. return false;
  4349. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  4350. llvm::reverse(UnionPathLengths)) {
  4351. // Form a designator for the union object.
  4352. SubobjectDesignator D = LHS.Designator;
  4353. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  4354. StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
  4355. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  4356. return false;
  4357. }
  4358. return true;
  4359. }
  4360. /// Determine if a class has any fields that might need to be copied by a
  4361. /// trivial copy or move operation.
  4362. static bool hasFields(const CXXRecordDecl *RD) {
  4363. if (!RD || RD->isEmpty())
  4364. return false;
  4365. for (auto *FD : RD->fields()) {
  4366. if (FD->isUnnamedBitfield())
  4367. continue;
  4368. return true;
  4369. }
  4370. for (auto &Base : RD->bases())
  4371. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  4372. return true;
  4373. return false;
  4374. }
  4375. namespace {
  4376. typedef SmallVector<APValue, 8> ArgVector;
  4377. }
  4378. /// EvaluateArgs - Evaluate the arguments to a function call.
  4379. static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
  4380. EvalInfo &Info, const FunctionDecl *Callee) {
  4381. bool Success = true;
  4382. llvm::SmallBitVector ForbiddenNullArgs;
  4383. if (Callee->hasAttr<NonNullAttr>()) {
  4384. ForbiddenNullArgs.resize(Args.size());
  4385. for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
  4386. if (!Attr->args_size()) {
  4387. ForbiddenNullArgs.set();
  4388. break;
  4389. } else
  4390. for (auto Idx : Attr->args()) {
  4391. unsigned ASTIdx = Idx.getASTIndex();
  4392. if (ASTIdx >= Args.size())
  4393. continue;
  4394. ForbiddenNullArgs[ASTIdx] = 1;
  4395. }
  4396. }
  4397. }
  4398. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  4399. I != E; ++I) {
  4400. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  4401. // If we're checking for a potential constant expression, evaluate all
  4402. // initializers even if some of them fail.
  4403. if (!Info.noteFailure())
  4404. return false;
  4405. Success = false;
  4406. } else if (!ForbiddenNullArgs.empty() &&
  4407. ForbiddenNullArgs[I - Args.begin()] &&
  4408. ArgValues[I - Args.begin()].isNullPointer()) {
  4409. Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
  4410. if (!Info.noteFailure())
  4411. return false;
  4412. Success = false;
  4413. }
  4414. }
  4415. return Success;
  4416. }
  4417. /// Evaluate a function call.
  4418. static bool HandleFunctionCall(SourceLocation CallLoc,
  4419. const FunctionDecl *Callee, const LValue *This,
  4420. ArrayRef<const Expr*> Args, const Stmt *Body,
  4421. EvalInfo &Info, APValue &Result,
  4422. const LValue *ResultSlot) {
  4423. ArgVector ArgValues(Args.size());
  4424. if (!EvaluateArgs(Args, ArgValues, Info, Callee))
  4425. return false;
  4426. if (!Info.CheckCallLimit(CallLoc))
  4427. return false;
  4428. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  4429. // For a trivial copy or move assignment, perform an APValue copy. This is
  4430. // essential for unions, where the operations performed by the assignment
  4431. // operator cannot be represented as statements.
  4432. //
  4433. // Skip this for non-union classes with no fields; in that case, the defaulted
  4434. // copy/move does not actually read the object.
  4435. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  4436. if (MD && MD->isDefaulted() &&
  4437. (MD->getParent()->isUnion() ||
  4438. (MD->isTrivial() && hasFields(MD->getParent())))) {
  4439. assert(This &&
  4440. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  4441. LValue RHS;
  4442. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4443. APValue RHSValue;
  4444. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  4445. RHS, RHSValue))
  4446. return false;
  4447. if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
  4448. !HandleUnionActiveMemberChange(Info, Args[0], *This))
  4449. return false;
  4450. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  4451. RHSValue))
  4452. return false;
  4453. This->moveInto(Result);
  4454. return true;
  4455. } else if (MD && isLambdaCallOperator(MD)) {
  4456. // We're in a lambda; determine the lambda capture field maps unless we're
  4457. // just constexpr checking a lambda's call operator. constexpr checking is
  4458. // done before the captures have been added to the closure object (unless
  4459. // we're inferring constexpr-ness), so we don't have access to them in this
  4460. // case. But since we don't need the captures to constexpr check, we can
  4461. // just ignore them.
  4462. if (!Info.checkingPotentialConstantExpression())
  4463. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  4464. Frame.LambdaThisCaptureField);
  4465. }
  4466. StmtResult Ret = {Result, ResultSlot};
  4467. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  4468. if (ESR == ESR_Succeeded) {
  4469. if (Callee->getReturnType()->isVoidType())
  4470. return true;
  4471. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  4472. }
  4473. return ESR == ESR_Returned;
  4474. }
  4475. /// Evaluate a constructor call.
  4476. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4477. APValue *ArgValues,
  4478. const CXXConstructorDecl *Definition,
  4479. EvalInfo &Info, APValue &Result) {
  4480. SourceLocation CallLoc = E->getExprLoc();
  4481. if (!Info.CheckCallLimit(CallLoc))
  4482. return false;
  4483. const CXXRecordDecl *RD = Definition->getParent();
  4484. if (RD->getNumVBases()) {
  4485. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  4486. return false;
  4487. }
  4488. EvalInfo::EvaluatingConstructorRAII EvalObj(
  4489. Info,
  4490. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  4491. RD->getNumBases());
  4492. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  4493. // FIXME: Creating an APValue just to hold a nonexistent return value is
  4494. // wasteful.
  4495. APValue RetVal;
  4496. StmtResult Ret = {RetVal, nullptr};
  4497. // If it's a delegating constructor, delegate.
  4498. if (Definition->isDelegatingConstructor()) {
  4499. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  4500. {
  4501. FullExpressionRAII InitScope(Info);
  4502. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  4503. return false;
  4504. }
  4505. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4506. }
  4507. // For a trivial copy or move constructor, perform an APValue copy. This is
  4508. // essential for unions (or classes with anonymous union members), where the
  4509. // operations performed by the constructor cannot be represented by
  4510. // ctor-initializers.
  4511. //
  4512. // Skip this for empty non-union classes; we should not perform an
  4513. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4514. // actually read them.
  4515. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4516. (Definition->getParent()->isUnion() ||
  4517. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4518. LValue RHS;
  4519. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4520. return handleLValueToRValueConversion(
  4521. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4522. RHS, Result);
  4523. }
  4524. // Reserve space for the struct members.
  4525. if (!RD->isUnion() && !Result.hasValue())
  4526. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4527. std::distance(RD->field_begin(), RD->field_end()));
  4528. if (RD->isInvalidDecl()) return false;
  4529. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4530. // A scope for temporaries lifetime-extended by reference members.
  4531. BlockScopeRAII LifetimeExtendedScope(Info);
  4532. bool Success = true;
  4533. unsigned BasesSeen = 0;
  4534. #ifndef NDEBUG
  4535. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4536. #endif
  4537. for (const auto *I : Definition->inits()) {
  4538. LValue Subobject = This;
  4539. LValue SubobjectParent = This;
  4540. APValue *Value = &Result;
  4541. // Determine the subobject to initialize.
  4542. FieldDecl *FD = nullptr;
  4543. if (I->isBaseInitializer()) {
  4544. QualType BaseType(I->getBaseClass(), 0);
  4545. #ifndef NDEBUG
  4546. // Non-virtual base classes are initialized in the order in the class
  4547. // definition. We have already checked for virtual base classes.
  4548. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4549. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4550. "base class initializers not in expected order");
  4551. ++BaseIt;
  4552. #endif
  4553. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4554. BaseType->getAsCXXRecordDecl(), &Layout))
  4555. return false;
  4556. Value = &Result.getStructBase(BasesSeen++);
  4557. } else if ((FD = I->getMember())) {
  4558. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4559. return false;
  4560. if (RD->isUnion()) {
  4561. Result = APValue(FD);
  4562. Value = &Result.getUnionValue();
  4563. } else {
  4564. Value = &Result.getStructField(FD->getFieldIndex());
  4565. }
  4566. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4567. // Walk the indirect field decl's chain to find the object to initialize,
  4568. // and make sure we've initialized every step along it.
  4569. auto IndirectFieldChain = IFD->chain();
  4570. for (auto *C : IndirectFieldChain) {
  4571. FD = cast<FieldDecl>(C);
  4572. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4573. // Switch the union field if it differs. This happens if we had
  4574. // preceding zero-initialization, and we're now initializing a union
  4575. // subobject other than the first.
  4576. // FIXME: In this case, the values of the other subobjects are
  4577. // specified, since zero-initialization sets all padding bits to zero.
  4578. if (!Value->hasValue() ||
  4579. (Value->isUnion() && Value->getUnionField() != FD)) {
  4580. if (CD->isUnion())
  4581. *Value = APValue(FD);
  4582. else
  4583. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4584. std::distance(CD->field_begin(), CD->field_end()));
  4585. }
  4586. // Store Subobject as its parent before updating it for the last element
  4587. // in the chain.
  4588. if (C == IndirectFieldChain.back())
  4589. SubobjectParent = Subobject;
  4590. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4591. return false;
  4592. if (CD->isUnion())
  4593. Value = &Value->getUnionValue();
  4594. else
  4595. Value = &Value->getStructField(FD->getFieldIndex());
  4596. }
  4597. } else {
  4598. llvm_unreachable("unknown base initializer kind");
  4599. }
  4600. // Need to override This for implicit field initializers as in this case
  4601. // This refers to innermost anonymous struct/union containing initializer,
  4602. // not to currently constructed class.
  4603. const Expr *Init = I->getInit();
  4604. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4605. isa<CXXDefaultInitExpr>(Init));
  4606. FullExpressionRAII InitScope(Info);
  4607. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4608. (FD && FD->isBitField() &&
  4609. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4610. // If we're checking for a potential constant expression, evaluate all
  4611. // initializers even if some of them fail.
  4612. if (!Info.noteFailure())
  4613. return false;
  4614. Success = false;
  4615. }
  4616. // This is the point at which the dynamic type of the object becomes this
  4617. // class type.
  4618. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  4619. EvalObj.finishedConstructingBases();
  4620. }
  4621. return Success &&
  4622. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4623. }
  4624. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4625. ArrayRef<const Expr*> Args,
  4626. const CXXConstructorDecl *Definition,
  4627. EvalInfo &Info, APValue &Result) {
  4628. ArgVector ArgValues(Args.size());
  4629. if (!EvaluateArgs(Args, ArgValues, Info, Definition))
  4630. return false;
  4631. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4632. Info, Result);
  4633. }
  4634. //===----------------------------------------------------------------------===//
  4635. // Generic Evaluation
  4636. //===----------------------------------------------------------------------===//
  4637. namespace {
  4638. class BitCastBuffer {
  4639. // FIXME: We're going to need bit-level granularity when we support
  4640. // bit-fields.
  4641. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  4642. // we don't support a host or target where that is the case. Still, we should
  4643. // use a more generic type in case we ever do.
  4644. SmallVector<Optional<unsigned char>, 32> Bytes;
  4645. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  4646. "Need at least 8 bit unsigned char");
  4647. bool TargetIsLittleEndian;
  4648. public:
  4649. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  4650. : Bytes(Width.getQuantity()),
  4651. TargetIsLittleEndian(TargetIsLittleEndian) {}
  4652. LLVM_NODISCARD
  4653. bool readObject(CharUnits Offset, CharUnits Width,
  4654. SmallVectorImpl<unsigned char> &Output) const {
  4655. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  4656. // If a byte of an integer is uninitialized, then the whole integer is
  4657. // uninitalized.
  4658. if (!Bytes[I.getQuantity()])
  4659. return false;
  4660. Output.push_back(*Bytes[I.getQuantity()]);
  4661. }
  4662. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  4663. std::reverse(Output.begin(), Output.end());
  4664. return true;
  4665. }
  4666. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  4667. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  4668. std::reverse(Input.begin(), Input.end());
  4669. size_t Index = 0;
  4670. for (unsigned char Byte : Input) {
  4671. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  4672. Bytes[Offset.getQuantity() + Index] = Byte;
  4673. ++Index;
  4674. }
  4675. }
  4676. size_t size() { return Bytes.size(); }
  4677. };
  4678. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  4679. /// target would represent the value at runtime.
  4680. class APValueToBufferConverter {
  4681. EvalInfo &Info;
  4682. BitCastBuffer Buffer;
  4683. const CastExpr *BCE;
  4684. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  4685. const CastExpr *BCE)
  4686. : Info(Info),
  4687. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  4688. BCE(BCE) {}
  4689. bool visit(const APValue &Val, QualType Ty) {
  4690. return visit(Val, Ty, CharUnits::fromQuantity(0));
  4691. }
  4692. // Write out Val with type Ty into Buffer starting at Offset.
  4693. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  4694. assert((size_t)Offset.getQuantity() <= Buffer.size());
  4695. // As a special case, nullptr_t has an indeterminate value.
  4696. if (Ty->isNullPtrType())
  4697. return true;
  4698. // Dig through Src to find the byte at SrcOffset.
  4699. switch (Val.getKind()) {
  4700. case APValue::Indeterminate:
  4701. case APValue::None:
  4702. return true;
  4703. case APValue::Int:
  4704. return visitInt(Val.getInt(), Ty, Offset);
  4705. case APValue::Float:
  4706. return visitFloat(Val.getFloat(), Ty, Offset);
  4707. case APValue::Array:
  4708. return visitArray(Val, Ty, Offset);
  4709. case APValue::Struct:
  4710. return visitRecord(Val, Ty, Offset);
  4711. case APValue::ComplexInt:
  4712. case APValue::ComplexFloat:
  4713. case APValue::Vector:
  4714. case APValue::FixedPoint:
  4715. // FIXME: We should support these.
  4716. case APValue::Union:
  4717. case APValue::MemberPointer:
  4718. case APValue::AddrLabelDiff: {
  4719. Info.FFDiag(BCE->getBeginLoc(),
  4720. diag::note_constexpr_bit_cast_unsupported_type)
  4721. << Ty;
  4722. return false;
  4723. }
  4724. case APValue::LValue:
  4725. llvm_unreachable("LValue subobject in bit_cast?");
  4726. }
  4727. llvm_unreachable("Unhandled APValue::ValueKind");
  4728. }
  4729. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  4730. const RecordDecl *RD = Ty->getAsRecordDecl();
  4731. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4732. // Visit the base classes.
  4733. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4734. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  4735. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  4736. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  4737. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  4738. Layout.getBaseClassOffset(BaseDecl) + Offset))
  4739. return false;
  4740. }
  4741. }
  4742. // Visit the fields.
  4743. unsigned FieldIdx = 0;
  4744. for (FieldDecl *FD : RD->fields()) {
  4745. if (FD->isBitField()) {
  4746. Info.FFDiag(BCE->getBeginLoc(),
  4747. diag::note_constexpr_bit_cast_unsupported_bitfield);
  4748. return false;
  4749. }
  4750. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  4751. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  4752. "only bit-fields can have sub-char alignment");
  4753. CharUnits FieldOffset =
  4754. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  4755. QualType FieldTy = FD->getType();
  4756. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  4757. return false;
  4758. ++FieldIdx;
  4759. }
  4760. return true;
  4761. }
  4762. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  4763. const auto *CAT =
  4764. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  4765. if (!CAT)
  4766. return false;
  4767. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  4768. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  4769. unsigned ArraySize = Val.getArraySize();
  4770. // First, initialize the initialized elements.
  4771. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  4772. const APValue &SubObj = Val.getArrayInitializedElt(I);
  4773. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  4774. return false;
  4775. }
  4776. // Next, initialize the rest of the array using the filler.
  4777. if (Val.hasArrayFiller()) {
  4778. const APValue &Filler = Val.getArrayFiller();
  4779. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  4780. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  4781. return false;
  4782. }
  4783. }
  4784. return true;
  4785. }
  4786. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  4787. CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
  4788. SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
  4789. llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
  4790. Buffer.writeObject(Offset, Bytes);
  4791. return true;
  4792. }
  4793. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  4794. APSInt AsInt(Val.bitcastToAPInt());
  4795. return visitInt(AsInt, Ty, Offset);
  4796. }
  4797. public:
  4798. static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
  4799. const CastExpr *BCE) {
  4800. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  4801. APValueToBufferConverter Converter(Info, DstSize, BCE);
  4802. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  4803. return None;
  4804. return Converter.Buffer;
  4805. }
  4806. };
  4807. /// Write an BitCastBuffer into an APValue.
  4808. class BufferToAPValueConverter {
  4809. EvalInfo &Info;
  4810. const BitCastBuffer &Buffer;
  4811. const CastExpr *BCE;
  4812. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  4813. const CastExpr *BCE)
  4814. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  4815. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  4816. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  4817. // Ideally this will be unreachable.
  4818. llvm::NoneType unsupportedType(QualType Ty) {
  4819. Info.FFDiag(BCE->getBeginLoc(),
  4820. diag::note_constexpr_bit_cast_unsupported_type)
  4821. << Ty;
  4822. return None;
  4823. }
  4824. Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  4825. const EnumType *EnumSugar = nullptr) {
  4826. if (T->isNullPtrType()) {
  4827. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  4828. return APValue((Expr *)nullptr,
  4829. /*Offset=*/CharUnits::fromQuantity(NullValue),
  4830. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  4831. }
  4832. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  4833. SmallVector<uint8_t, 8> Bytes;
  4834. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  4835. // If this is std::byte or unsigned char, then its okay to store an
  4836. // indeterminate value.
  4837. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  4838. bool IsUChar =
  4839. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  4840. T->isSpecificBuiltinType(BuiltinType::Char_U));
  4841. if (!IsStdByte && !IsUChar) {
  4842. QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
  4843. Info.FFDiag(BCE->getExprLoc(),
  4844. diag::note_constexpr_bit_cast_indet_dest)
  4845. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  4846. return None;
  4847. }
  4848. return APValue::IndeterminateValue();
  4849. }
  4850. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  4851. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  4852. if (T->isIntegralOrEnumerationType()) {
  4853. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  4854. return APValue(Val);
  4855. }
  4856. if (T->isRealFloatingType()) {
  4857. const llvm::fltSemantics &Semantics =
  4858. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  4859. return APValue(APFloat(Semantics, Val));
  4860. }
  4861. return unsupportedType(QualType(T, 0));
  4862. }
  4863. Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  4864. const RecordDecl *RD = RTy->getAsRecordDecl();
  4865. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4866. unsigned NumBases = 0;
  4867. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  4868. NumBases = CXXRD->getNumBases();
  4869. APValue ResultVal(APValue::UninitStruct(), NumBases,
  4870. std::distance(RD->field_begin(), RD->field_end()));
  4871. // Visit the base classes.
  4872. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4873. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  4874. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  4875. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  4876. if (BaseDecl->isEmpty() ||
  4877. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  4878. continue;
  4879. Optional<APValue> SubObj = visitType(
  4880. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  4881. if (!SubObj)
  4882. return None;
  4883. ResultVal.getStructBase(I) = *SubObj;
  4884. }
  4885. }
  4886. // Visit the fields.
  4887. unsigned FieldIdx = 0;
  4888. for (FieldDecl *FD : RD->fields()) {
  4889. // FIXME: We don't currently support bit-fields. A lot of the logic for
  4890. // this is in CodeGen, so we need to factor it around.
  4891. if (FD->isBitField()) {
  4892. Info.FFDiag(BCE->getBeginLoc(),
  4893. diag::note_constexpr_bit_cast_unsupported_bitfield);
  4894. return None;
  4895. }
  4896. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  4897. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  4898. CharUnits FieldOffset =
  4899. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  4900. Offset;
  4901. QualType FieldTy = FD->getType();
  4902. Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  4903. if (!SubObj)
  4904. return None;
  4905. ResultVal.getStructField(FieldIdx) = *SubObj;
  4906. ++FieldIdx;
  4907. }
  4908. return ResultVal;
  4909. }
  4910. Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  4911. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  4912. assert(!RepresentationType.isNull() &&
  4913. "enum forward decl should be caught by Sema");
  4914. const BuiltinType *AsBuiltin =
  4915. RepresentationType.getCanonicalType()->getAs<BuiltinType>();
  4916. assert(AsBuiltin && "non-integral enum underlying type?");
  4917. // Recurse into the underlying type. Treat std::byte transparently as
  4918. // unsigned char.
  4919. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  4920. }
  4921. Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  4922. size_t Size = Ty->getSize().getLimitedValue();
  4923. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  4924. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  4925. for (size_t I = 0; I != Size; ++I) {
  4926. Optional<APValue> ElementValue =
  4927. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  4928. if (!ElementValue)
  4929. return None;
  4930. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  4931. }
  4932. return ArrayValue;
  4933. }
  4934. Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  4935. return unsupportedType(QualType(Ty, 0));
  4936. }
  4937. Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  4938. QualType Can = Ty.getCanonicalType();
  4939. switch (Can->getTypeClass()) {
  4940. #define TYPE(Class, Base) \
  4941. case Type::Class: \
  4942. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  4943. #define ABSTRACT_TYPE(Class, Base)
  4944. #define NON_CANONICAL_TYPE(Class, Base) \
  4945. case Type::Class: \
  4946. llvm_unreachable("non-canonical type should be impossible!");
  4947. #define DEPENDENT_TYPE(Class, Base) \
  4948. case Type::Class: \
  4949. llvm_unreachable( \
  4950. "dependent types aren't supported in the constant evaluator!");
  4951. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  4952. case Type::Class: \
  4953. llvm_unreachable("either dependent or not canonical!");
  4954. #include "clang/AST/TypeNodes.def"
  4955. }
  4956. llvm_unreachable("Unhandled Type::TypeClass");
  4957. }
  4958. public:
  4959. // Pull out a full value of type DstType.
  4960. static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  4961. const CastExpr *BCE) {
  4962. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  4963. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  4964. }
  4965. };
  4966. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  4967. QualType Ty, EvalInfo *Info,
  4968. const ASTContext &Ctx,
  4969. bool CheckingDest) {
  4970. Ty = Ty.getCanonicalType();
  4971. auto diag = [&](int Reason) {
  4972. if (Info)
  4973. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  4974. << CheckingDest << (Reason == 4) << Reason;
  4975. return false;
  4976. };
  4977. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  4978. if (Info)
  4979. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  4980. << NoteTy << Construct << Ty;
  4981. return false;
  4982. };
  4983. if (Ty->isUnionType())
  4984. return diag(0);
  4985. if (Ty->isPointerType())
  4986. return diag(1);
  4987. if (Ty->isMemberPointerType())
  4988. return diag(2);
  4989. if (Ty.isVolatileQualified())
  4990. return diag(3);
  4991. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  4992. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  4993. for (CXXBaseSpecifier &BS : CXXRD->bases())
  4994. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  4995. CheckingDest))
  4996. return note(1, BS.getType(), BS.getBeginLoc());
  4997. }
  4998. for (FieldDecl *FD : Record->fields()) {
  4999. if (FD->getType()->isReferenceType())
  5000. return diag(4);
  5001. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  5002. CheckingDest))
  5003. return note(0, FD->getType(), FD->getBeginLoc());
  5004. }
  5005. }
  5006. if (Ty->isArrayType() &&
  5007. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  5008. Info, Ctx, CheckingDest))
  5009. return false;
  5010. return true;
  5011. }
  5012. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  5013. const ASTContext &Ctx,
  5014. const CastExpr *BCE) {
  5015. bool DestOK = checkBitCastConstexprEligibilityType(
  5016. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  5017. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  5018. BCE->getBeginLoc(),
  5019. BCE->getSubExpr()->getType(), Info, Ctx, false);
  5020. return SourceOK;
  5021. }
  5022. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  5023. APValue &SourceValue,
  5024. const CastExpr *BCE) {
  5025. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  5026. "no host or target supports non 8-bit chars");
  5027. assert(SourceValue.isLValue() &&
  5028. "LValueToRValueBitcast requires an lvalue operand!");
  5029. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  5030. return false;
  5031. LValue SourceLValue;
  5032. APValue SourceRValue;
  5033. SourceLValue.setFrom(Info.Ctx, SourceValue);
  5034. if (!handleLValueToRValueConversion(Info, BCE,
  5035. BCE->getSubExpr()->getType().withConst(),
  5036. SourceLValue, SourceRValue))
  5037. return false;
  5038. // Read out SourceValue into a char buffer.
  5039. Optional<BitCastBuffer> Buffer =
  5040. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  5041. if (!Buffer)
  5042. return false;
  5043. // Write out the buffer into a new APValue.
  5044. Optional<APValue> MaybeDestValue =
  5045. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  5046. if (!MaybeDestValue)
  5047. return false;
  5048. DestValue = std::move(*MaybeDestValue);
  5049. return true;
  5050. }
  5051. template <class Derived>
  5052. class ExprEvaluatorBase
  5053. : public ConstStmtVisitor<Derived, bool> {
  5054. private:
  5055. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5056. bool DerivedSuccess(const APValue &V, const Expr *E) {
  5057. return getDerived().Success(V, E);
  5058. }
  5059. bool DerivedZeroInitialization(const Expr *E) {
  5060. return getDerived().ZeroInitialization(E);
  5061. }
  5062. // Check whether a conditional operator with a non-constant condition is a
  5063. // potential constant expression. If neither arm is a potential constant
  5064. // expression, then the conditional operator is not either.
  5065. template<typename ConditionalOperator>
  5066. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  5067. assert(Info.checkingPotentialConstantExpression());
  5068. // Speculatively evaluate both arms.
  5069. SmallVector<PartialDiagnosticAt, 8> Diag;
  5070. {
  5071. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5072. StmtVisitorTy::Visit(E->getFalseExpr());
  5073. if (Diag.empty())
  5074. return;
  5075. }
  5076. {
  5077. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5078. Diag.clear();
  5079. StmtVisitorTy::Visit(E->getTrueExpr());
  5080. if (Diag.empty())
  5081. return;
  5082. }
  5083. Error(E, diag::note_constexpr_conditional_never_const);
  5084. }
  5085. template<typename ConditionalOperator>
  5086. bool HandleConditionalOperator(const ConditionalOperator *E) {
  5087. bool BoolResult;
  5088. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  5089. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  5090. CheckPotentialConstantConditional(E);
  5091. return false;
  5092. }
  5093. if (Info.noteFailure()) {
  5094. StmtVisitorTy::Visit(E->getTrueExpr());
  5095. StmtVisitorTy::Visit(E->getFalseExpr());
  5096. }
  5097. return false;
  5098. }
  5099. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  5100. return StmtVisitorTy::Visit(EvalExpr);
  5101. }
  5102. protected:
  5103. EvalInfo &Info;
  5104. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  5105. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  5106. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  5107. return Info.CCEDiag(E, D);
  5108. }
  5109. bool ZeroInitialization(const Expr *E) { return Error(E); }
  5110. public:
  5111. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  5112. EvalInfo &getEvalInfo() { return Info; }
  5113. /// Report an evaluation error. This should only be called when an error is
  5114. /// first discovered. When propagating an error, just return false.
  5115. bool Error(const Expr *E, diag::kind D) {
  5116. Info.FFDiag(E, D);
  5117. return false;
  5118. }
  5119. bool Error(const Expr *E) {
  5120. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  5121. }
  5122. bool VisitStmt(const Stmt *) {
  5123. llvm_unreachable("Expression evaluator should not be called on stmts");
  5124. }
  5125. bool VisitExpr(const Expr *E) {
  5126. return Error(E);
  5127. }
  5128. bool VisitConstantExpr(const ConstantExpr *E)
  5129. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5130. bool VisitParenExpr(const ParenExpr *E)
  5131. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5132. bool VisitUnaryExtension(const UnaryOperator *E)
  5133. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5134. bool VisitUnaryPlus(const UnaryOperator *E)
  5135. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5136. bool VisitChooseExpr(const ChooseExpr *E)
  5137. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  5138. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  5139. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  5140. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  5141. { return StmtVisitorTy::Visit(E->getReplacement()); }
  5142. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  5143. TempVersionRAII RAII(*Info.CurrentCall);
  5144. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5145. return StmtVisitorTy::Visit(E->getExpr());
  5146. }
  5147. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  5148. TempVersionRAII RAII(*Info.CurrentCall);
  5149. // The initializer may not have been parsed yet, or might be erroneous.
  5150. if (!E->getExpr())
  5151. return Error(E);
  5152. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5153. return StmtVisitorTy::Visit(E->getExpr());
  5154. }
  5155. // We cannot create any objects for which cleanups are required, so there is
  5156. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  5157. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  5158. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5159. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  5160. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  5161. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5162. }
  5163. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  5164. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  5165. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  5166. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5167. }
  5168. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  5169. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5170. }
  5171. bool VisitBinaryOperator(const BinaryOperator *E) {
  5172. switch (E->getOpcode()) {
  5173. default:
  5174. return Error(E);
  5175. case BO_Comma:
  5176. VisitIgnoredValue(E->getLHS());
  5177. return StmtVisitorTy::Visit(E->getRHS());
  5178. case BO_PtrMemD:
  5179. case BO_PtrMemI: {
  5180. LValue Obj;
  5181. if (!HandleMemberPointerAccess(Info, E, Obj))
  5182. return false;
  5183. APValue Result;
  5184. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  5185. return false;
  5186. return DerivedSuccess(Result, E);
  5187. }
  5188. }
  5189. }
  5190. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  5191. // Evaluate and cache the common expression. We treat it as a temporary,
  5192. // even though it's not quite the same thing.
  5193. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  5194. Info, E->getCommon()))
  5195. return false;
  5196. return HandleConditionalOperator(E);
  5197. }
  5198. bool VisitConditionalOperator(const ConditionalOperator *E) {
  5199. bool IsBcpCall = false;
  5200. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5201. // the result is a constant expression if it can be folded without
  5202. // side-effects. This is an important GNU extension. See GCC PR38377
  5203. // for discussion.
  5204. if (const CallExpr *CallCE =
  5205. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  5206. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  5207. IsBcpCall = true;
  5208. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  5209. // constant expression; we can't check whether it's potentially foldable.
  5210. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  5211. return false;
  5212. FoldConstant Fold(Info, IsBcpCall);
  5213. if (!HandleConditionalOperator(E)) {
  5214. Fold.keepDiagnostics();
  5215. return false;
  5216. }
  5217. return true;
  5218. }
  5219. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  5220. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  5221. return DerivedSuccess(*Value, E);
  5222. const Expr *Source = E->getSourceExpr();
  5223. if (!Source)
  5224. return Error(E);
  5225. if (Source == E) { // sanity checking.
  5226. assert(0 && "OpaqueValueExpr recursively refers to itself");
  5227. return Error(E);
  5228. }
  5229. return StmtVisitorTy::Visit(Source);
  5230. }
  5231. bool VisitCallExpr(const CallExpr *E) {
  5232. APValue Result;
  5233. if (!handleCallExpr(E, Result, nullptr))
  5234. return false;
  5235. return DerivedSuccess(Result, E);
  5236. }
  5237. bool handleCallExpr(const CallExpr *E, APValue &Result,
  5238. const LValue *ResultSlot) {
  5239. const Expr *Callee = E->getCallee()->IgnoreParens();
  5240. QualType CalleeType = Callee->getType();
  5241. const FunctionDecl *FD = nullptr;
  5242. LValue *This = nullptr, ThisVal;
  5243. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5244. bool HasQualifier = false;
  5245. // Extract function decl and 'this' pointer from the callee.
  5246. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  5247. const CXXMethodDecl *Member = nullptr;
  5248. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  5249. // Explicit bound member calls, such as x.f() or p->g();
  5250. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  5251. return false;
  5252. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  5253. if (!Member)
  5254. return Error(Callee);
  5255. This = &ThisVal;
  5256. HasQualifier = ME->hasQualifier();
  5257. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  5258. // Indirect bound member calls ('.*' or '->*').
  5259. Member = dyn_cast_or_null<CXXMethodDecl>(
  5260. HandleMemberPointerAccess(Info, BE, ThisVal, false));
  5261. if (!Member)
  5262. return Error(Callee);
  5263. This = &ThisVal;
  5264. } else
  5265. return Error(Callee);
  5266. FD = Member;
  5267. } else if (CalleeType->isFunctionPointerType()) {
  5268. LValue Call;
  5269. if (!EvaluatePointer(Callee, Call, Info))
  5270. return false;
  5271. if (!Call.getLValueOffset().isZero())
  5272. return Error(Callee);
  5273. FD = dyn_cast_or_null<FunctionDecl>(
  5274. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  5275. if (!FD)
  5276. return Error(Callee);
  5277. // Don't call function pointers which have been cast to some other type.
  5278. // Per DR (no number yet), the caller and callee can differ in noexcept.
  5279. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  5280. CalleeType->getPointeeType(), FD->getType())) {
  5281. return Error(E);
  5282. }
  5283. // Overloaded operator calls to member functions are represented as normal
  5284. // calls with '*this' as the first argument.
  5285. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  5286. if (MD && !MD->isStatic()) {
  5287. // FIXME: When selecting an implicit conversion for an overloaded
  5288. // operator delete, we sometimes try to evaluate calls to conversion
  5289. // operators without a 'this' parameter!
  5290. if (Args.empty())
  5291. return Error(E);
  5292. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  5293. return false;
  5294. This = &ThisVal;
  5295. Args = Args.slice(1);
  5296. } else if (MD && MD->isLambdaStaticInvoker()) {
  5297. // Map the static invoker for the lambda back to the call operator.
  5298. // Conveniently, we don't have to slice out the 'this' argument (as is
  5299. // being done for the non-static case), since a static member function
  5300. // doesn't have an implicit argument passed in.
  5301. const CXXRecordDecl *ClosureClass = MD->getParent();
  5302. assert(
  5303. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  5304. "Number of captures must be zero for conversion to function-ptr");
  5305. const CXXMethodDecl *LambdaCallOp =
  5306. ClosureClass->getLambdaCallOperator();
  5307. // Set 'FD', the function that will be called below, to the call
  5308. // operator. If the closure object represents a generic lambda, find
  5309. // the corresponding specialization of the call operator.
  5310. if (ClosureClass->isGenericLambda()) {
  5311. assert(MD->isFunctionTemplateSpecialization() &&
  5312. "A generic lambda's static-invoker function must be a "
  5313. "template specialization");
  5314. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  5315. FunctionTemplateDecl *CallOpTemplate =
  5316. LambdaCallOp->getDescribedFunctionTemplate();
  5317. void *InsertPos = nullptr;
  5318. FunctionDecl *CorrespondingCallOpSpecialization =
  5319. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  5320. assert(CorrespondingCallOpSpecialization &&
  5321. "We must always have a function call operator specialization "
  5322. "that corresponds to our static invoker specialization");
  5323. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  5324. } else
  5325. FD = LambdaCallOp;
  5326. }
  5327. } else
  5328. return Error(E);
  5329. SmallVector<QualType, 4> CovariantAdjustmentPath;
  5330. if (This) {
  5331. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  5332. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  5333. // Perform virtual dispatch, if necessary.
  5334. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  5335. CovariantAdjustmentPath);
  5336. if (!FD)
  5337. return false;
  5338. } else {
  5339. // Check that the 'this' pointer points to an object of the right type.
  5340. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
  5341. return false;
  5342. }
  5343. }
  5344. const FunctionDecl *Definition = nullptr;
  5345. Stmt *Body = FD->getBody(Definition);
  5346. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  5347. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  5348. Result, ResultSlot))
  5349. return false;
  5350. if (!CovariantAdjustmentPath.empty() &&
  5351. !HandleCovariantReturnAdjustment(Info, E, Result,
  5352. CovariantAdjustmentPath))
  5353. return false;
  5354. return true;
  5355. }
  5356. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5357. return StmtVisitorTy::Visit(E->getInitializer());
  5358. }
  5359. bool VisitInitListExpr(const InitListExpr *E) {
  5360. if (E->getNumInits() == 0)
  5361. return DerivedZeroInitialization(E);
  5362. if (E->getNumInits() == 1)
  5363. return StmtVisitorTy::Visit(E->getInit(0));
  5364. return Error(E);
  5365. }
  5366. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  5367. return DerivedZeroInitialization(E);
  5368. }
  5369. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  5370. return DerivedZeroInitialization(E);
  5371. }
  5372. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  5373. return DerivedZeroInitialization(E);
  5374. }
  5375. /// A member expression where the object is a prvalue is itself a prvalue.
  5376. bool VisitMemberExpr(const MemberExpr *E) {
  5377. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  5378. "missing temporary materialization conversion");
  5379. assert(!E->isArrow() && "missing call to bound member function?");
  5380. APValue Val;
  5381. if (!Evaluate(Val, Info, E->getBase()))
  5382. return false;
  5383. QualType BaseTy = E->getBase()->getType();
  5384. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  5385. if (!FD) return Error(E);
  5386. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  5387. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5388. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5389. // Note: there is no lvalue base here. But this case should only ever
  5390. // happen in C or in C++98, where we cannot be evaluating a constexpr
  5391. // constructor, which is the only case the base matters.
  5392. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  5393. SubobjectDesignator Designator(BaseTy);
  5394. Designator.addDeclUnchecked(FD);
  5395. APValue Result;
  5396. return extractSubobject(Info, E, Obj, Designator, Result) &&
  5397. DerivedSuccess(Result, E);
  5398. }
  5399. bool VisitCastExpr(const CastExpr *E) {
  5400. switch (E->getCastKind()) {
  5401. default:
  5402. break;
  5403. case CK_AtomicToNonAtomic: {
  5404. APValue AtomicVal;
  5405. // This does not need to be done in place even for class/array types:
  5406. // atomic-to-non-atomic conversion implies copying the object
  5407. // representation.
  5408. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  5409. return false;
  5410. return DerivedSuccess(AtomicVal, E);
  5411. }
  5412. case CK_NoOp:
  5413. case CK_UserDefinedConversion:
  5414. return StmtVisitorTy::Visit(E->getSubExpr());
  5415. case CK_LValueToRValue: {
  5416. LValue LVal;
  5417. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  5418. return false;
  5419. APValue RVal;
  5420. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5421. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5422. LVal, RVal))
  5423. return false;
  5424. return DerivedSuccess(RVal, E);
  5425. }
  5426. case CK_LValueToRValueBitCast: {
  5427. APValue DestValue, SourceValue;
  5428. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  5429. return false;
  5430. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  5431. return false;
  5432. return DerivedSuccess(DestValue, E);
  5433. }
  5434. }
  5435. return Error(E);
  5436. }
  5437. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  5438. return VisitUnaryPostIncDec(UO);
  5439. }
  5440. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  5441. return VisitUnaryPostIncDec(UO);
  5442. }
  5443. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  5444. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5445. return Error(UO);
  5446. LValue LVal;
  5447. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  5448. return false;
  5449. APValue RVal;
  5450. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  5451. UO->isIncrementOp(), &RVal))
  5452. return false;
  5453. return DerivedSuccess(RVal, UO);
  5454. }
  5455. bool VisitStmtExpr(const StmtExpr *E) {
  5456. // We will have checked the full-expressions inside the statement expression
  5457. // when they were completed, and don't need to check them again now.
  5458. if (Info.checkingForOverflow())
  5459. return Error(E);
  5460. BlockScopeRAII Scope(Info);
  5461. const CompoundStmt *CS = E->getSubStmt();
  5462. if (CS->body_empty())
  5463. return true;
  5464. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  5465. BE = CS->body_end();
  5466. /**/; ++BI) {
  5467. if (BI + 1 == BE) {
  5468. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  5469. if (!FinalExpr) {
  5470. Info.FFDiag((*BI)->getBeginLoc(),
  5471. diag::note_constexpr_stmt_expr_unsupported);
  5472. return false;
  5473. }
  5474. return this->Visit(FinalExpr);
  5475. }
  5476. APValue ReturnValue;
  5477. StmtResult Result = { ReturnValue, nullptr };
  5478. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  5479. if (ESR != ESR_Succeeded) {
  5480. // FIXME: If the statement-expression terminated due to 'return',
  5481. // 'break', or 'continue', it would be nice to propagate that to
  5482. // the outer statement evaluation rather than bailing out.
  5483. if (ESR != ESR_Failed)
  5484. Info.FFDiag((*BI)->getBeginLoc(),
  5485. diag::note_constexpr_stmt_expr_unsupported);
  5486. return false;
  5487. }
  5488. }
  5489. llvm_unreachable("Return from function from the loop above.");
  5490. }
  5491. /// Visit a value which is evaluated, but whose value is ignored.
  5492. void VisitIgnoredValue(const Expr *E) {
  5493. EvaluateIgnoredValue(Info, E);
  5494. }
  5495. /// Potentially visit a MemberExpr's base expression.
  5496. void VisitIgnoredBaseExpression(const Expr *E) {
  5497. // While MSVC doesn't evaluate the base expression, it does diagnose the
  5498. // presence of side-effecting behavior.
  5499. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  5500. return;
  5501. VisitIgnoredValue(E);
  5502. }
  5503. };
  5504. } // namespace
  5505. //===----------------------------------------------------------------------===//
  5506. // Common base class for lvalue and temporary evaluation.
  5507. //===----------------------------------------------------------------------===//
  5508. namespace {
  5509. template<class Derived>
  5510. class LValueExprEvaluatorBase
  5511. : public ExprEvaluatorBase<Derived> {
  5512. protected:
  5513. LValue &Result;
  5514. bool InvalidBaseOK;
  5515. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  5516. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  5517. bool Success(APValue::LValueBase B) {
  5518. Result.set(B);
  5519. return true;
  5520. }
  5521. bool evaluatePointer(const Expr *E, LValue &Result) {
  5522. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  5523. }
  5524. public:
  5525. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  5526. : ExprEvaluatorBaseTy(Info), Result(Result),
  5527. InvalidBaseOK(InvalidBaseOK) {}
  5528. bool Success(const APValue &V, const Expr *E) {
  5529. Result.setFrom(this->Info.Ctx, V);
  5530. return true;
  5531. }
  5532. bool VisitMemberExpr(const MemberExpr *E) {
  5533. // Handle non-static data members.
  5534. QualType BaseTy;
  5535. bool EvalOK;
  5536. if (E->isArrow()) {
  5537. EvalOK = evaluatePointer(E->getBase(), Result);
  5538. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  5539. } else if (E->getBase()->isRValue()) {
  5540. assert(E->getBase()->getType()->isRecordType());
  5541. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  5542. BaseTy = E->getBase()->getType();
  5543. } else {
  5544. EvalOK = this->Visit(E->getBase());
  5545. BaseTy = E->getBase()->getType();
  5546. }
  5547. if (!EvalOK) {
  5548. if (!InvalidBaseOK)
  5549. return false;
  5550. Result.setInvalid(E);
  5551. return true;
  5552. }
  5553. const ValueDecl *MD = E->getMemberDecl();
  5554. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  5555. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5556. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5557. (void)BaseTy;
  5558. if (!HandleLValueMember(this->Info, E, Result, FD))
  5559. return false;
  5560. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  5561. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  5562. return false;
  5563. } else
  5564. return this->Error(E);
  5565. if (MD->getType()->isReferenceType()) {
  5566. APValue RefValue;
  5567. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  5568. RefValue))
  5569. return false;
  5570. return Success(RefValue, E);
  5571. }
  5572. return true;
  5573. }
  5574. bool VisitBinaryOperator(const BinaryOperator *E) {
  5575. switch (E->getOpcode()) {
  5576. default:
  5577. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5578. case BO_PtrMemD:
  5579. case BO_PtrMemI:
  5580. return HandleMemberPointerAccess(this->Info, E, Result);
  5581. }
  5582. }
  5583. bool VisitCastExpr(const CastExpr *E) {
  5584. switch (E->getCastKind()) {
  5585. default:
  5586. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5587. case CK_DerivedToBase:
  5588. case CK_UncheckedDerivedToBase:
  5589. if (!this->Visit(E->getSubExpr()))
  5590. return false;
  5591. // Now figure out the necessary offset to add to the base LV to get from
  5592. // the derived class to the base class.
  5593. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  5594. Result);
  5595. }
  5596. }
  5597. };
  5598. }
  5599. //===----------------------------------------------------------------------===//
  5600. // LValue Evaluation
  5601. //
  5602. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  5603. // function designators (in C), decl references to void objects (in C), and
  5604. // temporaries (if building with -Wno-address-of-temporary).
  5605. //
  5606. // LValue evaluation produces values comprising a base expression of one of the
  5607. // following types:
  5608. // - Declarations
  5609. // * VarDecl
  5610. // * FunctionDecl
  5611. // - Literals
  5612. // * CompoundLiteralExpr in C (and in global scope in C++)
  5613. // * StringLiteral
  5614. // * PredefinedExpr
  5615. // * ObjCStringLiteralExpr
  5616. // * ObjCEncodeExpr
  5617. // * AddrLabelExpr
  5618. // * BlockExpr
  5619. // * CallExpr for a MakeStringConstant builtin
  5620. // - typeid(T) expressions, as TypeInfoLValues
  5621. // - Locals and temporaries
  5622. // * MaterializeTemporaryExpr
  5623. // * Any Expr, with a CallIndex indicating the function in which the temporary
  5624. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  5625. // from the AST (FIXME).
  5626. // * A MaterializeTemporaryExpr that has static storage duration, with no
  5627. // CallIndex, for a lifetime-extended temporary.
  5628. // plus an offset in bytes.
  5629. //===----------------------------------------------------------------------===//
  5630. namespace {
  5631. class LValueExprEvaluator
  5632. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  5633. public:
  5634. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  5635. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  5636. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  5637. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  5638. bool VisitDeclRefExpr(const DeclRefExpr *E);
  5639. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  5640. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  5641. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  5642. bool VisitMemberExpr(const MemberExpr *E);
  5643. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  5644. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  5645. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  5646. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  5647. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  5648. bool VisitUnaryDeref(const UnaryOperator *E);
  5649. bool VisitUnaryReal(const UnaryOperator *E);
  5650. bool VisitUnaryImag(const UnaryOperator *E);
  5651. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  5652. return VisitUnaryPreIncDec(UO);
  5653. }
  5654. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  5655. return VisitUnaryPreIncDec(UO);
  5656. }
  5657. bool VisitBinAssign(const BinaryOperator *BO);
  5658. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  5659. bool VisitCastExpr(const CastExpr *E) {
  5660. switch (E->getCastKind()) {
  5661. default:
  5662. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  5663. case CK_LValueBitCast:
  5664. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5665. if (!Visit(E->getSubExpr()))
  5666. return false;
  5667. Result.Designator.setInvalid();
  5668. return true;
  5669. case CK_BaseToDerived:
  5670. if (!Visit(E->getSubExpr()))
  5671. return false;
  5672. return HandleBaseToDerivedCast(Info, E, Result);
  5673. case CK_Dynamic:
  5674. if (!Visit(E->getSubExpr()))
  5675. return false;
  5676. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  5677. }
  5678. }
  5679. };
  5680. } // end anonymous namespace
  5681. /// Evaluate an expression as an lvalue. This can be legitimately called on
  5682. /// expressions which are not glvalues, in three cases:
  5683. /// * function designators in C, and
  5684. /// * "extern void" objects
  5685. /// * @selector() expressions in Objective-C
  5686. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  5687. bool InvalidBaseOK) {
  5688. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  5689. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  5690. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5691. }
  5692. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  5693. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  5694. return Success(FD);
  5695. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  5696. return VisitVarDecl(E, VD);
  5697. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  5698. return Visit(BD->getBinding());
  5699. return Error(E);
  5700. }
  5701. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  5702. // If we are within a lambda's call operator, check whether the 'VD' referred
  5703. // to within 'E' actually represents a lambda-capture that maps to a
  5704. // data-member/field within the closure object, and if so, evaluate to the
  5705. // field or what the field refers to.
  5706. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  5707. isa<DeclRefExpr>(E) &&
  5708. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  5709. // We don't always have a complete capture-map when checking or inferring if
  5710. // the function call operator meets the requirements of a constexpr function
  5711. // - but we don't need to evaluate the captures to determine constexprness
  5712. // (dcl.constexpr C++17).
  5713. if (Info.checkingPotentialConstantExpression())
  5714. return false;
  5715. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  5716. // Start with 'Result' referring to the complete closure object...
  5717. Result = *Info.CurrentCall->This;
  5718. // ... then update it to refer to the field of the closure object
  5719. // that represents the capture.
  5720. if (!HandleLValueMember(Info, E, Result, FD))
  5721. return false;
  5722. // And if the field is of reference type, update 'Result' to refer to what
  5723. // the field refers to.
  5724. if (FD->getType()->isReferenceType()) {
  5725. APValue RVal;
  5726. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  5727. RVal))
  5728. return false;
  5729. Result.setFrom(Info.Ctx, RVal);
  5730. }
  5731. return true;
  5732. }
  5733. }
  5734. CallStackFrame *Frame = nullptr;
  5735. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  5736. // Only if a local variable was declared in the function currently being
  5737. // evaluated, do we expect to be able to find its value in the current
  5738. // frame. (Otherwise it was likely declared in an enclosing context and
  5739. // could either have a valid evaluatable value (for e.g. a constexpr
  5740. // variable) or be ill-formed (and trigger an appropriate evaluation
  5741. // diagnostic)).
  5742. if (Info.CurrentCall->Callee &&
  5743. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  5744. Frame = Info.CurrentCall;
  5745. }
  5746. }
  5747. if (!VD->getType()->isReferenceType()) {
  5748. if (Frame) {
  5749. Result.set({VD, Frame->Index,
  5750. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  5751. return true;
  5752. }
  5753. return Success(VD);
  5754. }
  5755. APValue *V;
  5756. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  5757. return false;
  5758. if (!V->hasValue()) {
  5759. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  5760. // adjust the diagnostic to say that.
  5761. if (!Info.checkingPotentialConstantExpression())
  5762. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  5763. return false;
  5764. }
  5765. return Success(*V, E);
  5766. }
  5767. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  5768. const MaterializeTemporaryExpr *E) {
  5769. // Walk through the expression to find the materialized temporary itself.
  5770. SmallVector<const Expr *, 2> CommaLHSs;
  5771. SmallVector<SubobjectAdjustment, 2> Adjustments;
  5772. const Expr *Inner = E->GetTemporaryExpr()->
  5773. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  5774. // If we passed any comma operators, evaluate their LHSs.
  5775. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  5776. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  5777. return false;
  5778. // A materialized temporary with static storage duration can appear within the
  5779. // result of a constant expression evaluation, so we need to preserve its
  5780. // value for use outside this evaluation.
  5781. APValue *Value;
  5782. if (E->getStorageDuration() == SD_Static) {
  5783. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  5784. *Value = APValue();
  5785. Result.set(E);
  5786. } else {
  5787. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  5788. *Info.CurrentCall);
  5789. }
  5790. QualType Type = Inner->getType();
  5791. // Materialize the temporary itself.
  5792. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  5793. (E->getStorageDuration() == SD_Static &&
  5794. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  5795. *Value = APValue();
  5796. return false;
  5797. }
  5798. // Adjust our lvalue to refer to the desired subobject.
  5799. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  5800. --I;
  5801. switch (Adjustments[I].Kind) {
  5802. case SubobjectAdjustment::DerivedToBaseAdjustment:
  5803. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  5804. Type, Result))
  5805. return false;
  5806. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  5807. break;
  5808. case SubobjectAdjustment::FieldAdjustment:
  5809. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  5810. return false;
  5811. Type = Adjustments[I].Field->getType();
  5812. break;
  5813. case SubobjectAdjustment::MemberPointerAdjustment:
  5814. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  5815. Adjustments[I].Ptr.RHS))
  5816. return false;
  5817. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  5818. break;
  5819. }
  5820. }
  5821. return true;
  5822. }
  5823. bool
  5824. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5825. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  5826. "lvalue compound literal in c++?");
  5827. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  5828. // only see this when folding in C, so there's no standard to follow here.
  5829. return Success(E);
  5830. }
  5831. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  5832. TypeInfoLValue TypeInfo;
  5833. if (!E->isPotentiallyEvaluated()) {
  5834. if (E->isTypeOperand())
  5835. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  5836. else
  5837. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  5838. } else {
  5839. if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
  5840. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  5841. << E->getExprOperand()->getType()
  5842. << E->getExprOperand()->getSourceRange();
  5843. }
  5844. if (!Visit(E->getExprOperand()))
  5845. return false;
  5846. Optional<DynamicType> DynType =
  5847. ComputeDynamicType(Info, E, Result, AK_TypeId);
  5848. if (!DynType)
  5849. return false;
  5850. TypeInfo =
  5851. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  5852. }
  5853. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  5854. }
  5855. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  5856. return Success(E);
  5857. }
  5858. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  5859. // Handle static data members.
  5860. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  5861. VisitIgnoredBaseExpression(E->getBase());
  5862. return VisitVarDecl(E, VD);
  5863. }
  5864. // Handle static member functions.
  5865. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  5866. if (MD->isStatic()) {
  5867. VisitIgnoredBaseExpression(E->getBase());
  5868. return Success(MD);
  5869. }
  5870. }
  5871. // Handle non-static data members.
  5872. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  5873. }
  5874. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  5875. // FIXME: Deal with vectors as array subscript bases.
  5876. if (E->getBase()->getType()->isVectorType())
  5877. return Error(E);
  5878. bool Success = true;
  5879. if (!evaluatePointer(E->getBase(), Result)) {
  5880. if (!Info.noteFailure())
  5881. return false;
  5882. Success = false;
  5883. }
  5884. APSInt Index;
  5885. if (!EvaluateInteger(E->getIdx(), Index, Info))
  5886. return false;
  5887. return Success &&
  5888. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  5889. }
  5890. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  5891. return evaluatePointer(E->getSubExpr(), Result);
  5892. }
  5893. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  5894. if (!Visit(E->getSubExpr()))
  5895. return false;
  5896. // __real is a no-op on scalar lvalues.
  5897. if (E->getSubExpr()->getType()->isAnyComplexType())
  5898. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  5899. return true;
  5900. }
  5901. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  5902. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  5903. "lvalue __imag__ on scalar?");
  5904. if (!Visit(E->getSubExpr()))
  5905. return false;
  5906. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  5907. return true;
  5908. }
  5909. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  5910. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5911. return Error(UO);
  5912. if (!this->Visit(UO->getSubExpr()))
  5913. return false;
  5914. return handleIncDec(
  5915. this->Info, UO, Result, UO->getSubExpr()->getType(),
  5916. UO->isIncrementOp(), nullptr);
  5917. }
  5918. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  5919. const CompoundAssignOperator *CAO) {
  5920. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5921. return Error(CAO);
  5922. APValue RHS;
  5923. // The overall lvalue result is the result of evaluating the LHS.
  5924. if (!this->Visit(CAO->getLHS())) {
  5925. if (Info.noteFailure())
  5926. Evaluate(RHS, this->Info, CAO->getRHS());
  5927. return false;
  5928. }
  5929. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  5930. return false;
  5931. return handleCompoundAssignment(
  5932. this->Info, CAO,
  5933. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  5934. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  5935. }
  5936. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  5937. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5938. return Error(E);
  5939. APValue NewVal;
  5940. if (!this->Visit(E->getLHS())) {
  5941. if (Info.noteFailure())
  5942. Evaluate(NewVal, this->Info, E->getRHS());
  5943. return false;
  5944. }
  5945. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  5946. return false;
  5947. if (Info.getLangOpts().CPlusPlus2a &&
  5948. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  5949. return false;
  5950. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  5951. NewVal);
  5952. }
  5953. //===----------------------------------------------------------------------===//
  5954. // Pointer Evaluation
  5955. //===----------------------------------------------------------------------===//
  5956. /// Attempts to compute the number of bytes available at the pointer
  5957. /// returned by a function with the alloc_size attribute. Returns true if we
  5958. /// were successful. Places an unsigned number into `Result`.
  5959. ///
  5960. /// This expects the given CallExpr to be a call to a function with an
  5961. /// alloc_size attribute.
  5962. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5963. const CallExpr *Call,
  5964. llvm::APInt &Result) {
  5965. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  5966. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  5967. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  5968. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  5969. if (Call->getNumArgs() <= SizeArgNo)
  5970. return false;
  5971. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  5972. Expr::EvalResult ExprResult;
  5973. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  5974. return false;
  5975. Into = ExprResult.Val.getInt();
  5976. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  5977. return false;
  5978. Into = Into.zextOrSelf(BitsInSizeT);
  5979. return true;
  5980. };
  5981. APSInt SizeOfElem;
  5982. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  5983. return false;
  5984. if (!AllocSize->getNumElemsParam().isValid()) {
  5985. Result = std::move(SizeOfElem);
  5986. return true;
  5987. }
  5988. APSInt NumberOfElems;
  5989. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  5990. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  5991. return false;
  5992. bool Overflow;
  5993. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  5994. if (Overflow)
  5995. return false;
  5996. Result = std::move(BytesAvailable);
  5997. return true;
  5998. }
  5999. /// Convenience function. LVal's base must be a call to an alloc_size
  6000. /// function.
  6001. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6002. const LValue &LVal,
  6003. llvm::APInt &Result) {
  6004. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6005. "Can't get the size of a non alloc_size function");
  6006. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  6007. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  6008. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  6009. }
  6010. /// Attempts to evaluate the given LValueBase as the result of a call to
  6011. /// a function with the alloc_size attribute. If it was possible to do so, this
  6012. /// function will return true, make Result's Base point to said function call,
  6013. /// and mark Result's Base as invalid.
  6014. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  6015. LValue &Result) {
  6016. if (Base.isNull())
  6017. return false;
  6018. // Because we do no form of static analysis, we only support const variables.
  6019. //
  6020. // Additionally, we can't support parameters, nor can we support static
  6021. // variables (in the latter case, use-before-assign isn't UB; in the former,
  6022. // we have no clue what they'll be assigned to).
  6023. const auto *VD =
  6024. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  6025. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  6026. return false;
  6027. const Expr *Init = VD->getAnyInitializer();
  6028. if (!Init)
  6029. return false;
  6030. const Expr *E = Init->IgnoreParens();
  6031. if (!tryUnwrapAllocSizeCall(E))
  6032. return false;
  6033. // Store E instead of E unwrapped so that the type of the LValue's base is
  6034. // what the user wanted.
  6035. Result.setInvalid(E);
  6036. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  6037. Result.addUnsizedArray(Info, E, Pointee);
  6038. return true;
  6039. }
  6040. namespace {
  6041. class PointerExprEvaluator
  6042. : public ExprEvaluatorBase<PointerExprEvaluator> {
  6043. LValue &Result;
  6044. bool InvalidBaseOK;
  6045. bool Success(const Expr *E) {
  6046. Result.set(E);
  6047. return true;
  6048. }
  6049. bool evaluateLValue(const Expr *E, LValue &Result) {
  6050. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  6051. }
  6052. bool evaluatePointer(const Expr *E, LValue &Result) {
  6053. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  6054. }
  6055. bool visitNonBuiltinCallExpr(const CallExpr *E);
  6056. public:
  6057. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  6058. : ExprEvaluatorBaseTy(info), Result(Result),
  6059. InvalidBaseOK(InvalidBaseOK) {}
  6060. bool Success(const APValue &V, const Expr *E) {
  6061. Result.setFrom(Info.Ctx, V);
  6062. return true;
  6063. }
  6064. bool ZeroInitialization(const Expr *E) {
  6065. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  6066. Result.setNull(E->getType(), TargetVal);
  6067. return true;
  6068. }
  6069. bool VisitBinaryOperator(const BinaryOperator *E);
  6070. bool VisitCastExpr(const CastExpr* E);
  6071. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6072. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  6073. { return Success(E); }
  6074. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  6075. if (E->isExpressibleAsConstantInitializer())
  6076. return Success(E);
  6077. if (Info.noteFailure())
  6078. EvaluateIgnoredValue(Info, E->getSubExpr());
  6079. return Error(E);
  6080. }
  6081. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  6082. { return Success(E); }
  6083. bool VisitCallExpr(const CallExpr *E);
  6084. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6085. bool VisitBlockExpr(const BlockExpr *E) {
  6086. if (!E->getBlockDecl()->hasCaptures())
  6087. return Success(E);
  6088. return Error(E);
  6089. }
  6090. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  6091. // Can't look at 'this' when checking a potential constant expression.
  6092. if (Info.checkingPotentialConstantExpression())
  6093. return false;
  6094. if (!Info.CurrentCall->This) {
  6095. if (Info.getLangOpts().CPlusPlus11)
  6096. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  6097. else
  6098. Info.FFDiag(E);
  6099. return false;
  6100. }
  6101. Result = *Info.CurrentCall->This;
  6102. // If we are inside a lambda's call operator, the 'this' expression refers
  6103. // to the enclosing '*this' object (either by value or reference) which is
  6104. // either copied into the closure object's field that represents the '*this'
  6105. // or refers to '*this'.
  6106. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  6107. // Update 'Result' to refer to the data member/field of the closure object
  6108. // that represents the '*this' capture.
  6109. if (!HandleLValueMember(Info, E, Result,
  6110. Info.CurrentCall->LambdaThisCaptureField))
  6111. return false;
  6112. // If we captured '*this' by reference, replace the field with its referent.
  6113. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  6114. ->isPointerType()) {
  6115. APValue RVal;
  6116. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  6117. RVal))
  6118. return false;
  6119. Result.setFrom(Info.Ctx, RVal);
  6120. }
  6121. }
  6122. return true;
  6123. }
  6124. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  6125. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  6126. APValue LValResult = E->EvaluateInContext(
  6127. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  6128. Result.setFrom(Info.Ctx, LValResult);
  6129. return true;
  6130. }
  6131. // FIXME: Missing: @protocol, @selector
  6132. };
  6133. } // end anonymous namespace
  6134. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  6135. bool InvalidBaseOK) {
  6136. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6137. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6138. }
  6139. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6140. if (E->getOpcode() != BO_Add &&
  6141. E->getOpcode() != BO_Sub)
  6142. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6143. const Expr *PExp = E->getLHS();
  6144. const Expr *IExp = E->getRHS();
  6145. if (IExp->getType()->isPointerType())
  6146. std::swap(PExp, IExp);
  6147. bool EvalPtrOK = evaluatePointer(PExp, Result);
  6148. if (!EvalPtrOK && !Info.noteFailure())
  6149. return false;
  6150. llvm::APSInt Offset;
  6151. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  6152. return false;
  6153. if (E->getOpcode() == BO_Sub)
  6154. negateAsSigned(Offset);
  6155. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  6156. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  6157. }
  6158. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6159. return evaluateLValue(E->getSubExpr(), Result);
  6160. }
  6161. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6162. const Expr *SubExpr = E->getSubExpr();
  6163. switch (E->getCastKind()) {
  6164. default:
  6165. break;
  6166. case CK_BitCast:
  6167. case CK_CPointerToObjCPointerCast:
  6168. case CK_BlockPointerToObjCPointerCast:
  6169. case CK_AnyPointerToBlockPointerCast:
  6170. case CK_AddressSpaceConversion:
  6171. if (!Visit(SubExpr))
  6172. return false;
  6173. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  6174. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  6175. // also static_casts, but we disallow them as a resolution to DR1312.
  6176. if (!E->getType()->isVoidPointerType()) {
  6177. Result.Designator.setInvalid();
  6178. if (SubExpr->getType()->isVoidPointerType())
  6179. CCEDiag(E, diag::note_constexpr_invalid_cast)
  6180. << 3 << SubExpr->getType();
  6181. else
  6182. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6183. }
  6184. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  6185. ZeroInitialization(E);
  6186. return true;
  6187. case CK_DerivedToBase:
  6188. case CK_UncheckedDerivedToBase:
  6189. if (!evaluatePointer(E->getSubExpr(), Result))
  6190. return false;
  6191. if (!Result.Base && Result.Offset.isZero())
  6192. return true;
  6193. // Now figure out the necessary offset to add to the base LV to get from
  6194. // the derived class to the base class.
  6195. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  6196. castAs<PointerType>()->getPointeeType(),
  6197. Result);
  6198. case CK_BaseToDerived:
  6199. if (!Visit(E->getSubExpr()))
  6200. return false;
  6201. if (!Result.Base && Result.Offset.isZero())
  6202. return true;
  6203. return HandleBaseToDerivedCast(Info, E, Result);
  6204. case CK_Dynamic:
  6205. if (!Visit(E->getSubExpr()))
  6206. return false;
  6207. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6208. case CK_NullToPointer:
  6209. VisitIgnoredValue(E->getSubExpr());
  6210. return ZeroInitialization(E);
  6211. case CK_IntegralToPointer: {
  6212. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6213. APValue Value;
  6214. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  6215. break;
  6216. if (Value.isInt()) {
  6217. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  6218. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  6219. Result.Base = (Expr*)nullptr;
  6220. Result.InvalidBase = false;
  6221. Result.Offset = CharUnits::fromQuantity(N);
  6222. Result.Designator.setInvalid();
  6223. Result.IsNullPtr = false;
  6224. return true;
  6225. } else {
  6226. // Cast is of an lvalue, no need to change value.
  6227. Result.setFrom(Info.Ctx, Value);
  6228. return true;
  6229. }
  6230. }
  6231. case CK_ArrayToPointerDecay: {
  6232. if (SubExpr->isGLValue()) {
  6233. if (!evaluateLValue(SubExpr, Result))
  6234. return false;
  6235. } else {
  6236. APValue &Value = createTemporary(SubExpr, false, Result,
  6237. *Info.CurrentCall);
  6238. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  6239. return false;
  6240. }
  6241. // The result is a pointer to the first element of the array.
  6242. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  6243. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  6244. Result.addArray(Info, E, CAT);
  6245. else
  6246. Result.addUnsizedArray(Info, E, AT->getElementType());
  6247. return true;
  6248. }
  6249. case CK_FunctionToPointerDecay:
  6250. return evaluateLValue(SubExpr, Result);
  6251. case CK_LValueToRValue: {
  6252. LValue LVal;
  6253. if (!evaluateLValue(E->getSubExpr(), LVal))
  6254. return false;
  6255. APValue RVal;
  6256. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6257. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6258. LVal, RVal))
  6259. return InvalidBaseOK &&
  6260. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  6261. return Success(RVal, E);
  6262. }
  6263. }
  6264. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6265. }
  6266. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  6267. UnaryExprOrTypeTrait ExprKind) {
  6268. // C++ [expr.alignof]p3:
  6269. // When alignof is applied to a reference type, the result is the
  6270. // alignment of the referenced type.
  6271. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  6272. T = Ref->getPointeeType();
  6273. if (T.getQualifiers().hasUnaligned())
  6274. return CharUnits::One();
  6275. const bool AlignOfReturnsPreferred =
  6276. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  6277. // __alignof is defined to return the preferred alignment.
  6278. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  6279. // as well.
  6280. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  6281. return Info.Ctx.toCharUnitsFromBits(
  6282. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  6283. // alignof and _Alignof are defined to return the ABI alignment.
  6284. else if (ExprKind == UETT_AlignOf)
  6285. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  6286. else
  6287. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  6288. }
  6289. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  6290. UnaryExprOrTypeTrait ExprKind) {
  6291. E = E->IgnoreParens();
  6292. // The kinds of expressions that we have special-case logic here for
  6293. // should be kept up to date with the special checks for those
  6294. // expressions in Sema.
  6295. // alignof decl is always accepted, even if it doesn't make sense: we default
  6296. // to 1 in those cases.
  6297. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6298. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  6299. /*RefAsPointee*/true);
  6300. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  6301. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  6302. /*RefAsPointee*/true);
  6303. return GetAlignOfType(Info, E->getType(), ExprKind);
  6304. }
  6305. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  6306. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  6307. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  6308. return true;
  6309. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  6310. return false;
  6311. Result.setInvalid(E);
  6312. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  6313. Result.addUnsizedArray(Info, E, PointeeTy);
  6314. return true;
  6315. }
  6316. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6317. if (IsStringLiteralCall(E))
  6318. return Success(E);
  6319. if (unsigned BuiltinOp = E->getBuiltinCallee())
  6320. return VisitBuiltinCallExpr(E, BuiltinOp);
  6321. return visitNonBuiltinCallExpr(E);
  6322. }
  6323. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  6324. unsigned BuiltinOp) {
  6325. switch (BuiltinOp) {
  6326. case Builtin::BI__builtin_addressof:
  6327. return evaluateLValue(E->getArg(0), Result);
  6328. case Builtin::BI__builtin_assume_aligned: {
  6329. // We need to be very careful here because: if the pointer does not have the
  6330. // asserted alignment, then the behavior is undefined, and undefined
  6331. // behavior is non-constant.
  6332. if (!evaluatePointer(E->getArg(0), Result))
  6333. return false;
  6334. LValue OffsetResult(Result);
  6335. APSInt Alignment;
  6336. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  6337. return false;
  6338. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  6339. if (E->getNumArgs() > 2) {
  6340. APSInt Offset;
  6341. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  6342. return false;
  6343. int64_t AdditionalOffset = -Offset.getZExtValue();
  6344. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  6345. }
  6346. // If there is a base object, then it must have the correct alignment.
  6347. if (OffsetResult.Base) {
  6348. CharUnits BaseAlignment;
  6349. if (const ValueDecl *VD =
  6350. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  6351. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  6352. } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
  6353. BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
  6354. } else {
  6355. BaseAlignment = GetAlignOfType(
  6356. Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
  6357. }
  6358. if (BaseAlignment < Align) {
  6359. Result.Designator.setInvalid();
  6360. // FIXME: Add support to Diagnostic for long / long long.
  6361. CCEDiag(E->getArg(0),
  6362. diag::note_constexpr_baa_insufficient_alignment) << 0
  6363. << (unsigned)BaseAlignment.getQuantity()
  6364. << (unsigned)Align.getQuantity();
  6365. return false;
  6366. }
  6367. }
  6368. // The offset must also have the correct alignment.
  6369. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  6370. Result.Designator.setInvalid();
  6371. (OffsetResult.Base
  6372. ? CCEDiag(E->getArg(0),
  6373. diag::note_constexpr_baa_insufficient_alignment) << 1
  6374. : CCEDiag(E->getArg(0),
  6375. diag::note_constexpr_baa_value_insufficient_alignment))
  6376. << (int)OffsetResult.Offset.getQuantity()
  6377. << (unsigned)Align.getQuantity();
  6378. return false;
  6379. }
  6380. return true;
  6381. }
  6382. case Builtin::BI__builtin_launder:
  6383. return evaluatePointer(E->getArg(0), Result);
  6384. case Builtin::BIstrchr:
  6385. case Builtin::BIwcschr:
  6386. case Builtin::BImemchr:
  6387. case Builtin::BIwmemchr:
  6388. if (Info.getLangOpts().CPlusPlus11)
  6389. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6390. << /*isConstexpr*/0 << /*isConstructor*/0
  6391. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6392. else
  6393. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6394. LLVM_FALLTHROUGH;
  6395. case Builtin::BI__builtin_strchr:
  6396. case Builtin::BI__builtin_wcschr:
  6397. case Builtin::BI__builtin_memchr:
  6398. case Builtin::BI__builtin_char_memchr:
  6399. case Builtin::BI__builtin_wmemchr: {
  6400. if (!Visit(E->getArg(0)))
  6401. return false;
  6402. APSInt Desired;
  6403. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  6404. return false;
  6405. uint64_t MaxLength = uint64_t(-1);
  6406. if (BuiltinOp != Builtin::BIstrchr &&
  6407. BuiltinOp != Builtin::BIwcschr &&
  6408. BuiltinOp != Builtin::BI__builtin_strchr &&
  6409. BuiltinOp != Builtin::BI__builtin_wcschr) {
  6410. APSInt N;
  6411. if (!EvaluateInteger(E->getArg(2), N, Info))
  6412. return false;
  6413. MaxLength = N.getExtValue();
  6414. }
  6415. // We cannot find the value if there are no candidates to match against.
  6416. if (MaxLength == 0u)
  6417. return ZeroInitialization(E);
  6418. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  6419. Result.Designator.Invalid)
  6420. return false;
  6421. QualType CharTy = Result.Designator.getType(Info.Ctx);
  6422. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  6423. BuiltinOp == Builtin::BI__builtin_memchr;
  6424. assert(IsRawByte ||
  6425. Info.Ctx.hasSameUnqualifiedType(
  6426. CharTy, E->getArg(0)->getType()->getPointeeType()));
  6427. // Pointers to const void may point to objects of incomplete type.
  6428. if (IsRawByte && CharTy->isIncompleteType()) {
  6429. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  6430. return false;
  6431. }
  6432. // Give up on byte-oriented matching against multibyte elements.
  6433. // FIXME: We can compare the bytes in the correct order.
  6434. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  6435. return false;
  6436. // Figure out what value we're actually looking for (after converting to
  6437. // the corresponding unsigned type if necessary).
  6438. uint64_t DesiredVal;
  6439. bool StopAtNull = false;
  6440. switch (BuiltinOp) {
  6441. case Builtin::BIstrchr:
  6442. case Builtin::BI__builtin_strchr:
  6443. // strchr compares directly to the passed integer, and therefore
  6444. // always fails if given an int that is not a char.
  6445. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  6446. E->getArg(1)->getType(),
  6447. Desired),
  6448. Desired))
  6449. return ZeroInitialization(E);
  6450. StopAtNull = true;
  6451. LLVM_FALLTHROUGH;
  6452. case Builtin::BImemchr:
  6453. case Builtin::BI__builtin_memchr:
  6454. case Builtin::BI__builtin_char_memchr:
  6455. // memchr compares by converting both sides to unsigned char. That's also
  6456. // correct for strchr if we get this far (to cope with plain char being
  6457. // unsigned in the strchr case).
  6458. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  6459. break;
  6460. case Builtin::BIwcschr:
  6461. case Builtin::BI__builtin_wcschr:
  6462. StopAtNull = true;
  6463. LLVM_FALLTHROUGH;
  6464. case Builtin::BIwmemchr:
  6465. case Builtin::BI__builtin_wmemchr:
  6466. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  6467. DesiredVal = Desired.getZExtValue();
  6468. break;
  6469. }
  6470. for (; MaxLength; --MaxLength) {
  6471. APValue Char;
  6472. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  6473. !Char.isInt())
  6474. return false;
  6475. if (Char.getInt().getZExtValue() == DesiredVal)
  6476. return true;
  6477. if (StopAtNull && !Char.getInt())
  6478. break;
  6479. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  6480. return false;
  6481. }
  6482. // Not found: return nullptr.
  6483. return ZeroInitialization(E);
  6484. }
  6485. case Builtin::BImemcpy:
  6486. case Builtin::BImemmove:
  6487. case Builtin::BIwmemcpy:
  6488. case Builtin::BIwmemmove:
  6489. if (Info.getLangOpts().CPlusPlus11)
  6490. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6491. << /*isConstexpr*/0 << /*isConstructor*/0
  6492. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6493. else
  6494. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6495. LLVM_FALLTHROUGH;
  6496. case Builtin::BI__builtin_memcpy:
  6497. case Builtin::BI__builtin_memmove:
  6498. case Builtin::BI__builtin_wmemcpy:
  6499. case Builtin::BI__builtin_wmemmove: {
  6500. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  6501. BuiltinOp == Builtin::BIwmemmove ||
  6502. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  6503. BuiltinOp == Builtin::BI__builtin_wmemmove;
  6504. bool Move = BuiltinOp == Builtin::BImemmove ||
  6505. BuiltinOp == Builtin::BIwmemmove ||
  6506. BuiltinOp == Builtin::BI__builtin_memmove ||
  6507. BuiltinOp == Builtin::BI__builtin_wmemmove;
  6508. // The result of mem* is the first argument.
  6509. if (!Visit(E->getArg(0)))
  6510. return false;
  6511. LValue Dest = Result;
  6512. LValue Src;
  6513. if (!EvaluatePointer(E->getArg(1), Src, Info))
  6514. return false;
  6515. APSInt N;
  6516. if (!EvaluateInteger(E->getArg(2), N, Info))
  6517. return false;
  6518. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  6519. // If the size is zero, we treat this as always being a valid no-op.
  6520. // (Even if one of the src and dest pointers is null.)
  6521. if (!N)
  6522. return true;
  6523. // Otherwise, if either of the operands is null, we can't proceed. Don't
  6524. // try to determine the type of the copied objects, because there aren't
  6525. // any.
  6526. if (!Src.Base || !Dest.Base) {
  6527. APValue Val;
  6528. (!Src.Base ? Src : Dest).moveInto(Val);
  6529. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  6530. << Move << WChar << !!Src.Base
  6531. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  6532. return false;
  6533. }
  6534. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  6535. return false;
  6536. // We require that Src and Dest are both pointers to arrays of
  6537. // trivially-copyable type. (For the wide version, the designator will be
  6538. // invalid if the designated object is not a wchar_t.)
  6539. QualType T = Dest.Designator.getType(Info.Ctx);
  6540. QualType SrcT = Src.Designator.getType(Info.Ctx);
  6541. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  6542. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  6543. return false;
  6544. }
  6545. if (T->isIncompleteType()) {
  6546. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  6547. return false;
  6548. }
  6549. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  6550. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  6551. return false;
  6552. }
  6553. // Figure out how many T's we're copying.
  6554. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  6555. if (!WChar) {
  6556. uint64_t Remainder;
  6557. llvm::APInt OrigN = N;
  6558. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  6559. if (Remainder) {
  6560. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  6561. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  6562. << (unsigned)TSize;
  6563. return false;
  6564. }
  6565. }
  6566. // Check that the copying will remain within the arrays, just so that we
  6567. // can give a more meaningful diagnostic. This implicitly also checks that
  6568. // N fits into 64 bits.
  6569. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  6570. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  6571. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  6572. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  6573. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  6574. << N.toString(10, /*Signed*/false);
  6575. return false;
  6576. }
  6577. uint64_t NElems = N.getZExtValue();
  6578. uint64_t NBytes = NElems * TSize;
  6579. // Check for overlap.
  6580. int Direction = 1;
  6581. if (HasSameBase(Src, Dest)) {
  6582. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  6583. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  6584. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  6585. // Dest is inside the source region.
  6586. if (!Move) {
  6587. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  6588. return false;
  6589. }
  6590. // For memmove and friends, copy backwards.
  6591. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  6592. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  6593. return false;
  6594. Direction = -1;
  6595. } else if (!Move && SrcOffset >= DestOffset &&
  6596. SrcOffset - DestOffset < NBytes) {
  6597. // Src is inside the destination region for memcpy: invalid.
  6598. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  6599. return false;
  6600. }
  6601. }
  6602. while (true) {
  6603. APValue Val;
  6604. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  6605. !handleAssignment(Info, E, Dest, T, Val))
  6606. return false;
  6607. // Do not iterate past the last element; if we're copying backwards, that
  6608. // might take us off the start of the array.
  6609. if (--NElems == 0)
  6610. return true;
  6611. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  6612. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  6613. return false;
  6614. }
  6615. }
  6616. default:
  6617. return visitNonBuiltinCallExpr(E);
  6618. }
  6619. }
  6620. //===----------------------------------------------------------------------===//
  6621. // Member Pointer Evaluation
  6622. //===----------------------------------------------------------------------===//
  6623. namespace {
  6624. class MemberPointerExprEvaluator
  6625. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  6626. MemberPtr &Result;
  6627. bool Success(const ValueDecl *D) {
  6628. Result = MemberPtr(D);
  6629. return true;
  6630. }
  6631. public:
  6632. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  6633. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  6634. bool Success(const APValue &V, const Expr *E) {
  6635. Result.setFrom(V);
  6636. return true;
  6637. }
  6638. bool ZeroInitialization(const Expr *E) {
  6639. return Success((const ValueDecl*)nullptr);
  6640. }
  6641. bool VisitCastExpr(const CastExpr *E);
  6642. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6643. };
  6644. } // end anonymous namespace
  6645. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  6646. EvalInfo &Info) {
  6647. assert(E->isRValue() && E->getType()->isMemberPointerType());
  6648. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  6649. }
  6650. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6651. switch (E->getCastKind()) {
  6652. default:
  6653. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6654. case CK_NullToMemberPointer:
  6655. VisitIgnoredValue(E->getSubExpr());
  6656. return ZeroInitialization(E);
  6657. case CK_BaseToDerivedMemberPointer: {
  6658. if (!Visit(E->getSubExpr()))
  6659. return false;
  6660. if (E->path_empty())
  6661. return true;
  6662. // Base-to-derived member pointer casts store the path in derived-to-base
  6663. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  6664. // the wrong end of the derived->base arc, so stagger the path by one class.
  6665. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  6666. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  6667. PathI != PathE; ++PathI) {
  6668. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  6669. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  6670. if (!Result.castToDerived(Derived))
  6671. return Error(E);
  6672. }
  6673. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  6674. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  6675. return Error(E);
  6676. return true;
  6677. }
  6678. case CK_DerivedToBaseMemberPointer:
  6679. if (!Visit(E->getSubExpr()))
  6680. return false;
  6681. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  6682. PathE = E->path_end(); PathI != PathE; ++PathI) {
  6683. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  6684. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  6685. if (!Result.castToBase(Base))
  6686. return Error(E);
  6687. }
  6688. return true;
  6689. }
  6690. }
  6691. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6692. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  6693. // member can be formed.
  6694. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  6695. }
  6696. //===----------------------------------------------------------------------===//
  6697. // Record Evaluation
  6698. //===----------------------------------------------------------------------===//
  6699. namespace {
  6700. class RecordExprEvaluator
  6701. : public ExprEvaluatorBase<RecordExprEvaluator> {
  6702. const LValue &This;
  6703. APValue &Result;
  6704. public:
  6705. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  6706. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  6707. bool Success(const APValue &V, const Expr *E) {
  6708. Result = V;
  6709. return true;
  6710. }
  6711. bool ZeroInitialization(const Expr *E) {
  6712. return ZeroInitialization(E, E->getType());
  6713. }
  6714. bool ZeroInitialization(const Expr *E, QualType T);
  6715. bool VisitCallExpr(const CallExpr *E) {
  6716. return handleCallExpr(E, Result, &This);
  6717. }
  6718. bool VisitCastExpr(const CastExpr *E);
  6719. bool VisitInitListExpr(const InitListExpr *E);
  6720. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6721. return VisitCXXConstructExpr(E, E->getType());
  6722. }
  6723. bool VisitLambdaExpr(const LambdaExpr *E);
  6724. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  6725. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  6726. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  6727. bool VisitBinCmp(const BinaryOperator *E);
  6728. };
  6729. }
  6730. /// Perform zero-initialization on an object of non-union class type.
  6731. /// C++11 [dcl.init]p5:
  6732. /// To zero-initialize an object or reference of type T means:
  6733. /// [...]
  6734. /// -- if T is a (possibly cv-qualified) non-union class type,
  6735. /// each non-static data member and each base-class subobject is
  6736. /// zero-initialized
  6737. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  6738. const RecordDecl *RD,
  6739. const LValue &This, APValue &Result) {
  6740. assert(!RD->isUnion() && "Expected non-union class type");
  6741. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  6742. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  6743. std::distance(RD->field_begin(), RD->field_end()));
  6744. if (RD->isInvalidDecl()) return false;
  6745. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6746. if (CD) {
  6747. unsigned Index = 0;
  6748. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  6749. End = CD->bases_end(); I != End; ++I, ++Index) {
  6750. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  6751. LValue Subobject = This;
  6752. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  6753. return false;
  6754. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  6755. Result.getStructBase(Index)))
  6756. return false;
  6757. }
  6758. }
  6759. for (const auto *I : RD->fields()) {
  6760. // -- if T is a reference type, no initialization is performed.
  6761. if (I->getType()->isReferenceType())
  6762. continue;
  6763. LValue Subobject = This;
  6764. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  6765. return false;
  6766. ImplicitValueInitExpr VIE(I->getType());
  6767. if (!EvaluateInPlace(
  6768. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  6769. return false;
  6770. }
  6771. return true;
  6772. }
  6773. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  6774. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  6775. if (RD->isInvalidDecl()) return false;
  6776. if (RD->isUnion()) {
  6777. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  6778. // object's first non-static named data member is zero-initialized
  6779. RecordDecl::field_iterator I = RD->field_begin();
  6780. if (I == RD->field_end()) {
  6781. Result = APValue((const FieldDecl*)nullptr);
  6782. return true;
  6783. }
  6784. LValue Subobject = This;
  6785. if (!HandleLValueMember(Info, E, Subobject, *I))
  6786. return false;
  6787. Result = APValue(*I);
  6788. ImplicitValueInitExpr VIE(I->getType());
  6789. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  6790. }
  6791. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  6792. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  6793. return false;
  6794. }
  6795. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  6796. }
  6797. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6798. switch (E->getCastKind()) {
  6799. default:
  6800. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6801. case CK_ConstructorConversion:
  6802. return Visit(E->getSubExpr());
  6803. case CK_DerivedToBase:
  6804. case CK_UncheckedDerivedToBase: {
  6805. APValue DerivedObject;
  6806. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  6807. return false;
  6808. if (!DerivedObject.isStruct())
  6809. return Error(E->getSubExpr());
  6810. // Derived-to-base rvalue conversion: just slice off the derived part.
  6811. APValue *Value = &DerivedObject;
  6812. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  6813. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  6814. PathE = E->path_end(); PathI != PathE; ++PathI) {
  6815. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  6816. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  6817. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  6818. RD = Base;
  6819. }
  6820. Result = *Value;
  6821. return true;
  6822. }
  6823. }
  6824. }
  6825. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6826. if (E->isTransparent())
  6827. return Visit(E->getInit(0));
  6828. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  6829. if (RD->isInvalidDecl()) return false;
  6830. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6831. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  6832. EvalInfo::EvaluatingConstructorRAII EvalObj(
  6833. Info,
  6834. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  6835. CXXRD && CXXRD->getNumBases());
  6836. if (RD->isUnion()) {
  6837. const FieldDecl *Field = E->getInitializedFieldInUnion();
  6838. Result = APValue(Field);
  6839. if (!Field)
  6840. return true;
  6841. // If the initializer list for a union does not contain any elements, the
  6842. // first element of the union is value-initialized.
  6843. // FIXME: The element should be initialized from an initializer list.
  6844. // Is this difference ever observable for initializer lists which
  6845. // we don't build?
  6846. ImplicitValueInitExpr VIE(Field->getType());
  6847. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  6848. LValue Subobject = This;
  6849. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  6850. return false;
  6851. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  6852. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  6853. isa<CXXDefaultInitExpr>(InitExpr));
  6854. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  6855. }
  6856. if (!Result.hasValue())
  6857. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  6858. std::distance(RD->field_begin(), RD->field_end()));
  6859. unsigned ElementNo = 0;
  6860. bool Success = true;
  6861. // Initialize base classes.
  6862. if (CXXRD && CXXRD->getNumBases()) {
  6863. for (const auto &Base : CXXRD->bases()) {
  6864. assert(ElementNo < E->getNumInits() && "missing init for base class");
  6865. const Expr *Init = E->getInit(ElementNo);
  6866. LValue Subobject = This;
  6867. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  6868. return false;
  6869. APValue &FieldVal = Result.getStructBase(ElementNo);
  6870. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  6871. if (!Info.noteFailure())
  6872. return false;
  6873. Success = false;
  6874. }
  6875. ++ElementNo;
  6876. }
  6877. EvalObj.finishedConstructingBases();
  6878. }
  6879. // Initialize members.
  6880. for (const auto *Field : RD->fields()) {
  6881. // Anonymous bit-fields are not considered members of the class for
  6882. // purposes of aggregate initialization.
  6883. if (Field->isUnnamedBitfield())
  6884. continue;
  6885. LValue Subobject = This;
  6886. bool HaveInit = ElementNo < E->getNumInits();
  6887. // FIXME: Diagnostics here should point to the end of the initializer
  6888. // list, not the start.
  6889. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  6890. Subobject, Field, &Layout))
  6891. return false;
  6892. // Perform an implicit value-initialization for members beyond the end of
  6893. // the initializer list.
  6894. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  6895. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  6896. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  6897. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  6898. isa<CXXDefaultInitExpr>(Init));
  6899. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  6900. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  6901. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  6902. FieldVal, Field))) {
  6903. if (!Info.noteFailure())
  6904. return false;
  6905. Success = false;
  6906. }
  6907. }
  6908. return Success;
  6909. }
  6910. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6911. QualType T) {
  6912. // Note that E's type is not necessarily the type of our class here; we might
  6913. // be initializing an array element instead.
  6914. const CXXConstructorDecl *FD = E->getConstructor();
  6915. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  6916. bool ZeroInit = E->requiresZeroInitialization();
  6917. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  6918. // If we've already performed zero-initialization, we're already done.
  6919. if (Result.hasValue())
  6920. return true;
  6921. // We can get here in two different ways:
  6922. // 1) We're performing value-initialization, and should zero-initialize
  6923. // the object, or
  6924. // 2) We're performing default-initialization of an object with a trivial
  6925. // constexpr default constructor, in which case we should start the
  6926. // lifetimes of all the base subobjects (there can be no data member
  6927. // subobjects in this case) per [basic.life]p1.
  6928. // Either way, ZeroInitialization is appropriate.
  6929. return ZeroInitialization(E, T);
  6930. }
  6931. const FunctionDecl *Definition = nullptr;
  6932. auto Body = FD->getBody(Definition);
  6933. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  6934. return false;
  6935. // Avoid materializing a temporary for an elidable copy/move constructor.
  6936. if (E->isElidable() && !ZeroInit)
  6937. if (const MaterializeTemporaryExpr *ME
  6938. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  6939. return Visit(ME->GetTemporaryExpr());
  6940. if (ZeroInit && !ZeroInitialization(E, T))
  6941. return false;
  6942. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  6943. return HandleConstructorCall(E, This, Args,
  6944. cast<CXXConstructorDecl>(Definition), Info,
  6945. Result);
  6946. }
  6947. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  6948. const CXXInheritedCtorInitExpr *E) {
  6949. if (!Info.CurrentCall) {
  6950. assert(Info.checkingPotentialConstantExpression());
  6951. return false;
  6952. }
  6953. const CXXConstructorDecl *FD = E->getConstructor();
  6954. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  6955. return false;
  6956. const FunctionDecl *Definition = nullptr;
  6957. auto Body = FD->getBody(Definition);
  6958. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  6959. return false;
  6960. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  6961. cast<CXXConstructorDecl>(Definition), Info,
  6962. Result);
  6963. }
  6964. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  6965. const CXXStdInitializerListExpr *E) {
  6966. const ConstantArrayType *ArrayType =
  6967. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  6968. LValue Array;
  6969. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  6970. return false;
  6971. // Get a pointer to the first element of the array.
  6972. Array.addArray(Info, E, ArrayType);
  6973. // FIXME: Perform the checks on the field types in SemaInit.
  6974. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  6975. RecordDecl::field_iterator Field = Record->field_begin();
  6976. if (Field == Record->field_end())
  6977. return Error(E);
  6978. // Start pointer.
  6979. if (!Field->getType()->isPointerType() ||
  6980. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  6981. ArrayType->getElementType()))
  6982. return Error(E);
  6983. // FIXME: What if the initializer_list type has base classes, etc?
  6984. Result = APValue(APValue::UninitStruct(), 0, 2);
  6985. Array.moveInto(Result.getStructField(0));
  6986. if (++Field == Record->field_end())
  6987. return Error(E);
  6988. if (Field->getType()->isPointerType() &&
  6989. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  6990. ArrayType->getElementType())) {
  6991. // End pointer.
  6992. if (!HandleLValueArrayAdjustment(Info, E, Array,
  6993. ArrayType->getElementType(),
  6994. ArrayType->getSize().getZExtValue()))
  6995. return false;
  6996. Array.moveInto(Result.getStructField(1));
  6997. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  6998. // Length.
  6999. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  7000. else
  7001. return Error(E);
  7002. if (++Field != Record->field_end())
  7003. return Error(E);
  7004. return true;
  7005. }
  7006. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  7007. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  7008. if (ClosureClass->isInvalidDecl()) return false;
  7009. if (Info.checkingPotentialConstantExpression()) return true;
  7010. const size_t NumFields =
  7011. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  7012. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  7013. E->capture_init_end()) &&
  7014. "The number of lambda capture initializers should equal the number of "
  7015. "fields within the closure type");
  7016. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  7017. // Iterate through all the lambda's closure object's fields and initialize
  7018. // them.
  7019. auto *CaptureInitIt = E->capture_init_begin();
  7020. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  7021. bool Success = true;
  7022. for (const auto *Field : ClosureClass->fields()) {
  7023. assert(CaptureInitIt != E->capture_init_end());
  7024. // Get the initializer for this field
  7025. Expr *const CurFieldInit = *CaptureInitIt++;
  7026. // If there is no initializer, either this is a VLA or an error has
  7027. // occurred.
  7028. if (!CurFieldInit)
  7029. return Error(E);
  7030. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7031. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  7032. if (!Info.keepEvaluatingAfterFailure())
  7033. return false;
  7034. Success = false;
  7035. }
  7036. ++CaptureIt;
  7037. }
  7038. return Success;
  7039. }
  7040. static bool EvaluateRecord(const Expr *E, const LValue &This,
  7041. APValue &Result, EvalInfo &Info) {
  7042. assert(E->isRValue() && E->getType()->isRecordType() &&
  7043. "can't evaluate expression as a record rvalue");
  7044. return RecordExprEvaluator(Info, This, Result).Visit(E);
  7045. }
  7046. //===----------------------------------------------------------------------===//
  7047. // Temporary Evaluation
  7048. //
  7049. // Temporaries are represented in the AST as rvalues, but generally behave like
  7050. // lvalues. The full-object of which the temporary is a subobject is implicitly
  7051. // materialized so that a reference can bind to it.
  7052. //===----------------------------------------------------------------------===//
  7053. namespace {
  7054. class TemporaryExprEvaluator
  7055. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  7056. public:
  7057. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  7058. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  7059. /// Visit an expression which constructs the value of this temporary.
  7060. bool VisitConstructExpr(const Expr *E) {
  7061. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  7062. return EvaluateInPlace(Value, Info, Result, E);
  7063. }
  7064. bool VisitCastExpr(const CastExpr *E) {
  7065. switch (E->getCastKind()) {
  7066. default:
  7067. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  7068. case CK_ConstructorConversion:
  7069. return VisitConstructExpr(E->getSubExpr());
  7070. }
  7071. }
  7072. bool VisitInitListExpr(const InitListExpr *E) {
  7073. return VisitConstructExpr(E);
  7074. }
  7075. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7076. return VisitConstructExpr(E);
  7077. }
  7078. bool VisitCallExpr(const CallExpr *E) {
  7079. return VisitConstructExpr(E);
  7080. }
  7081. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  7082. return VisitConstructExpr(E);
  7083. }
  7084. bool VisitLambdaExpr(const LambdaExpr *E) {
  7085. return VisitConstructExpr(E);
  7086. }
  7087. };
  7088. } // end anonymous namespace
  7089. /// Evaluate an expression of record type as a temporary.
  7090. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  7091. assert(E->isRValue() && E->getType()->isRecordType());
  7092. return TemporaryExprEvaluator(Info, Result).Visit(E);
  7093. }
  7094. //===----------------------------------------------------------------------===//
  7095. // Vector Evaluation
  7096. //===----------------------------------------------------------------------===//
  7097. namespace {
  7098. class VectorExprEvaluator
  7099. : public ExprEvaluatorBase<VectorExprEvaluator> {
  7100. APValue &Result;
  7101. public:
  7102. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  7103. : ExprEvaluatorBaseTy(info), Result(Result) {}
  7104. bool Success(ArrayRef<APValue> V, const Expr *E) {
  7105. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  7106. // FIXME: remove this APValue copy.
  7107. Result = APValue(V.data(), V.size());
  7108. return true;
  7109. }
  7110. bool Success(const APValue &V, const Expr *E) {
  7111. assert(V.isVector());
  7112. Result = V;
  7113. return true;
  7114. }
  7115. bool ZeroInitialization(const Expr *E);
  7116. bool VisitUnaryReal(const UnaryOperator *E)
  7117. { return Visit(E->getSubExpr()); }
  7118. bool VisitCastExpr(const CastExpr* E);
  7119. bool VisitInitListExpr(const InitListExpr *E);
  7120. bool VisitUnaryImag(const UnaryOperator *E);
  7121. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  7122. // binary comparisons, binary and/or/xor,
  7123. // shufflevector, ExtVectorElementExpr
  7124. };
  7125. } // end anonymous namespace
  7126. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  7127. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  7128. return VectorExprEvaluator(Info, Result).Visit(E);
  7129. }
  7130. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7131. const VectorType *VTy = E->getType()->castAs<VectorType>();
  7132. unsigned NElts = VTy->getNumElements();
  7133. const Expr *SE = E->getSubExpr();
  7134. QualType SETy = SE->getType();
  7135. switch (E->getCastKind()) {
  7136. case CK_VectorSplat: {
  7137. APValue Val = APValue();
  7138. if (SETy->isIntegerType()) {
  7139. APSInt IntResult;
  7140. if (!EvaluateInteger(SE, IntResult, Info))
  7141. return false;
  7142. Val = APValue(std::move(IntResult));
  7143. } else if (SETy->isRealFloatingType()) {
  7144. APFloat FloatResult(0.0);
  7145. if (!EvaluateFloat(SE, FloatResult, Info))
  7146. return false;
  7147. Val = APValue(std::move(FloatResult));
  7148. } else {
  7149. return Error(E);
  7150. }
  7151. // Splat and create vector APValue.
  7152. SmallVector<APValue, 4> Elts(NElts, Val);
  7153. return Success(Elts, E);
  7154. }
  7155. case CK_BitCast: {
  7156. // Evaluate the operand into an APInt we can extract from.
  7157. llvm::APInt SValInt;
  7158. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  7159. return false;
  7160. // Extract the elements
  7161. QualType EltTy = VTy->getElementType();
  7162. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  7163. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  7164. SmallVector<APValue, 4> Elts;
  7165. if (EltTy->isRealFloatingType()) {
  7166. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  7167. unsigned FloatEltSize = EltSize;
  7168. if (&Sem == &APFloat::x87DoubleExtended())
  7169. FloatEltSize = 80;
  7170. for (unsigned i = 0; i < NElts; i++) {
  7171. llvm::APInt Elt;
  7172. if (BigEndian)
  7173. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  7174. else
  7175. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  7176. Elts.push_back(APValue(APFloat(Sem, Elt)));
  7177. }
  7178. } else if (EltTy->isIntegerType()) {
  7179. for (unsigned i = 0; i < NElts; i++) {
  7180. llvm::APInt Elt;
  7181. if (BigEndian)
  7182. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  7183. else
  7184. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  7185. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  7186. }
  7187. } else {
  7188. return Error(E);
  7189. }
  7190. return Success(Elts, E);
  7191. }
  7192. default:
  7193. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7194. }
  7195. }
  7196. bool
  7197. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7198. const VectorType *VT = E->getType()->castAs<VectorType>();
  7199. unsigned NumInits = E->getNumInits();
  7200. unsigned NumElements = VT->getNumElements();
  7201. QualType EltTy = VT->getElementType();
  7202. SmallVector<APValue, 4> Elements;
  7203. // The number of initializers can be less than the number of
  7204. // vector elements. For OpenCL, this can be due to nested vector
  7205. // initialization. For GCC compatibility, missing trailing elements
  7206. // should be initialized with zeroes.
  7207. unsigned CountInits = 0, CountElts = 0;
  7208. while (CountElts < NumElements) {
  7209. // Handle nested vector initialization.
  7210. if (CountInits < NumInits
  7211. && E->getInit(CountInits)->getType()->isVectorType()) {
  7212. APValue v;
  7213. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  7214. return Error(E);
  7215. unsigned vlen = v.getVectorLength();
  7216. for (unsigned j = 0; j < vlen; j++)
  7217. Elements.push_back(v.getVectorElt(j));
  7218. CountElts += vlen;
  7219. } else if (EltTy->isIntegerType()) {
  7220. llvm::APSInt sInt(32);
  7221. if (CountInits < NumInits) {
  7222. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  7223. return false;
  7224. } else // trailing integer zero.
  7225. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  7226. Elements.push_back(APValue(sInt));
  7227. CountElts++;
  7228. } else {
  7229. llvm::APFloat f(0.0);
  7230. if (CountInits < NumInits) {
  7231. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  7232. return false;
  7233. } else // trailing float zero.
  7234. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  7235. Elements.push_back(APValue(f));
  7236. CountElts++;
  7237. }
  7238. CountInits++;
  7239. }
  7240. return Success(Elements, E);
  7241. }
  7242. bool
  7243. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  7244. const VectorType *VT = E->getType()->getAs<VectorType>();
  7245. QualType EltTy = VT->getElementType();
  7246. APValue ZeroElement;
  7247. if (EltTy->isIntegerType())
  7248. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  7249. else
  7250. ZeroElement =
  7251. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  7252. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  7253. return Success(Elements, E);
  7254. }
  7255. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7256. VisitIgnoredValue(E->getSubExpr());
  7257. return ZeroInitialization(E);
  7258. }
  7259. //===----------------------------------------------------------------------===//
  7260. // Array Evaluation
  7261. //===----------------------------------------------------------------------===//
  7262. namespace {
  7263. class ArrayExprEvaluator
  7264. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  7265. const LValue &This;
  7266. APValue &Result;
  7267. public:
  7268. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  7269. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  7270. bool Success(const APValue &V, const Expr *E) {
  7271. assert(V.isArray() && "expected array");
  7272. Result = V;
  7273. return true;
  7274. }
  7275. bool ZeroInitialization(const Expr *E) {
  7276. const ConstantArrayType *CAT =
  7277. Info.Ctx.getAsConstantArrayType(E->getType());
  7278. if (!CAT)
  7279. return Error(E);
  7280. Result = APValue(APValue::UninitArray(), 0,
  7281. CAT->getSize().getZExtValue());
  7282. if (!Result.hasArrayFiller()) return true;
  7283. // Zero-initialize all elements.
  7284. LValue Subobject = This;
  7285. Subobject.addArray(Info, E, CAT);
  7286. ImplicitValueInitExpr VIE(CAT->getElementType());
  7287. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  7288. }
  7289. bool VisitCallExpr(const CallExpr *E) {
  7290. return handleCallExpr(E, Result, &This);
  7291. }
  7292. bool VisitInitListExpr(const InitListExpr *E);
  7293. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  7294. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  7295. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  7296. const LValue &Subobject,
  7297. APValue *Value, QualType Type);
  7298. bool VisitStringLiteral(const StringLiteral *E) {
  7299. expandStringLiteral(Info, E, Result);
  7300. return true;
  7301. }
  7302. };
  7303. } // end anonymous namespace
  7304. static bool EvaluateArray(const Expr *E, const LValue &This,
  7305. APValue &Result, EvalInfo &Info) {
  7306. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  7307. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  7308. }
  7309. // Return true iff the given array filler may depend on the element index.
  7310. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  7311. // For now, just whitelist non-class value-initialization and initialization
  7312. // lists comprised of them.
  7313. if (isa<ImplicitValueInitExpr>(FillerExpr))
  7314. return false;
  7315. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  7316. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  7317. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  7318. return true;
  7319. }
  7320. return false;
  7321. }
  7322. return true;
  7323. }
  7324. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7325. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  7326. if (!CAT)
  7327. return Error(E);
  7328. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  7329. // an appropriately-typed string literal enclosed in braces.
  7330. if (E->isStringLiteralInit())
  7331. return Visit(E->getInit(0));
  7332. bool Success = true;
  7333. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  7334. "zero-initialized array shouldn't have any initialized elts");
  7335. APValue Filler;
  7336. if (Result.isArray() && Result.hasArrayFiller())
  7337. Filler = Result.getArrayFiller();
  7338. unsigned NumEltsToInit = E->getNumInits();
  7339. unsigned NumElts = CAT->getSize().getZExtValue();
  7340. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  7341. // If the initializer might depend on the array index, run it for each
  7342. // array element.
  7343. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  7344. NumEltsToInit = NumElts;
  7345. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  7346. << NumEltsToInit << ".\n");
  7347. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  7348. // If the array was previously zero-initialized, preserve the
  7349. // zero-initialized values.
  7350. if (Filler.hasValue()) {
  7351. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  7352. Result.getArrayInitializedElt(I) = Filler;
  7353. if (Result.hasArrayFiller())
  7354. Result.getArrayFiller() = Filler;
  7355. }
  7356. LValue Subobject = This;
  7357. Subobject.addArray(Info, E, CAT);
  7358. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  7359. const Expr *Init =
  7360. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  7361. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  7362. Info, Subobject, Init) ||
  7363. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  7364. CAT->getElementType(), 1)) {
  7365. if (!Info.noteFailure())
  7366. return false;
  7367. Success = false;
  7368. }
  7369. }
  7370. if (!Result.hasArrayFiller())
  7371. return Success;
  7372. // If we get here, we have a trivial filler, which we can just evaluate
  7373. // once and splat over the rest of the array elements.
  7374. assert(FillerExpr && "no array filler for incomplete init list");
  7375. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  7376. FillerExpr) && Success;
  7377. }
  7378. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  7379. if (E->getCommonExpr() &&
  7380. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  7381. Info, E->getCommonExpr()->getSourceExpr()))
  7382. return false;
  7383. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  7384. uint64_t Elements = CAT->getSize().getZExtValue();
  7385. Result = APValue(APValue::UninitArray(), Elements, Elements);
  7386. LValue Subobject = This;
  7387. Subobject.addArray(Info, E, CAT);
  7388. bool Success = true;
  7389. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  7390. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  7391. Info, Subobject, E->getSubExpr()) ||
  7392. !HandleLValueArrayAdjustment(Info, E, Subobject,
  7393. CAT->getElementType(), 1)) {
  7394. if (!Info.noteFailure())
  7395. return false;
  7396. Success = false;
  7397. }
  7398. }
  7399. return Success;
  7400. }
  7401. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7402. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  7403. }
  7404. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7405. const LValue &Subobject,
  7406. APValue *Value,
  7407. QualType Type) {
  7408. bool HadZeroInit = Value->hasValue();
  7409. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  7410. unsigned N = CAT->getSize().getZExtValue();
  7411. // Preserve the array filler if we had prior zero-initialization.
  7412. APValue Filler =
  7413. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  7414. : APValue();
  7415. *Value = APValue(APValue::UninitArray(), N, N);
  7416. if (HadZeroInit)
  7417. for (unsigned I = 0; I != N; ++I)
  7418. Value->getArrayInitializedElt(I) = Filler;
  7419. // Initialize the elements.
  7420. LValue ArrayElt = Subobject;
  7421. ArrayElt.addArray(Info, E, CAT);
  7422. for (unsigned I = 0; I != N; ++I)
  7423. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  7424. CAT->getElementType()) ||
  7425. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  7426. CAT->getElementType(), 1))
  7427. return false;
  7428. return true;
  7429. }
  7430. if (!Type->isRecordType())
  7431. return Error(E);
  7432. return RecordExprEvaluator(Info, Subobject, *Value)
  7433. .VisitCXXConstructExpr(E, Type);
  7434. }
  7435. //===----------------------------------------------------------------------===//
  7436. // Integer Evaluation
  7437. //
  7438. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  7439. // types and back in constant folding. Integer values are thus represented
  7440. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  7441. //===----------------------------------------------------------------------===//
  7442. namespace {
  7443. class IntExprEvaluator
  7444. : public ExprEvaluatorBase<IntExprEvaluator> {
  7445. APValue &Result;
  7446. public:
  7447. IntExprEvaluator(EvalInfo &info, APValue &result)
  7448. : ExprEvaluatorBaseTy(info), Result(result) {}
  7449. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  7450. assert(E->getType()->isIntegralOrEnumerationType() &&
  7451. "Invalid evaluation result.");
  7452. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  7453. "Invalid evaluation result.");
  7454. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7455. "Invalid evaluation result.");
  7456. Result = APValue(SI);
  7457. return true;
  7458. }
  7459. bool Success(const llvm::APSInt &SI, const Expr *E) {
  7460. return Success(SI, E, Result);
  7461. }
  7462. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  7463. assert(E->getType()->isIntegralOrEnumerationType() &&
  7464. "Invalid evaluation result.");
  7465. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7466. "Invalid evaluation result.");
  7467. Result = APValue(APSInt(I));
  7468. Result.getInt().setIsUnsigned(
  7469. E->getType()->isUnsignedIntegerOrEnumerationType());
  7470. return true;
  7471. }
  7472. bool Success(const llvm::APInt &I, const Expr *E) {
  7473. return Success(I, E, Result);
  7474. }
  7475. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  7476. assert(E->getType()->isIntegralOrEnumerationType() &&
  7477. "Invalid evaluation result.");
  7478. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  7479. return true;
  7480. }
  7481. bool Success(uint64_t Value, const Expr *E) {
  7482. return Success(Value, E, Result);
  7483. }
  7484. bool Success(CharUnits Size, const Expr *E) {
  7485. return Success(Size.getQuantity(), E);
  7486. }
  7487. bool Success(const APValue &V, const Expr *E) {
  7488. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  7489. Result = V;
  7490. return true;
  7491. }
  7492. return Success(V.getInt(), E);
  7493. }
  7494. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  7495. //===--------------------------------------------------------------------===//
  7496. // Visitor Methods
  7497. //===--------------------------------------------------------------------===//
  7498. bool VisitConstantExpr(const ConstantExpr *E);
  7499. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  7500. return Success(E->getValue(), E);
  7501. }
  7502. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  7503. return Success(E->getValue(), E);
  7504. }
  7505. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  7506. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  7507. if (CheckReferencedDecl(E, E->getDecl()))
  7508. return true;
  7509. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  7510. }
  7511. bool VisitMemberExpr(const MemberExpr *E) {
  7512. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  7513. VisitIgnoredBaseExpression(E->getBase());
  7514. return true;
  7515. }
  7516. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  7517. }
  7518. bool VisitCallExpr(const CallExpr *E);
  7519. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  7520. bool VisitBinaryOperator(const BinaryOperator *E);
  7521. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  7522. bool VisitUnaryOperator(const UnaryOperator *E);
  7523. bool VisitCastExpr(const CastExpr* E);
  7524. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  7525. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  7526. return Success(E->getValue(), E);
  7527. }
  7528. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  7529. return Success(E->getValue(), E);
  7530. }
  7531. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  7532. if (Info.ArrayInitIndex == uint64_t(-1)) {
  7533. // We were asked to evaluate this subexpression independent of the
  7534. // enclosing ArrayInitLoopExpr. We can't do that.
  7535. Info.FFDiag(E);
  7536. return false;
  7537. }
  7538. return Success(Info.ArrayInitIndex, E);
  7539. }
  7540. // Note, GNU defines __null as an integer, not a pointer.
  7541. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  7542. return ZeroInitialization(E);
  7543. }
  7544. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  7545. return Success(E->getValue(), E);
  7546. }
  7547. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  7548. return Success(E->getValue(), E);
  7549. }
  7550. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  7551. return Success(E->getValue(), E);
  7552. }
  7553. bool VisitUnaryReal(const UnaryOperator *E);
  7554. bool VisitUnaryImag(const UnaryOperator *E);
  7555. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  7556. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  7557. bool VisitSourceLocExpr(const SourceLocExpr *E);
  7558. // FIXME: Missing: array subscript of vector, member of vector
  7559. };
  7560. class FixedPointExprEvaluator
  7561. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  7562. APValue &Result;
  7563. public:
  7564. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  7565. : ExprEvaluatorBaseTy(info), Result(result) {}
  7566. bool Success(const llvm::APInt &I, const Expr *E) {
  7567. return Success(
  7568. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  7569. }
  7570. bool Success(uint64_t Value, const Expr *E) {
  7571. return Success(
  7572. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  7573. }
  7574. bool Success(const APValue &V, const Expr *E) {
  7575. return Success(V.getFixedPoint(), E);
  7576. }
  7577. bool Success(const APFixedPoint &V, const Expr *E) {
  7578. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  7579. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7580. "Invalid evaluation result.");
  7581. Result = APValue(V);
  7582. return true;
  7583. }
  7584. //===--------------------------------------------------------------------===//
  7585. // Visitor Methods
  7586. //===--------------------------------------------------------------------===//
  7587. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  7588. return Success(E->getValue(), E);
  7589. }
  7590. bool VisitCastExpr(const CastExpr *E);
  7591. bool VisitUnaryOperator(const UnaryOperator *E);
  7592. bool VisitBinaryOperator(const BinaryOperator *E);
  7593. };
  7594. } // end anonymous namespace
  7595. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  7596. /// produce either the integer value or a pointer.
  7597. ///
  7598. /// GCC has a heinous extension which folds casts between pointer types and
  7599. /// pointer-sized integral types. We support this by allowing the evaluation of
  7600. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  7601. /// Some simple arithmetic on such values is supported (they are treated much
  7602. /// like char*).
  7603. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  7604. EvalInfo &Info) {
  7605. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  7606. return IntExprEvaluator(Info, Result).Visit(E);
  7607. }
  7608. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  7609. APValue Val;
  7610. if (!EvaluateIntegerOrLValue(E, Val, Info))
  7611. return false;
  7612. if (!Val.isInt()) {
  7613. // FIXME: It would be better to produce the diagnostic for casting
  7614. // a pointer to an integer.
  7615. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7616. return false;
  7617. }
  7618. Result = Val.getInt();
  7619. return true;
  7620. }
  7621. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  7622. APValue Evaluated = E->EvaluateInContext(
  7623. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  7624. return Success(Evaluated, E);
  7625. }
  7626. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  7627. EvalInfo &Info) {
  7628. if (E->getType()->isFixedPointType()) {
  7629. APValue Val;
  7630. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  7631. return false;
  7632. if (!Val.isFixedPoint())
  7633. return false;
  7634. Result = Val.getFixedPoint();
  7635. return true;
  7636. }
  7637. return false;
  7638. }
  7639. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  7640. EvalInfo &Info) {
  7641. if (E->getType()->isIntegerType()) {
  7642. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  7643. APSInt Val;
  7644. if (!EvaluateInteger(E, Val, Info))
  7645. return false;
  7646. Result = APFixedPoint(Val, FXSema);
  7647. return true;
  7648. } else if (E->getType()->isFixedPointType()) {
  7649. return EvaluateFixedPoint(E, Result, Info);
  7650. }
  7651. return false;
  7652. }
  7653. /// Check whether the given declaration can be directly converted to an integral
  7654. /// rvalue. If not, no diagnostic is produced; there are other things we can
  7655. /// try.
  7656. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  7657. // Enums are integer constant exprs.
  7658. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  7659. // Check for signedness/width mismatches between E type and ECD value.
  7660. bool SameSign = (ECD->getInitVal().isSigned()
  7661. == E->getType()->isSignedIntegerOrEnumerationType());
  7662. bool SameWidth = (ECD->getInitVal().getBitWidth()
  7663. == Info.Ctx.getIntWidth(E->getType()));
  7664. if (SameSign && SameWidth)
  7665. return Success(ECD->getInitVal(), E);
  7666. else {
  7667. // Get rid of mismatch (otherwise Success assertions will fail)
  7668. // by computing a new value matching the type of E.
  7669. llvm::APSInt Val = ECD->getInitVal();
  7670. if (!SameSign)
  7671. Val.setIsSigned(!ECD->getInitVal().isSigned());
  7672. if (!SameWidth)
  7673. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  7674. return Success(Val, E);
  7675. }
  7676. }
  7677. return false;
  7678. }
  7679. /// Values returned by __builtin_classify_type, chosen to match the values
  7680. /// produced by GCC's builtin.
  7681. enum class GCCTypeClass {
  7682. None = -1,
  7683. Void = 0,
  7684. Integer = 1,
  7685. // GCC reserves 2 for character types, but instead classifies them as
  7686. // integers.
  7687. Enum = 3,
  7688. Bool = 4,
  7689. Pointer = 5,
  7690. // GCC reserves 6 for references, but appears to never use it (because
  7691. // expressions never have reference type, presumably).
  7692. PointerToDataMember = 7,
  7693. RealFloat = 8,
  7694. Complex = 9,
  7695. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  7696. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  7697. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  7698. // uses 12 for that purpose, same as for a class or struct. Maybe it
  7699. // internally implements a pointer to member as a struct? Who knows.
  7700. PointerToMemberFunction = 12, // Not a bug, see above.
  7701. ClassOrStruct = 12,
  7702. Union = 13,
  7703. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  7704. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  7705. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  7706. // literals.
  7707. };
  7708. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  7709. /// as GCC.
  7710. static GCCTypeClass
  7711. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  7712. assert(!T->isDependentType() && "unexpected dependent type");
  7713. QualType CanTy = T.getCanonicalType();
  7714. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  7715. switch (CanTy->getTypeClass()) {
  7716. #define TYPE(ID, BASE)
  7717. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  7718. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  7719. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  7720. #include "clang/AST/TypeNodes.def"
  7721. case Type::Auto:
  7722. case Type::DeducedTemplateSpecialization:
  7723. llvm_unreachable("unexpected non-canonical or dependent type");
  7724. case Type::Builtin:
  7725. switch (BT->getKind()) {
  7726. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  7727. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  7728. case BuiltinType::ID: return GCCTypeClass::Integer;
  7729. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  7730. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  7731. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  7732. case BuiltinType::ID: break;
  7733. #include "clang/AST/BuiltinTypes.def"
  7734. case BuiltinType::Void:
  7735. return GCCTypeClass::Void;
  7736. case BuiltinType::Bool:
  7737. return GCCTypeClass::Bool;
  7738. case BuiltinType::Char_U:
  7739. case BuiltinType::UChar:
  7740. case BuiltinType::WChar_U:
  7741. case BuiltinType::Char8:
  7742. case BuiltinType::Char16:
  7743. case BuiltinType::Char32:
  7744. case BuiltinType::UShort:
  7745. case BuiltinType::UInt:
  7746. case BuiltinType::ULong:
  7747. case BuiltinType::ULongLong:
  7748. case BuiltinType::UInt128:
  7749. return GCCTypeClass::Integer;
  7750. case BuiltinType::UShortAccum:
  7751. case BuiltinType::UAccum:
  7752. case BuiltinType::ULongAccum:
  7753. case BuiltinType::UShortFract:
  7754. case BuiltinType::UFract:
  7755. case BuiltinType::ULongFract:
  7756. case BuiltinType::SatUShortAccum:
  7757. case BuiltinType::SatUAccum:
  7758. case BuiltinType::SatULongAccum:
  7759. case BuiltinType::SatUShortFract:
  7760. case BuiltinType::SatUFract:
  7761. case BuiltinType::SatULongFract:
  7762. return GCCTypeClass::None;
  7763. case BuiltinType::NullPtr:
  7764. case BuiltinType::ObjCId:
  7765. case BuiltinType::ObjCClass:
  7766. case BuiltinType::ObjCSel:
  7767. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  7768. case BuiltinType::Id:
  7769. #include "clang/Basic/OpenCLImageTypes.def"
  7770. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  7771. case BuiltinType::Id:
  7772. #include "clang/Basic/OpenCLExtensionTypes.def"
  7773. case BuiltinType::OCLSampler:
  7774. case BuiltinType::OCLEvent:
  7775. case BuiltinType::OCLClkEvent:
  7776. case BuiltinType::OCLQueue:
  7777. case BuiltinType::OCLReserveID:
  7778. #define SVE_TYPE(Name, Id, SingletonId) \
  7779. case BuiltinType::Id:
  7780. #include "clang/Basic/AArch64SVEACLETypes.def"
  7781. return GCCTypeClass::None;
  7782. case BuiltinType::Dependent:
  7783. llvm_unreachable("unexpected dependent type");
  7784. };
  7785. llvm_unreachable("unexpected placeholder type");
  7786. case Type::Enum:
  7787. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  7788. case Type::Pointer:
  7789. case Type::ConstantArray:
  7790. case Type::VariableArray:
  7791. case Type::IncompleteArray:
  7792. case Type::FunctionNoProto:
  7793. case Type::FunctionProto:
  7794. return GCCTypeClass::Pointer;
  7795. case Type::MemberPointer:
  7796. return CanTy->isMemberDataPointerType()
  7797. ? GCCTypeClass::PointerToDataMember
  7798. : GCCTypeClass::PointerToMemberFunction;
  7799. case Type::Complex:
  7800. return GCCTypeClass::Complex;
  7801. case Type::Record:
  7802. return CanTy->isUnionType() ? GCCTypeClass::Union
  7803. : GCCTypeClass::ClassOrStruct;
  7804. case Type::Atomic:
  7805. // GCC classifies _Atomic T the same as T.
  7806. return EvaluateBuiltinClassifyType(
  7807. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  7808. case Type::BlockPointer:
  7809. case Type::Vector:
  7810. case Type::ExtVector:
  7811. case Type::ObjCObject:
  7812. case Type::ObjCInterface:
  7813. case Type::ObjCObjectPointer:
  7814. case Type::Pipe:
  7815. // GCC classifies vectors as None. We follow its lead and classify all
  7816. // other types that don't fit into the regular classification the same way.
  7817. return GCCTypeClass::None;
  7818. case Type::LValueReference:
  7819. case Type::RValueReference:
  7820. llvm_unreachable("invalid type for expression");
  7821. }
  7822. llvm_unreachable("unexpected type class");
  7823. }
  7824. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  7825. /// as GCC.
  7826. static GCCTypeClass
  7827. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  7828. // If no argument was supplied, default to None. This isn't
  7829. // ideal, however it is what gcc does.
  7830. if (E->getNumArgs() == 0)
  7831. return GCCTypeClass::None;
  7832. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  7833. // being an ICE, but still folds it to a constant using the type of the first
  7834. // argument.
  7835. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  7836. }
  7837. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  7838. /// __builtin_constant_p when applied to the given pointer.
  7839. ///
  7840. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  7841. /// or it points to the first character of a string literal.
  7842. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  7843. APValue::LValueBase Base = LV.getLValueBase();
  7844. if (Base.isNull()) {
  7845. // A null base is acceptable.
  7846. return true;
  7847. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  7848. if (!isa<StringLiteral>(E))
  7849. return false;
  7850. return LV.getLValueOffset().isZero();
  7851. } else if (Base.is<TypeInfoLValue>()) {
  7852. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  7853. // evaluate to true.
  7854. return true;
  7855. } else {
  7856. // Any other base is not constant enough for GCC.
  7857. return false;
  7858. }
  7859. }
  7860. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  7861. /// GCC as we can manage.
  7862. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  7863. // This evaluation is not permitted to have side-effects, so evaluate it in
  7864. // a speculative evaluation context.
  7865. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7866. // Constant-folding is always enabled for the operand of __builtin_constant_p
  7867. // (even when the enclosing evaluation context otherwise requires a strict
  7868. // language-specific constant expression).
  7869. FoldConstant Fold(Info, true);
  7870. QualType ArgType = Arg->getType();
  7871. // __builtin_constant_p always has one operand. The rules which gcc follows
  7872. // are not precisely documented, but are as follows:
  7873. //
  7874. // - If the operand is of integral, floating, complex or enumeration type,
  7875. // and can be folded to a known value of that type, it returns 1.
  7876. // - If the operand can be folded to a pointer to the first character
  7877. // of a string literal (or such a pointer cast to an integral type)
  7878. // or to a null pointer or an integer cast to a pointer, it returns 1.
  7879. //
  7880. // Otherwise, it returns 0.
  7881. //
  7882. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  7883. // its support for this did not work prior to GCC 9 and is not yet well
  7884. // understood.
  7885. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  7886. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  7887. ArgType->isNullPtrType()) {
  7888. APValue V;
  7889. if (!::EvaluateAsRValue(Info, Arg, V)) {
  7890. Fold.keepDiagnostics();
  7891. return false;
  7892. }
  7893. // For a pointer (possibly cast to integer), there are special rules.
  7894. if (V.getKind() == APValue::LValue)
  7895. return EvaluateBuiltinConstantPForLValue(V);
  7896. // Otherwise, any constant value is good enough.
  7897. return V.hasValue();
  7898. }
  7899. // Anything else isn't considered to be sufficiently constant.
  7900. return false;
  7901. }
  7902. /// Retrieves the "underlying object type" of the given expression,
  7903. /// as used by __builtin_object_size.
  7904. static QualType getObjectType(APValue::LValueBase B) {
  7905. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  7906. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  7907. return VD->getType();
  7908. } else if (const Expr *E = B.get<const Expr*>()) {
  7909. if (isa<CompoundLiteralExpr>(E))
  7910. return E->getType();
  7911. } else if (B.is<TypeInfoLValue>()) {
  7912. return B.getTypeInfoType();
  7913. }
  7914. return QualType();
  7915. }
  7916. /// A more selective version of E->IgnoreParenCasts for
  7917. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  7918. /// to change the type of E.
  7919. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  7920. ///
  7921. /// Always returns an RValue with a pointer representation.
  7922. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  7923. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  7924. auto *NoParens = E->IgnoreParens();
  7925. auto *Cast = dyn_cast<CastExpr>(NoParens);
  7926. if (Cast == nullptr)
  7927. return NoParens;
  7928. // We only conservatively allow a few kinds of casts, because this code is
  7929. // inherently a simple solution that seeks to support the common case.
  7930. auto CastKind = Cast->getCastKind();
  7931. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  7932. CastKind != CK_AddressSpaceConversion)
  7933. return NoParens;
  7934. auto *SubExpr = Cast->getSubExpr();
  7935. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  7936. return NoParens;
  7937. return ignorePointerCastsAndParens(SubExpr);
  7938. }
  7939. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  7940. /// record layout. e.g.
  7941. /// struct { struct { int a, b; } fst, snd; } obj;
  7942. /// obj.fst // no
  7943. /// obj.snd // yes
  7944. /// obj.fst.a // no
  7945. /// obj.fst.b // no
  7946. /// obj.snd.a // no
  7947. /// obj.snd.b // yes
  7948. ///
  7949. /// Please note: this function is specialized for how __builtin_object_size
  7950. /// views "objects".
  7951. ///
  7952. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  7953. /// correct result, it will always return true.
  7954. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  7955. assert(!LVal.Designator.Invalid);
  7956. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  7957. const RecordDecl *Parent = FD->getParent();
  7958. Invalid = Parent->isInvalidDecl();
  7959. if (Invalid || Parent->isUnion())
  7960. return true;
  7961. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  7962. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  7963. };
  7964. auto &Base = LVal.getLValueBase();
  7965. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  7966. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  7967. bool Invalid;
  7968. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  7969. return Invalid;
  7970. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  7971. for (auto *FD : IFD->chain()) {
  7972. bool Invalid;
  7973. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  7974. return Invalid;
  7975. }
  7976. }
  7977. }
  7978. unsigned I = 0;
  7979. QualType BaseType = getType(Base);
  7980. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  7981. // If we don't know the array bound, conservatively assume we're looking at
  7982. // the final array element.
  7983. ++I;
  7984. if (BaseType->isIncompleteArrayType())
  7985. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  7986. else
  7987. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  7988. }
  7989. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  7990. const auto &Entry = LVal.Designator.Entries[I];
  7991. if (BaseType->isArrayType()) {
  7992. // Because __builtin_object_size treats arrays as objects, we can ignore
  7993. // the index iff this is the last array in the Designator.
  7994. if (I + 1 == E)
  7995. return true;
  7996. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  7997. uint64_t Index = Entry.getAsArrayIndex();
  7998. if (Index + 1 != CAT->getSize())
  7999. return false;
  8000. BaseType = CAT->getElementType();
  8001. } else if (BaseType->isAnyComplexType()) {
  8002. const auto *CT = BaseType->castAs<ComplexType>();
  8003. uint64_t Index = Entry.getAsArrayIndex();
  8004. if (Index != 1)
  8005. return false;
  8006. BaseType = CT->getElementType();
  8007. } else if (auto *FD = getAsField(Entry)) {
  8008. bool Invalid;
  8009. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8010. return Invalid;
  8011. BaseType = FD->getType();
  8012. } else {
  8013. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  8014. return false;
  8015. }
  8016. }
  8017. return true;
  8018. }
  8019. /// Tests to see if the LValue has a user-specified designator (that isn't
  8020. /// necessarily valid). Note that this always returns 'true' if the LValue has
  8021. /// an unsized array as its first designator entry, because there's currently no
  8022. /// way to tell if the user typed *foo or foo[0].
  8023. static bool refersToCompleteObject(const LValue &LVal) {
  8024. if (LVal.Designator.Invalid)
  8025. return false;
  8026. if (!LVal.Designator.Entries.empty())
  8027. return LVal.Designator.isMostDerivedAnUnsizedArray();
  8028. if (!LVal.InvalidBase)
  8029. return true;
  8030. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  8031. // the LValueBase.
  8032. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  8033. return !E || !isa<MemberExpr>(E);
  8034. }
  8035. /// Attempts to detect a user writing into a piece of memory that's impossible
  8036. /// to figure out the size of by just using types.
  8037. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  8038. const SubobjectDesignator &Designator = LVal.Designator;
  8039. // Notes:
  8040. // - Users can only write off of the end when we have an invalid base. Invalid
  8041. // bases imply we don't know where the memory came from.
  8042. // - We used to be a bit more aggressive here; we'd only be conservative if
  8043. // the array at the end was flexible, or if it had 0 or 1 elements. This
  8044. // broke some common standard library extensions (PR30346), but was
  8045. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  8046. // with some sort of whitelist. OTOH, it seems that GCC is always
  8047. // conservative with the last element in structs (if it's an array), so our
  8048. // current behavior is more compatible than a whitelisting approach would
  8049. // be.
  8050. return LVal.InvalidBase &&
  8051. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  8052. Designator.MostDerivedIsArrayElement &&
  8053. isDesignatorAtObjectEnd(Ctx, LVal);
  8054. }
  8055. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  8056. /// Fails if the conversion would cause loss of precision.
  8057. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  8058. CharUnits &Result) {
  8059. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  8060. if (Int.ugt(CharUnitsMax))
  8061. return false;
  8062. Result = CharUnits::fromQuantity(Int.getZExtValue());
  8063. return true;
  8064. }
  8065. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  8066. /// determine how many bytes exist from the beginning of the object to either
  8067. /// the end of the current subobject, or the end of the object itself, depending
  8068. /// on what the LValue looks like + the value of Type.
  8069. ///
  8070. /// If this returns false, the value of Result is undefined.
  8071. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  8072. unsigned Type, const LValue &LVal,
  8073. CharUnits &EndOffset) {
  8074. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  8075. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  8076. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  8077. return false;
  8078. return HandleSizeof(Info, ExprLoc, Ty, Result);
  8079. };
  8080. // We want to evaluate the size of the entire object. This is a valid fallback
  8081. // for when Type=1 and the designator is invalid, because we're asked for an
  8082. // upper-bound.
  8083. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  8084. // Type=3 wants a lower bound, so we can't fall back to this.
  8085. if (Type == 3 && !DetermineForCompleteObject)
  8086. return false;
  8087. llvm::APInt APEndOffset;
  8088. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8089. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8090. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8091. if (LVal.InvalidBase)
  8092. return false;
  8093. QualType BaseTy = getObjectType(LVal.getLValueBase());
  8094. return CheckedHandleSizeof(BaseTy, EndOffset);
  8095. }
  8096. // We want to evaluate the size of a subobject.
  8097. const SubobjectDesignator &Designator = LVal.Designator;
  8098. // The following is a moderately common idiom in C:
  8099. //
  8100. // struct Foo { int a; char c[1]; };
  8101. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  8102. // strcpy(&F->c[0], Bar);
  8103. //
  8104. // In order to not break too much legacy code, we need to support it.
  8105. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  8106. // If we can resolve this to an alloc_size call, we can hand that back,
  8107. // because we know for certain how many bytes there are to write to.
  8108. llvm::APInt APEndOffset;
  8109. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8110. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8111. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8112. // If we cannot determine the size of the initial allocation, then we can't
  8113. // given an accurate upper-bound. However, we are still able to give
  8114. // conservative lower-bounds for Type=3.
  8115. if (Type == 1)
  8116. return false;
  8117. }
  8118. CharUnits BytesPerElem;
  8119. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  8120. return false;
  8121. // According to the GCC documentation, we want the size of the subobject
  8122. // denoted by the pointer. But that's not quite right -- what we actually
  8123. // want is the size of the immediately-enclosing array, if there is one.
  8124. int64_t ElemsRemaining;
  8125. if (Designator.MostDerivedIsArrayElement &&
  8126. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  8127. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  8128. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  8129. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  8130. } else {
  8131. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  8132. }
  8133. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  8134. return true;
  8135. }
  8136. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  8137. /// returns true and stores the result in @p Size.
  8138. ///
  8139. /// If @p WasError is non-null, this will report whether the failure to evaluate
  8140. /// is to be treated as an Error in IntExprEvaluator.
  8141. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  8142. EvalInfo &Info, uint64_t &Size) {
  8143. // Determine the denoted object.
  8144. LValue LVal;
  8145. {
  8146. // The operand of __builtin_object_size is never evaluated for side-effects.
  8147. // If there are any, but we can determine the pointed-to object anyway, then
  8148. // ignore the side-effects.
  8149. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8150. IgnoreSideEffectsRAII Fold(Info);
  8151. if (E->isGLValue()) {
  8152. // It's possible for us to be given GLValues if we're called via
  8153. // Expr::tryEvaluateObjectSize.
  8154. APValue RVal;
  8155. if (!EvaluateAsRValue(Info, E, RVal))
  8156. return false;
  8157. LVal.setFrom(Info.Ctx, RVal);
  8158. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  8159. /*InvalidBaseOK=*/true))
  8160. return false;
  8161. }
  8162. // If we point to before the start of the object, there are no accessible
  8163. // bytes.
  8164. if (LVal.getLValueOffset().isNegative()) {
  8165. Size = 0;
  8166. return true;
  8167. }
  8168. CharUnits EndOffset;
  8169. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  8170. return false;
  8171. // If we've fallen outside of the end offset, just pretend there's nothing to
  8172. // write to/read from.
  8173. if (EndOffset <= LVal.getLValueOffset())
  8174. Size = 0;
  8175. else
  8176. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  8177. return true;
  8178. }
  8179. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  8180. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  8181. if (E->getResultAPValueKind() != APValue::None)
  8182. return Success(E->getAPValueResult(), E);
  8183. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  8184. }
  8185. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8186. if (unsigned BuiltinOp = E->getBuiltinCallee())
  8187. return VisitBuiltinCallExpr(E, BuiltinOp);
  8188. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8189. }
  8190. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  8191. unsigned BuiltinOp) {
  8192. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  8193. default:
  8194. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8195. case Builtin::BI__builtin_dynamic_object_size:
  8196. case Builtin::BI__builtin_object_size: {
  8197. // The type was checked when we built the expression.
  8198. unsigned Type =
  8199. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  8200. assert(Type <= 3 && "unexpected type");
  8201. uint64_t Size;
  8202. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  8203. return Success(Size, E);
  8204. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  8205. return Success((Type & 2) ? 0 : -1, E);
  8206. // Expression had no side effects, but we couldn't statically determine the
  8207. // size of the referenced object.
  8208. switch (Info.EvalMode) {
  8209. case EvalInfo::EM_ConstantExpression:
  8210. case EvalInfo::EM_PotentialConstantExpression:
  8211. case EvalInfo::EM_ConstantFold:
  8212. case EvalInfo::EM_EvaluateForOverflow:
  8213. case EvalInfo::EM_IgnoreSideEffects:
  8214. // Leave it to IR generation.
  8215. return Error(E);
  8216. case EvalInfo::EM_ConstantExpressionUnevaluated:
  8217. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  8218. // Reduce it to a constant now.
  8219. return Success((Type & 2) ? 0 : -1, E);
  8220. }
  8221. llvm_unreachable("unexpected EvalMode");
  8222. }
  8223. case Builtin::BI__builtin_os_log_format_buffer_size: {
  8224. analyze_os_log::OSLogBufferLayout Layout;
  8225. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  8226. return Success(Layout.size().getQuantity(), E);
  8227. }
  8228. case Builtin::BI__builtin_bswap16:
  8229. case Builtin::BI__builtin_bswap32:
  8230. case Builtin::BI__builtin_bswap64: {
  8231. APSInt Val;
  8232. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8233. return false;
  8234. return Success(Val.byteSwap(), E);
  8235. }
  8236. case Builtin::BI__builtin_classify_type:
  8237. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  8238. case Builtin::BI__builtin_clrsb:
  8239. case Builtin::BI__builtin_clrsbl:
  8240. case Builtin::BI__builtin_clrsbll: {
  8241. APSInt Val;
  8242. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8243. return false;
  8244. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  8245. }
  8246. case Builtin::BI__builtin_clz:
  8247. case Builtin::BI__builtin_clzl:
  8248. case Builtin::BI__builtin_clzll:
  8249. case Builtin::BI__builtin_clzs: {
  8250. APSInt Val;
  8251. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8252. return false;
  8253. if (!Val)
  8254. return Error(E);
  8255. return Success(Val.countLeadingZeros(), E);
  8256. }
  8257. case Builtin::BI__builtin_constant_p: {
  8258. const Expr *Arg = E->getArg(0);
  8259. if (EvaluateBuiltinConstantP(Info, Arg))
  8260. return Success(true, E);
  8261. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  8262. // Outside a constant context, eagerly evaluate to false in the presence
  8263. // of side-effects in order to avoid -Wunsequenced false-positives in
  8264. // a branch on __builtin_constant_p(expr).
  8265. return Success(false, E);
  8266. }
  8267. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8268. return false;
  8269. }
  8270. case Builtin::BI__builtin_is_constant_evaluated:
  8271. return Success(Info.InConstantContext, E);
  8272. case Builtin::BI__builtin_ctz:
  8273. case Builtin::BI__builtin_ctzl:
  8274. case Builtin::BI__builtin_ctzll:
  8275. case Builtin::BI__builtin_ctzs: {
  8276. APSInt Val;
  8277. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8278. return false;
  8279. if (!Val)
  8280. return Error(E);
  8281. return Success(Val.countTrailingZeros(), E);
  8282. }
  8283. case Builtin::BI__builtin_eh_return_data_regno: {
  8284. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  8285. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  8286. return Success(Operand, E);
  8287. }
  8288. case Builtin::BI__builtin_expect:
  8289. return Visit(E->getArg(0));
  8290. case Builtin::BI__builtin_ffs:
  8291. case Builtin::BI__builtin_ffsl:
  8292. case Builtin::BI__builtin_ffsll: {
  8293. APSInt Val;
  8294. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8295. return false;
  8296. unsigned N = Val.countTrailingZeros();
  8297. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  8298. }
  8299. case Builtin::BI__builtin_fpclassify: {
  8300. APFloat Val(0.0);
  8301. if (!EvaluateFloat(E->getArg(5), Val, Info))
  8302. return false;
  8303. unsigned Arg;
  8304. switch (Val.getCategory()) {
  8305. case APFloat::fcNaN: Arg = 0; break;
  8306. case APFloat::fcInfinity: Arg = 1; break;
  8307. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  8308. case APFloat::fcZero: Arg = 4; break;
  8309. }
  8310. return Visit(E->getArg(Arg));
  8311. }
  8312. case Builtin::BI__builtin_isinf_sign: {
  8313. APFloat Val(0.0);
  8314. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8315. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  8316. }
  8317. case Builtin::BI__builtin_isinf: {
  8318. APFloat Val(0.0);
  8319. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8320. Success(Val.isInfinity() ? 1 : 0, E);
  8321. }
  8322. case Builtin::BI__builtin_isfinite: {
  8323. APFloat Val(0.0);
  8324. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8325. Success(Val.isFinite() ? 1 : 0, E);
  8326. }
  8327. case Builtin::BI__builtin_isnan: {
  8328. APFloat Val(0.0);
  8329. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8330. Success(Val.isNaN() ? 1 : 0, E);
  8331. }
  8332. case Builtin::BI__builtin_isnormal: {
  8333. APFloat Val(0.0);
  8334. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8335. Success(Val.isNormal() ? 1 : 0, E);
  8336. }
  8337. case Builtin::BI__builtin_parity:
  8338. case Builtin::BI__builtin_parityl:
  8339. case Builtin::BI__builtin_parityll: {
  8340. APSInt Val;
  8341. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8342. return false;
  8343. return Success(Val.countPopulation() % 2, E);
  8344. }
  8345. case Builtin::BI__builtin_popcount:
  8346. case Builtin::BI__builtin_popcountl:
  8347. case Builtin::BI__builtin_popcountll: {
  8348. APSInt Val;
  8349. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8350. return false;
  8351. return Success(Val.countPopulation(), E);
  8352. }
  8353. case Builtin::BIstrlen:
  8354. case Builtin::BIwcslen:
  8355. // A call to strlen is not a constant expression.
  8356. if (Info.getLangOpts().CPlusPlus11)
  8357. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8358. << /*isConstexpr*/0 << /*isConstructor*/0
  8359. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8360. else
  8361. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8362. LLVM_FALLTHROUGH;
  8363. case Builtin::BI__builtin_strlen:
  8364. case Builtin::BI__builtin_wcslen: {
  8365. // As an extension, we support __builtin_strlen() as a constant expression,
  8366. // and support folding strlen() to a constant.
  8367. LValue String;
  8368. if (!EvaluatePointer(E->getArg(0), String, Info))
  8369. return false;
  8370. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  8371. // Fast path: if it's a string literal, search the string value.
  8372. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  8373. String.getLValueBase().dyn_cast<const Expr *>())) {
  8374. // The string literal may have embedded null characters. Find the first
  8375. // one and truncate there.
  8376. StringRef Str = S->getBytes();
  8377. int64_t Off = String.Offset.getQuantity();
  8378. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  8379. S->getCharByteWidth() == 1 &&
  8380. // FIXME: Add fast-path for wchar_t too.
  8381. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  8382. Str = Str.substr(Off);
  8383. StringRef::size_type Pos = Str.find(0);
  8384. if (Pos != StringRef::npos)
  8385. Str = Str.substr(0, Pos);
  8386. return Success(Str.size(), E);
  8387. }
  8388. // Fall through to slow path to issue appropriate diagnostic.
  8389. }
  8390. // Slow path: scan the bytes of the string looking for the terminating 0.
  8391. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  8392. APValue Char;
  8393. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  8394. !Char.isInt())
  8395. return false;
  8396. if (!Char.getInt())
  8397. return Success(Strlen, E);
  8398. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  8399. return false;
  8400. }
  8401. }
  8402. case Builtin::BIstrcmp:
  8403. case Builtin::BIwcscmp:
  8404. case Builtin::BIstrncmp:
  8405. case Builtin::BIwcsncmp:
  8406. case Builtin::BImemcmp:
  8407. case Builtin::BIbcmp:
  8408. case Builtin::BIwmemcmp:
  8409. // A call to strlen is not a constant expression.
  8410. if (Info.getLangOpts().CPlusPlus11)
  8411. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8412. << /*isConstexpr*/0 << /*isConstructor*/0
  8413. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8414. else
  8415. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8416. LLVM_FALLTHROUGH;
  8417. case Builtin::BI__builtin_strcmp:
  8418. case Builtin::BI__builtin_wcscmp:
  8419. case Builtin::BI__builtin_strncmp:
  8420. case Builtin::BI__builtin_wcsncmp:
  8421. case Builtin::BI__builtin_memcmp:
  8422. case Builtin::BI__builtin_bcmp:
  8423. case Builtin::BI__builtin_wmemcmp: {
  8424. LValue String1, String2;
  8425. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  8426. !EvaluatePointer(E->getArg(1), String2, Info))
  8427. return false;
  8428. uint64_t MaxLength = uint64_t(-1);
  8429. if (BuiltinOp != Builtin::BIstrcmp &&
  8430. BuiltinOp != Builtin::BIwcscmp &&
  8431. BuiltinOp != Builtin::BI__builtin_strcmp &&
  8432. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  8433. APSInt N;
  8434. if (!EvaluateInteger(E->getArg(2), N, Info))
  8435. return false;
  8436. MaxLength = N.getExtValue();
  8437. }
  8438. // Empty substrings compare equal by definition.
  8439. if (MaxLength == 0u)
  8440. return Success(0, E);
  8441. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  8442. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  8443. String1.Designator.Invalid || String2.Designator.Invalid)
  8444. return false;
  8445. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  8446. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  8447. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  8448. BuiltinOp == Builtin::BIbcmp ||
  8449. BuiltinOp == Builtin::BI__builtin_memcmp ||
  8450. BuiltinOp == Builtin::BI__builtin_bcmp;
  8451. assert(IsRawByte ||
  8452. (Info.Ctx.hasSameUnqualifiedType(
  8453. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  8454. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  8455. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  8456. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  8457. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  8458. Char1.isInt() && Char2.isInt();
  8459. };
  8460. const auto &AdvanceElems = [&] {
  8461. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  8462. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  8463. };
  8464. if (IsRawByte) {
  8465. uint64_t BytesRemaining = MaxLength;
  8466. // Pointers to const void may point to objects of incomplete type.
  8467. if (CharTy1->isIncompleteType()) {
  8468. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  8469. return false;
  8470. }
  8471. if (CharTy2->isIncompleteType()) {
  8472. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  8473. return false;
  8474. }
  8475. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  8476. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  8477. // Give up on comparing between elements with disparate widths.
  8478. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  8479. return false;
  8480. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  8481. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  8482. "following loop considers at least one element");
  8483. while (true) {
  8484. APValue Char1, Char2;
  8485. if (!ReadCurElems(Char1, Char2))
  8486. return false;
  8487. // We have compatible in-memory widths, but a possible type and
  8488. // (for `bool`) internal representation mismatch.
  8489. // Assuming two's complement representation, including 0 for `false` and
  8490. // 1 for `true`, we can check an appropriate number of elements for
  8491. // equality even if they are not byte-sized.
  8492. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  8493. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  8494. if (Char1InMem.ne(Char2InMem)) {
  8495. // If the elements are byte-sized, then we can produce a three-way
  8496. // comparison result in a straightforward manner.
  8497. if (BytesPerElement == 1u) {
  8498. // memcmp always compares unsigned chars.
  8499. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  8500. }
  8501. // The result is byte-order sensitive, and we have multibyte elements.
  8502. // FIXME: We can compare the remaining bytes in the correct order.
  8503. return false;
  8504. }
  8505. if (!AdvanceElems())
  8506. return false;
  8507. if (BytesRemaining <= BytesPerElement)
  8508. break;
  8509. BytesRemaining -= BytesPerElement;
  8510. }
  8511. // Enough elements are equal to account for the memcmp limit.
  8512. return Success(0, E);
  8513. }
  8514. bool StopAtNull =
  8515. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  8516. BuiltinOp != Builtin::BIwmemcmp &&
  8517. BuiltinOp != Builtin::BI__builtin_memcmp &&
  8518. BuiltinOp != Builtin::BI__builtin_bcmp &&
  8519. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  8520. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  8521. BuiltinOp == Builtin::BIwcsncmp ||
  8522. BuiltinOp == Builtin::BIwmemcmp ||
  8523. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  8524. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  8525. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  8526. for (; MaxLength; --MaxLength) {
  8527. APValue Char1, Char2;
  8528. if (!ReadCurElems(Char1, Char2))
  8529. return false;
  8530. if (Char1.getInt() != Char2.getInt()) {
  8531. if (IsWide) // wmemcmp compares with wchar_t signedness.
  8532. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  8533. // memcmp always compares unsigned chars.
  8534. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  8535. }
  8536. if (StopAtNull && !Char1.getInt())
  8537. return Success(0, E);
  8538. assert(!(StopAtNull && !Char2.getInt()));
  8539. if (!AdvanceElems())
  8540. return false;
  8541. }
  8542. // We hit the strncmp / memcmp limit.
  8543. return Success(0, E);
  8544. }
  8545. case Builtin::BI__atomic_always_lock_free:
  8546. case Builtin::BI__atomic_is_lock_free:
  8547. case Builtin::BI__c11_atomic_is_lock_free: {
  8548. APSInt SizeVal;
  8549. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  8550. return false;
  8551. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  8552. // of two less than the maximum inline atomic width, we know it is
  8553. // lock-free. If the size isn't a power of two, or greater than the
  8554. // maximum alignment where we promote atomics, we know it is not lock-free
  8555. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  8556. // the answer can only be determined at runtime; for example, 16-byte
  8557. // atomics have lock-free implementations on some, but not all,
  8558. // x86-64 processors.
  8559. // Check power-of-two.
  8560. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  8561. if (Size.isPowerOfTwo()) {
  8562. // Check against inlining width.
  8563. unsigned InlineWidthBits =
  8564. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  8565. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  8566. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  8567. Size == CharUnits::One() ||
  8568. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  8569. Expr::NPC_NeverValueDependent))
  8570. // OK, we will inline appropriately-aligned operations of this size,
  8571. // and _Atomic(T) is appropriately-aligned.
  8572. return Success(1, E);
  8573. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  8574. castAs<PointerType>()->getPointeeType();
  8575. if (!PointeeType->isIncompleteType() &&
  8576. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  8577. // OK, we will inline operations on this object.
  8578. return Success(1, E);
  8579. }
  8580. }
  8581. }
  8582. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  8583. Success(0, E) : Error(E);
  8584. }
  8585. case Builtin::BIomp_is_initial_device:
  8586. // We can decide statically which value the runtime would return if called.
  8587. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  8588. case Builtin::BI__builtin_add_overflow:
  8589. case Builtin::BI__builtin_sub_overflow:
  8590. case Builtin::BI__builtin_mul_overflow:
  8591. case Builtin::BI__builtin_sadd_overflow:
  8592. case Builtin::BI__builtin_uadd_overflow:
  8593. case Builtin::BI__builtin_uaddl_overflow:
  8594. case Builtin::BI__builtin_uaddll_overflow:
  8595. case Builtin::BI__builtin_usub_overflow:
  8596. case Builtin::BI__builtin_usubl_overflow:
  8597. case Builtin::BI__builtin_usubll_overflow:
  8598. case Builtin::BI__builtin_umul_overflow:
  8599. case Builtin::BI__builtin_umull_overflow:
  8600. case Builtin::BI__builtin_umulll_overflow:
  8601. case Builtin::BI__builtin_saddl_overflow:
  8602. case Builtin::BI__builtin_saddll_overflow:
  8603. case Builtin::BI__builtin_ssub_overflow:
  8604. case Builtin::BI__builtin_ssubl_overflow:
  8605. case Builtin::BI__builtin_ssubll_overflow:
  8606. case Builtin::BI__builtin_smul_overflow:
  8607. case Builtin::BI__builtin_smull_overflow:
  8608. case Builtin::BI__builtin_smulll_overflow: {
  8609. LValue ResultLValue;
  8610. APSInt LHS, RHS;
  8611. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  8612. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  8613. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  8614. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  8615. return false;
  8616. APSInt Result;
  8617. bool DidOverflow = false;
  8618. // If the types don't have to match, enlarge all 3 to the largest of them.
  8619. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  8620. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  8621. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  8622. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  8623. ResultType->isSignedIntegerOrEnumerationType();
  8624. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  8625. ResultType->isSignedIntegerOrEnumerationType();
  8626. uint64_t LHSSize = LHS.getBitWidth();
  8627. uint64_t RHSSize = RHS.getBitWidth();
  8628. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  8629. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  8630. // Add an additional bit if the signedness isn't uniformly agreed to. We
  8631. // could do this ONLY if there is a signed and an unsigned that both have
  8632. // MaxBits, but the code to check that is pretty nasty. The issue will be
  8633. // caught in the shrink-to-result later anyway.
  8634. if (IsSigned && !AllSigned)
  8635. ++MaxBits;
  8636. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  8637. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  8638. Result = APSInt(MaxBits, !IsSigned);
  8639. }
  8640. // Find largest int.
  8641. switch (BuiltinOp) {
  8642. default:
  8643. llvm_unreachable("Invalid value for BuiltinOp");
  8644. case Builtin::BI__builtin_add_overflow:
  8645. case Builtin::BI__builtin_sadd_overflow:
  8646. case Builtin::BI__builtin_saddl_overflow:
  8647. case Builtin::BI__builtin_saddll_overflow:
  8648. case Builtin::BI__builtin_uadd_overflow:
  8649. case Builtin::BI__builtin_uaddl_overflow:
  8650. case Builtin::BI__builtin_uaddll_overflow:
  8651. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  8652. : LHS.uadd_ov(RHS, DidOverflow);
  8653. break;
  8654. case Builtin::BI__builtin_sub_overflow:
  8655. case Builtin::BI__builtin_ssub_overflow:
  8656. case Builtin::BI__builtin_ssubl_overflow:
  8657. case Builtin::BI__builtin_ssubll_overflow:
  8658. case Builtin::BI__builtin_usub_overflow:
  8659. case Builtin::BI__builtin_usubl_overflow:
  8660. case Builtin::BI__builtin_usubll_overflow:
  8661. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  8662. : LHS.usub_ov(RHS, DidOverflow);
  8663. break;
  8664. case Builtin::BI__builtin_mul_overflow:
  8665. case Builtin::BI__builtin_smul_overflow:
  8666. case Builtin::BI__builtin_smull_overflow:
  8667. case Builtin::BI__builtin_smulll_overflow:
  8668. case Builtin::BI__builtin_umul_overflow:
  8669. case Builtin::BI__builtin_umull_overflow:
  8670. case Builtin::BI__builtin_umulll_overflow:
  8671. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  8672. : LHS.umul_ov(RHS, DidOverflow);
  8673. break;
  8674. }
  8675. // In the case where multiple sizes are allowed, truncate and see if
  8676. // the values are the same.
  8677. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  8678. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  8679. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  8680. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  8681. // since it will give us the behavior of a TruncOrSelf in the case where
  8682. // its parameter <= its size. We previously set Result to be at least the
  8683. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  8684. // will work exactly like TruncOrSelf.
  8685. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  8686. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  8687. if (!APSInt::isSameValue(Temp, Result))
  8688. DidOverflow = true;
  8689. Result = Temp;
  8690. }
  8691. APValue APV{Result};
  8692. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  8693. return false;
  8694. return Success(DidOverflow, E);
  8695. }
  8696. }
  8697. }
  8698. /// Determine whether this is a pointer past the end of the complete
  8699. /// object referred to by the lvalue.
  8700. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  8701. const LValue &LV) {
  8702. // A null pointer can be viewed as being "past the end" but we don't
  8703. // choose to look at it that way here.
  8704. if (!LV.getLValueBase())
  8705. return false;
  8706. // If the designator is valid and refers to a subobject, we're not pointing
  8707. // past the end.
  8708. if (!LV.getLValueDesignator().Invalid &&
  8709. !LV.getLValueDesignator().isOnePastTheEnd())
  8710. return false;
  8711. // A pointer to an incomplete type might be past-the-end if the type's size is
  8712. // zero. We cannot tell because the type is incomplete.
  8713. QualType Ty = getType(LV.getLValueBase());
  8714. if (Ty->isIncompleteType())
  8715. return true;
  8716. // We're a past-the-end pointer if we point to the byte after the object,
  8717. // no matter what our type or path is.
  8718. auto Size = Ctx.getTypeSizeInChars(Ty);
  8719. return LV.getLValueOffset() == Size;
  8720. }
  8721. namespace {
  8722. /// Data recursive integer evaluator of certain binary operators.
  8723. ///
  8724. /// We use a data recursive algorithm for binary operators so that we are able
  8725. /// to handle extreme cases of chained binary operators without causing stack
  8726. /// overflow.
  8727. class DataRecursiveIntBinOpEvaluator {
  8728. struct EvalResult {
  8729. APValue Val;
  8730. bool Failed;
  8731. EvalResult() : Failed(false) { }
  8732. void swap(EvalResult &RHS) {
  8733. Val.swap(RHS.Val);
  8734. Failed = RHS.Failed;
  8735. RHS.Failed = false;
  8736. }
  8737. };
  8738. struct Job {
  8739. const Expr *E;
  8740. EvalResult LHSResult; // meaningful only for binary operator expression.
  8741. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  8742. Job() = default;
  8743. Job(Job &&) = default;
  8744. void startSpeculativeEval(EvalInfo &Info) {
  8745. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  8746. }
  8747. private:
  8748. SpeculativeEvaluationRAII SpecEvalRAII;
  8749. };
  8750. SmallVector<Job, 16> Queue;
  8751. IntExprEvaluator &IntEval;
  8752. EvalInfo &Info;
  8753. APValue &FinalResult;
  8754. public:
  8755. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  8756. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  8757. /// True if \param E is a binary operator that we are going to handle
  8758. /// data recursively.
  8759. /// We handle binary operators that are comma, logical, or that have operands
  8760. /// with integral or enumeration type.
  8761. static bool shouldEnqueue(const BinaryOperator *E) {
  8762. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  8763. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  8764. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8765. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8766. }
  8767. bool Traverse(const BinaryOperator *E) {
  8768. enqueue(E);
  8769. EvalResult PrevResult;
  8770. while (!Queue.empty())
  8771. process(PrevResult);
  8772. if (PrevResult.Failed) return false;
  8773. FinalResult.swap(PrevResult.Val);
  8774. return true;
  8775. }
  8776. private:
  8777. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8778. return IntEval.Success(Value, E, Result);
  8779. }
  8780. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  8781. return IntEval.Success(Value, E, Result);
  8782. }
  8783. bool Error(const Expr *E) {
  8784. return IntEval.Error(E);
  8785. }
  8786. bool Error(const Expr *E, diag::kind D) {
  8787. return IntEval.Error(E, D);
  8788. }
  8789. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  8790. return Info.CCEDiag(E, D);
  8791. }
  8792. // Returns true if visiting the RHS is necessary, false otherwise.
  8793. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  8794. bool &SuppressRHSDiags);
  8795. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  8796. const BinaryOperator *E, APValue &Result);
  8797. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  8798. Result.Failed = !Evaluate(Result.Val, Info, E);
  8799. if (Result.Failed)
  8800. Result.Val = APValue();
  8801. }
  8802. void process(EvalResult &Result);
  8803. void enqueue(const Expr *E) {
  8804. E = E->IgnoreParens();
  8805. Queue.resize(Queue.size()+1);
  8806. Queue.back().E = E;
  8807. Queue.back().Kind = Job::AnyExprKind;
  8808. }
  8809. };
  8810. }
  8811. bool DataRecursiveIntBinOpEvaluator::
  8812. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  8813. bool &SuppressRHSDiags) {
  8814. if (E->getOpcode() == BO_Comma) {
  8815. // Ignore LHS but note if we could not evaluate it.
  8816. if (LHSResult.Failed)
  8817. return Info.noteSideEffect();
  8818. return true;
  8819. }
  8820. if (E->isLogicalOp()) {
  8821. bool LHSAsBool;
  8822. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  8823. // We were able to evaluate the LHS, see if we can get away with not
  8824. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  8825. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  8826. Success(LHSAsBool, E, LHSResult.Val);
  8827. return false; // Ignore RHS
  8828. }
  8829. } else {
  8830. LHSResult.Failed = true;
  8831. // Since we weren't able to evaluate the left hand side, it
  8832. // might have had side effects.
  8833. if (!Info.noteSideEffect())
  8834. return false;
  8835. // We can't evaluate the LHS; however, sometimes the result
  8836. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  8837. // Don't ignore RHS and suppress diagnostics from this arm.
  8838. SuppressRHSDiags = true;
  8839. }
  8840. return true;
  8841. }
  8842. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8843. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8844. if (LHSResult.Failed && !Info.noteFailure())
  8845. return false; // Ignore RHS;
  8846. return true;
  8847. }
  8848. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  8849. bool IsSub) {
  8850. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  8851. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  8852. // offsets.
  8853. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  8854. CharUnits &Offset = LVal.getLValueOffset();
  8855. uint64_t Offset64 = Offset.getQuantity();
  8856. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  8857. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  8858. : Offset64 + Index64);
  8859. }
  8860. bool DataRecursiveIntBinOpEvaluator::
  8861. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  8862. const BinaryOperator *E, APValue &Result) {
  8863. if (E->getOpcode() == BO_Comma) {
  8864. if (RHSResult.Failed)
  8865. return false;
  8866. Result = RHSResult.Val;
  8867. return true;
  8868. }
  8869. if (E->isLogicalOp()) {
  8870. bool lhsResult, rhsResult;
  8871. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  8872. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  8873. if (LHSIsOK) {
  8874. if (RHSIsOK) {
  8875. if (E->getOpcode() == BO_LOr)
  8876. return Success(lhsResult || rhsResult, E, Result);
  8877. else
  8878. return Success(lhsResult && rhsResult, E, Result);
  8879. }
  8880. } else {
  8881. if (RHSIsOK) {
  8882. // We can't evaluate the LHS; however, sometimes the result
  8883. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  8884. if (rhsResult == (E->getOpcode() == BO_LOr))
  8885. return Success(rhsResult, E, Result);
  8886. }
  8887. }
  8888. return false;
  8889. }
  8890. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8891. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8892. if (LHSResult.Failed || RHSResult.Failed)
  8893. return false;
  8894. const APValue &LHSVal = LHSResult.Val;
  8895. const APValue &RHSVal = RHSResult.Val;
  8896. // Handle cases like (unsigned long)&a + 4.
  8897. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  8898. Result = LHSVal;
  8899. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  8900. return true;
  8901. }
  8902. // Handle cases like 4 + (unsigned long)&a
  8903. if (E->getOpcode() == BO_Add &&
  8904. RHSVal.isLValue() && LHSVal.isInt()) {
  8905. Result = RHSVal;
  8906. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  8907. return true;
  8908. }
  8909. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  8910. // Handle (intptr_t)&&A - (intptr_t)&&B.
  8911. if (!LHSVal.getLValueOffset().isZero() ||
  8912. !RHSVal.getLValueOffset().isZero())
  8913. return false;
  8914. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  8915. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  8916. if (!LHSExpr || !RHSExpr)
  8917. return false;
  8918. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8919. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8920. if (!LHSAddrExpr || !RHSAddrExpr)
  8921. return false;
  8922. // Make sure both labels come from the same function.
  8923. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8924. RHSAddrExpr->getLabel()->getDeclContext())
  8925. return false;
  8926. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  8927. return true;
  8928. }
  8929. // All the remaining cases expect both operands to be an integer
  8930. if (!LHSVal.isInt() || !RHSVal.isInt())
  8931. return Error(E);
  8932. // Set up the width and signedness manually, in case it can't be deduced
  8933. // from the operation we're performing.
  8934. // FIXME: Don't do this in the cases where we can deduce it.
  8935. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  8936. E->getType()->isUnsignedIntegerOrEnumerationType());
  8937. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  8938. RHSVal.getInt(), Value))
  8939. return false;
  8940. return Success(Value, E, Result);
  8941. }
  8942. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  8943. Job &job = Queue.back();
  8944. switch (job.Kind) {
  8945. case Job::AnyExprKind: {
  8946. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  8947. if (shouldEnqueue(Bop)) {
  8948. job.Kind = Job::BinOpKind;
  8949. enqueue(Bop->getLHS());
  8950. return;
  8951. }
  8952. }
  8953. EvaluateExpr(job.E, Result);
  8954. Queue.pop_back();
  8955. return;
  8956. }
  8957. case Job::BinOpKind: {
  8958. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  8959. bool SuppressRHSDiags = false;
  8960. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  8961. Queue.pop_back();
  8962. return;
  8963. }
  8964. if (SuppressRHSDiags)
  8965. job.startSpeculativeEval(Info);
  8966. job.LHSResult.swap(Result);
  8967. job.Kind = Job::BinOpVisitedLHSKind;
  8968. enqueue(Bop->getRHS());
  8969. return;
  8970. }
  8971. case Job::BinOpVisitedLHSKind: {
  8972. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  8973. EvalResult RHS;
  8974. RHS.swap(Result);
  8975. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  8976. Queue.pop_back();
  8977. return;
  8978. }
  8979. }
  8980. llvm_unreachable("Invalid Job::Kind!");
  8981. }
  8982. namespace {
  8983. /// Used when we determine that we should fail, but can keep evaluating prior to
  8984. /// noting that we had a failure.
  8985. class DelayedNoteFailureRAII {
  8986. EvalInfo &Info;
  8987. bool NoteFailure;
  8988. public:
  8989. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  8990. : Info(Info), NoteFailure(NoteFailure) {}
  8991. ~DelayedNoteFailureRAII() {
  8992. if (NoteFailure) {
  8993. bool ContinueAfterFailure = Info.noteFailure();
  8994. (void)ContinueAfterFailure;
  8995. assert(ContinueAfterFailure &&
  8996. "Shouldn't have kept evaluating on failure.");
  8997. }
  8998. }
  8999. };
  9000. }
  9001. template <class SuccessCB, class AfterCB>
  9002. static bool
  9003. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  9004. SuccessCB &&Success, AfterCB &&DoAfter) {
  9005. assert(E->isComparisonOp() && "expected comparison operator");
  9006. assert((E->getOpcode() == BO_Cmp ||
  9007. E->getType()->isIntegralOrEnumerationType()) &&
  9008. "unsupported binary expression evaluation");
  9009. auto Error = [&](const Expr *E) {
  9010. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9011. return false;
  9012. };
  9013. using CCR = ComparisonCategoryResult;
  9014. bool IsRelational = E->isRelationalOp();
  9015. bool IsEquality = E->isEqualityOp();
  9016. if (E->getOpcode() == BO_Cmp) {
  9017. const ComparisonCategoryInfo &CmpInfo =
  9018. Info.Ctx.CompCategories.getInfoForType(E->getType());
  9019. IsRelational = CmpInfo.isOrdered();
  9020. IsEquality = CmpInfo.isEquality();
  9021. }
  9022. QualType LHSTy = E->getLHS()->getType();
  9023. QualType RHSTy = E->getRHS()->getType();
  9024. if (LHSTy->isIntegralOrEnumerationType() &&
  9025. RHSTy->isIntegralOrEnumerationType()) {
  9026. APSInt LHS, RHS;
  9027. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  9028. if (!LHSOK && !Info.noteFailure())
  9029. return false;
  9030. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  9031. return false;
  9032. if (LHS < RHS)
  9033. return Success(CCR::Less, E);
  9034. if (LHS > RHS)
  9035. return Success(CCR::Greater, E);
  9036. return Success(CCR::Equal, E);
  9037. }
  9038. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  9039. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  9040. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  9041. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  9042. if (!LHSOK && !Info.noteFailure())
  9043. return false;
  9044. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  9045. return false;
  9046. if (LHSFX < RHSFX)
  9047. return Success(CCR::Less, E);
  9048. if (LHSFX > RHSFX)
  9049. return Success(CCR::Greater, E);
  9050. return Success(CCR::Equal, E);
  9051. }
  9052. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  9053. ComplexValue LHS, RHS;
  9054. bool LHSOK;
  9055. if (E->isAssignmentOp()) {
  9056. LValue LV;
  9057. EvaluateLValue(E->getLHS(), LV, Info);
  9058. LHSOK = false;
  9059. } else if (LHSTy->isRealFloatingType()) {
  9060. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  9061. if (LHSOK) {
  9062. LHS.makeComplexFloat();
  9063. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  9064. }
  9065. } else {
  9066. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  9067. }
  9068. if (!LHSOK && !Info.noteFailure())
  9069. return false;
  9070. if (E->getRHS()->getType()->isRealFloatingType()) {
  9071. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  9072. return false;
  9073. RHS.makeComplexFloat();
  9074. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  9075. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  9076. return false;
  9077. if (LHS.isComplexFloat()) {
  9078. APFloat::cmpResult CR_r =
  9079. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  9080. APFloat::cmpResult CR_i =
  9081. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  9082. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  9083. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9084. } else {
  9085. assert(IsEquality && "invalid complex comparison");
  9086. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  9087. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  9088. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9089. }
  9090. }
  9091. if (LHSTy->isRealFloatingType() &&
  9092. RHSTy->isRealFloatingType()) {
  9093. APFloat RHS(0.0), LHS(0.0);
  9094. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  9095. if (!LHSOK && !Info.noteFailure())
  9096. return false;
  9097. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  9098. return false;
  9099. assert(E->isComparisonOp() && "Invalid binary operator!");
  9100. auto GetCmpRes = [&]() {
  9101. switch (LHS.compare(RHS)) {
  9102. case APFloat::cmpEqual:
  9103. return CCR::Equal;
  9104. case APFloat::cmpLessThan:
  9105. return CCR::Less;
  9106. case APFloat::cmpGreaterThan:
  9107. return CCR::Greater;
  9108. case APFloat::cmpUnordered:
  9109. return CCR::Unordered;
  9110. }
  9111. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  9112. };
  9113. return Success(GetCmpRes(), E);
  9114. }
  9115. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  9116. LValue LHSValue, RHSValue;
  9117. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9118. if (!LHSOK && !Info.noteFailure())
  9119. return false;
  9120. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9121. return false;
  9122. // Reject differing bases from the normal codepath; we special-case
  9123. // comparisons to null.
  9124. if (!HasSameBase(LHSValue, RHSValue)) {
  9125. // Inequalities and subtractions between unrelated pointers have
  9126. // unspecified or undefined behavior.
  9127. if (!IsEquality)
  9128. return Error(E);
  9129. // A constant address may compare equal to the address of a symbol.
  9130. // The one exception is that address of an object cannot compare equal
  9131. // to a null pointer constant.
  9132. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  9133. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  9134. return Error(E);
  9135. // It's implementation-defined whether distinct literals will have
  9136. // distinct addresses. In clang, the result of such a comparison is
  9137. // unspecified, so it is not a constant expression. However, we do know
  9138. // that the address of a literal will be non-null.
  9139. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  9140. LHSValue.Base && RHSValue.Base)
  9141. return Error(E);
  9142. // We can't tell whether weak symbols will end up pointing to the same
  9143. // object.
  9144. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  9145. return Error(E);
  9146. // We can't compare the address of the start of one object with the
  9147. // past-the-end address of another object, per C++ DR1652.
  9148. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  9149. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  9150. (RHSValue.Base && RHSValue.Offset.isZero() &&
  9151. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  9152. return Error(E);
  9153. // We can't tell whether an object is at the same address as another
  9154. // zero sized object.
  9155. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  9156. (LHSValue.Base && isZeroSized(RHSValue)))
  9157. return Error(E);
  9158. return Success(CCR::Nonequal, E);
  9159. }
  9160. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9161. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9162. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9163. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9164. // C++11 [expr.rel]p3:
  9165. // Pointers to void (after pointer conversions) can be compared, with a
  9166. // result defined as follows: If both pointers represent the same
  9167. // address or are both the null pointer value, the result is true if the
  9168. // operator is <= or >= and false otherwise; otherwise the result is
  9169. // unspecified.
  9170. // We interpret this as applying to pointers to *cv* void.
  9171. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  9172. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  9173. // C++11 [expr.rel]p2:
  9174. // - If two pointers point to non-static data members of the same object,
  9175. // or to subobjects or array elements fo such members, recursively, the
  9176. // pointer to the later declared member compares greater provided the
  9177. // two members have the same access control and provided their class is
  9178. // not a union.
  9179. // [...]
  9180. // - Otherwise pointer comparisons are unspecified.
  9181. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  9182. bool WasArrayIndex;
  9183. unsigned Mismatch = FindDesignatorMismatch(
  9184. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  9185. // At the point where the designators diverge, the comparison has a
  9186. // specified value if:
  9187. // - we are comparing array indices
  9188. // - we are comparing fields of a union, or fields with the same access
  9189. // Otherwise, the result is unspecified and thus the comparison is not a
  9190. // constant expression.
  9191. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  9192. Mismatch < RHSDesignator.Entries.size()) {
  9193. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  9194. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  9195. if (!LF && !RF)
  9196. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  9197. else if (!LF)
  9198. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9199. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  9200. << RF->getParent() << RF;
  9201. else if (!RF)
  9202. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9203. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  9204. << LF->getParent() << LF;
  9205. else if (!LF->getParent()->isUnion() &&
  9206. LF->getAccess() != RF->getAccess())
  9207. Info.CCEDiag(E,
  9208. diag::note_constexpr_pointer_comparison_differing_access)
  9209. << LF << LF->getAccess() << RF << RF->getAccess()
  9210. << LF->getParent();
  9211. }
  9212. }
  9213. // The comparison here must be unsigned, and performed with the same
  9214. // width as the pointer.
  9215. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  9216. uint64_t CompareLHS = LHSOffset.getQuantity();
  9217. uint64_t CompareRHS = RHSOffset.getQuantity();
  9218. assert(PtrSize <= 64 && "Unexpected pointer width");
  9219. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  9220. CompareLHS &= Mask;
  9221. CompareRHS &= Mask;
  9222. // If there is a base and this is a relational operator, we can only
  9223. // compare pointers within the object in question; otherwise, the result
  9224. // depends on where the object is located in memory.
  9225. if (!LHSValue.Base.isNull() && IsRelational) {
  9226. QualType BaseTy = getType(LHSValue.Base);
  9227. if (BaseTy->isIncompleteType())
  9228. return Error(E);
  9229. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  9230. uint64_t OffsetLimit = Size.getQuantity();
  9231. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  9232. return Error(E);
  9233. }
  9234. if (CompareLHS < CompareRHS)
  9235. return Success(CCR::Less, E);
  9236. if (CompareLHS > CompareRHS)
  9237. return Success(CCR::Greater, E);
  9238. return Success(CCR::Equal, E);
  9239. }
  9240. if (LHSTy->isMemberPointerType()) {
  9241. assert(IsEquality && "unexpected member pointer operation");
  9242. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  9243. MemberPtr LHSValue, RHSValue;
  9244. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  9245. if (!LHSOK && !Info.noteFailure())
  9246. return false;
  9247. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9248. return false;
  9249. // C++11 [expr.eq]p2:
  9250. // If both operands are null, they compare equal. Otherwise if only one is
  9251. // null, they compare unequal.
  9252. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  9253. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  9254. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  9255. }
  9256. // Otherwise if either is a pointer to a virtual member function, the
  9257. // result is unspecified.
  9258. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  9259. if (MD->isVirtual())
  9260. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  9261. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  9262. if (MD->isVirtual())
  9263. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  9264. // Otherwise they compare equal if and only if they would refer to the
  9265. // same member of the same most derived object or the same subobject if
  9266. // they were dereferenced with a hypothetical object of the associated
  9267. // class type.
  9268. bool Equal = LHSValue == RHSValue;
  9269. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  9270. }
  9271. if (LHSTy->isNullPtrType()) {
  9272. assert(E->isComparisonOp() && "unexpected nullptr operation");
  9273. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  9274. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  9275. // are compared, the result is true of the operator is <=, >= or ==, and
  9276. // false otherwise.
  9277. return Success(CCR::Equal, E);
  9278. }
  9279. return DoAfter();
  9280. }
  9281. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  9282. if (!CheckLiteralType(Info, E))
  9283. return false;
  9284. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  9285. const BinaryOperator *E) {
  9286. // Evaluation succeeded. Lookup the information for the comparison category
  9287. // type and fetch the VarDecl for the result.
  9288. const ComparisonCategoryInfo &CmpInfo =
  9289. Info.Ctx.CompCategories.getInfoForType(E->getType());
  9290. const VarDecl *VD =
  9291. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  9292. // Check and evaluate the result as a constant expression.
  9293. LValue LV;
  9294. LV.set(VD);
  9295. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  9296. return false;
  9297. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  9298. };
  9299. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  9300. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  9301. });
  9302. }
  9303. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9304. // We don't call noteFailure immediately because the assignment happens after
  9305. // we evaluate LHS and RHS.
  9306. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  9307. return Error(E);
  9308. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  9309. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  9310. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  9311. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  9312. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  9313. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  9314. if (E->isComparisonOp()) {
  9315. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  9316. // comparisons and then translating the result.
  9317. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  9318. const BinaryOperator *E) {
  9319. using CCR = ComparisonCategoryResult;
  9320. bool IsEqual = ResKind == CCR::Equal,
  9321. IsLess = ResKind == CCR::Less,
  9322. IsGreater = ResKind == CCR::Greater;
  9323. auto Op = E->getOpcode();
  9324. switch (Op) {
  9325. default:
  9326. llvm_unreachable("unsupported binary operator");
  9327. case BO_EQ:
  9328. case BO_NE:
  9329. return Success(IsEqual == (Op == BO_EQ), E);
  9330. case BO_LT: return Success(IsLess, E);
  9331. case BO_GT: return Success(IsGreater, E);
  9332. case BO_LE: return Success(IsEqual || IsLess, E);
  9333. case BO_GE: return Success(IsEqual || IsGreater, E);
  9334. }
  9335. };
  9336. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  9337. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9338. });
  9339. }
  9340. QualType LHSTy = E->getLHS()->getType();
  9341. QualType RHSTy = E->getRHS()->getType();
  9342. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  9343. E->getOpcode() == BO_Sub) {
  9344. LValue LHSValue, RHSValue;
  9345. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9346. if (!LHSOK && !Info.noteFailure())
  9347. return false;
  9348. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9349. return false;
  9350. // Reject differing bases from the normal codepath; we special-case
  9351. // comparisons to null.
  9352. if (!HasSameBase(LHSValue, RHSValue)) {
  9353. // Handle &&A - &&B.
  9354. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  9355. return Error(E);
  9356. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  9357. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  9358. if (!LHSExpr || !RHSExpr)
  9359. return Error(E);
  9360. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9361. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9362. if (!LHSAddrExpr || !RHSAddrExpr)
  9363. return Error(E);
  9364. // Make sure both labels come from the same function.
  9365. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9366. RHSAddrExpr->getLabel()->getDeclContext())
  9367. return Error(E);
  9368. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  9369. }
  9370. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9371. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9372. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9373. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9374. // C++11 [expr.add]p6:
  9375. // Unless both pointers point to elements of the same array object, or
  9376. // one past the last element of the array object, the behavior is
  9377. // undefined.
  9378. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  9379. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  9380. RHSDesignator))
  9381. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  9382. QualType Type = E->getLHS()->getType();
  9383. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  9384. CharUnits ElementSize;
  9385. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  9386. return false;
  9387. // As an extension, a type may have zero size (empty struct or union in
  9388. // C, array of zero length). Pointer subtraction in such cases has
  9389. // undefined behavior, so is not constant.
  9390. if (ElementSize.isZero()) {
  9391. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  9392. << ElementType;
  9393. return false;
  9394. }
  9395. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  9396. // and produce incorrect results when it overflows. Such behavior
  9397. // appears to be non-conforming, but is common, so perhaps we should
  9398. // assume the standard intended for such cases to be undefined behavior
  9399. // and check for them.
  9400. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  9401. // overflow in the final conversion to ptrdiff_t.
  9402. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  9403. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  9404. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  9405. false);
  9406. APSInt TrueResult = (LHS - RHS) / ElemSize;
  9407. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  9408. if (Result.extend(65) != TrueResult &&
  9409. !HandleOverflow(Info, E, TrueResult, E->getType()))
  9410. return false;
  9411. return Success(Result, E);
  9412. }
  9413. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9414. }
  9415. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  9416. /// a result as the expression's type.
  9417. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  9418. const UnaryExprOrTypeTraitExpr *E) {
  9419. switch(E->getKind()) {
  9420. case UETT_PreferredAlignOf:
  9421. case UETT_AlignOf: {
  9422. if (E->isArgumentType())
  9423. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  9424. E);
  9425. else
  9426. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  9427. E);
  9428. }
  9429. case UETT_VecStep: {
  9430. QualType Ty = E->getTypeOfArgument();
  9431. if (Ty->isVectorType()) {
  9432. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  9433. // The vec_step built-in functions that take a 3-component
  9434. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  9435. if (n == 3)
  9436. n = 4;
  9437. return Success(n, E);
  9438. } else
  9439. return Success(1, E);
  9440. }
  9441. case UETT_SizeOf: {
  9442. QualType SrcTy = E->getTypeOfArgument();
  9443. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  9444. // the result is the size of the referenced type."
  9445. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  9446. SrcTy = Ref->getPointeeType();
  9447. CharUnits Sizeof;
  9448. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  9449. return false;
  9450. return Success(Sizeof, E);
  9451. }
  9452. case UETT_OpenMPRequiredSimdAlign:
  9453. assert(E->isArgumentType());
  9454. return Success(
  9455. Info.Ctx.toCharUnitsFromBits(
  9456. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  9457. .getQuantity(),
  9458. E);
  9459. }
  9460. llvm_unreachable("unknown expr/type trait");
  9461. }
  9462. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  9463. CharUnits Result;
  9464. unsigned n = OOE->getNumComponents();
  9465. if (n == 0)
  9466. return Error(OOE);
  9467. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  9468. for (unsigned i = 0; i != n; ++i) {
  9469. OffsetOfNode ON = OOE->getComponent(i);
  9470. switch (ON.getKind()) {
  9471. case OffsetOfNode::Array: {
  9472. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  9473. APSInt IdxResult;
  9474. if (!EvaluateInteger(Idx, IdxResult, Info))
  9475. return false;
  9476. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  9477. if (!AT)
  9478. return Error(OOE);
  9479. CurrentType = AT->getElementType();
  9480. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  9481. Result += IdxResult.getSExtValue() * ElementSize;
  9482. break;
  9483. }
  9484. case OffsetOfNode::Field: {
  9485. FieldDecl *MemberDecl = ON.getField();
  9486. const RecordType *RT = CurrentType->getAs<RecordType>();
  9487. if (!RT)
  9488. return Error(OOE);
  9489. RecordDecl *RD = RT->getDecl();
  9490. if (RD->isInvalidDecl()) return false;
  9491. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  9492. unsigned i = MemberDecl->getFieldIndex();
  9493. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  9494. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  9495. CurrentType = MemberDecl->getType().getNonReferenceType();
  9496. break;
  9497. }
  9498. case OffsetOfNode::Identifier:
  9499. llvm_unreachable("dependent __builtin_offsetof");
  9500. case OffsetOfNode::Base: {
  9501. CXXBaseSpecifier *BaseSpec = ON.getBase();
  9502. if (BaseSpec->isVirtual())
  9503. return Error(OOE);
  9504. // Find the layout of the class whose base we are looking into.
  9505. const RecordType *RT = CurrentType->getAs<RecordType>();
  9506. if (!RT)
  9507. return Error(OOE);
  9508. RecordDecl *RD = RT->getDecl();
  9509. if (RD->isInvalidDecl()) return false;
  9510. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  9511. // Find the base class itself.
  9512. CurrentType = BaseSpec->getType();
  9513. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  9514. if (!BaseRT)
  9515. return Error(OOE);
  9516. // Add the offset to the base.
  9517. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  9518. break;
  9519. }
  9520. }
  9521. }
  9522. return Success(Result, OOE);
  9523. }
  9524. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9525. switch (E->getOpcode()) {
  9526. default:
  9527. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  9528. // See C99 6.6p3.
  9529. return Error(E);
  9530. case UO_Extension:
  9531. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  9532. // If so, we could clear the diagnostic ID.
  9533. return Visit(E->getSubExpr());
  9534. case UO_Plus:
  9535. // The result is just the value.
  9536. return Visit(E->getSubExpr());
  9537. case UO_Minus: {
  9538. if (!Visit(E->getSubExpr()))
  9539. return false;
  9540. if (!Result.isInt()) return Error(E);
  9541. const APSInt &Value = Result.getInt();
  9542. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  9543. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  9544. E->getType()))
  9545. return false;
  9546. return Success(-Value, E);
  9547. }
  9548. case UO_Not: {
  9549. if (!Visit(E->getSubExpr()))
  9550. return false;
  9551. if (!Result.isInt()) return Error(E);
  9552. return Success(~Result.getInt(), E);
  9553. }
  9554. case UO_LNot: {
  9555. bool bres;
  9556. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  9557. return false;
  9558. return Success(!bres, E);
  9559. }
  9560. }
  9561. }
  9562. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  9563. /// result type is integer.
  9564. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9565. const Expr *SubExpr = E->getSubExpr();
  9566. QualType DestType = E->getType();
  9567. QualType SrcType = SubExpr->getType();
  9568. switch (E->getCastKind()) {
  9569. case CK_BaseToDerived:
  9570. case CK_DerivedToBase:
  9571. case CK_UncheckedDerivedToBase:
  9572. case CK_Dynamic:
  9573. case CK_ToUnion:
  9574. case CK_ArrayToPointerDecay:
  9575. case CK_FunctionToPointerDecay:
  9576. case CK_NullToPointer:
  9577. case CK_NullToMemberPointer:
  9578. case CK_BaseToDerivedMemberPointer:
  9579. case CK_DerivedToBaseMemberPointer:
  9580. case CK_ReinterpretMemberPointer:
  9581. case CK_ConstructorConversion:
  9582. case CK_IntegralToPointer:
  9583. case CK_ToVoid:
  9584. case CK_VectorSplat:
  9585. case CK_IntegralToFloating:
  9586. case CK_FloatingCast:
  9587. case CK_CPointerToObjCPointerCast:
  9588. case CK_BlockPointerToObjCPointerCast:
  9589. case CK_AnyPointerToBlockPointerCast:
  9590. case CK_ObjCObjectLValueCast:
  9591. case CK_FloatingRealToComplex:
  9592. case CK_FloatingComplexToReal:
  9593. case CK_FloatingComplexCast:
  9594. case CK_FloatingComplexToIntegralComplex:
  9595. case CK_IntegralRealToComplex:
  9596. case CK_IntegralComplexCast:
  9597. case CK_IntegralComplexToFloatingComplex:
  9598. case CK_BuiltinFnToFnPtr:
  9599. case CK_ZeroToOCLOpaqueType:
  9600. case CK_NonAtomicToAtomic:
  9601. case CK_AddressSpaceConversion:
  9602. case CK_IntToOCLSampler:
  9603. case CK_FixedPointCast:
  9604. case CK_IntegralToFixedPoint:
  9605. llvm_unreachable("invalid cast kind for integral value");
  9606. case CK_BitCast:
  9607. case CK_Dependent:
  9608. case CK_LValueBitCast:
  9609. case CK_ARCProduceObject:
  9610. case CK_ARCConsumeObject:
  9611. case CK_ARCReclaimReturnedObject:
  9612. case CK_ARCExtendBlockObject:
  9613. case CK_CopyAndAutoreleaseBlockObject:
  9614. return Error(E);
  9615. case CK_UserDefinedConversion:
  9616. case CK_LValueToRValue:
  9617. case CK_AtomicToNonAtomic:
  9618. case CK_NoOp:
  9619. case CK_LValueToRValueBitCast:
  9620. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9621. case CK_MemberPointerToBoolean:
  9622. case CK_PointerToBoolean:
  9623. case CK_IntegralToBoolean:
  9624. case CK_FloatingToBoolean:
  9625. case CK_BooleanToSignedIntegral:
  9626. case CK_FloatingComplexToBoolean:
  9627. case CK_IntegralComplexToBoolean: {
  9628. bool BoolResult;
  9629. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  9630. return false;
  9631. uint64_t IntResult = BoolResult;
  9632. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  9633. IntResult = (uint64_t)-1;
  9634. return Success(IntResult, E);
  9635. }
  9636. case CK_FixedPointToIntegral: {
  9637. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  9638. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  9639. return false;
  9640. bool Overflowed;
  9641. llvm::APSInt Result = Src.convertToInt(
  9642. Info.Ctx.getIntWidth(DestType),
  9643. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  9644. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  9645. return false;
  9646. return Success(Result, E);
  9647. }
  9648. case CK_FixedPointToBoolean: {
  9649. // Unsigned padding does not affect this.
  9650. APValue Val;
  9651. if (!Evaluate(Val, Info, SubExpr))
  9652. return false;
  9653. return Success(Val.getFixedPoint().getBoolValue(), E);
  9654. }
  9655. case CK_IntegralCast: {
  9656. if (!Visit(SubExpr))
  9657. return false;
  9658. if (!Result.isInt()) {
  9659. // Allow casts of address-of-label differences if they are no-ops
  9660. // or narrowing. (The narrowing case isn't actually guaranteed to
  9661. // be constant-evaluatable except in some narrow cases which are hard
  9662. // to detect here. We let it through on the assumption the user knows
  9663. // what they are doing.)
  9664. if (Result.isAddrLabelDiff())
  9665. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  9666. // Only allow casts of lvalues if they are lossless.
  9667. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  9668. }
  9669. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  9670. Result.getInt()), E);
  9671. }
  9672. case CK_PointerToIntegral: {
  9673. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  9674. LValue LV;
  9675. if (!EvaluatePointer(SubExpr, LV, Info))
  9676. return false;
  9677. if (LV.getLValueBase()) {
  9678. // Only allow based lvalue casts if they are lossless.
  9679. // FIXME: Allow a larger integer size than the pointer size, and allow
  9680. // narrowing back down to pointer width in subsequent integral casts.
  9681. // FIXME: Check integer type's active bits, not its type size.
  9682. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  9683. return Error(E);
  9684. LV.Designator.setInvalid();
  9685. LV.moveInto(Result);
  9686. return true;
  9687. }
  9688. APSInt AsInt;
  9689. APValue V;
  9690. LV.moveInto(V);
  9691. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  9692. llvm_unreachable("Can't cast this!");
  9693. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  9694. }
  9695. case CK_IntegralComplexToReal: {
  9696. ComplexValue C;
  9697. if (!EvaluateComplex(SubExpr, C, Info))
  9698. return false;
  9699. return Success(C.getComplexIntReal(), E);
  9700. }
  9701. case CK_FloatingToIntegral: {
  9702. APFloat F(0.0);
  9703. if (!EvaluateFloat(SubExpr, F, Info))
  9704. return false;
  9705. APSInt Value;
  9706. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  9707. return false;
  9708. return Success(Value, E);
  9709. }
  9710. }
  9711. llvm_unreachable("unknown cast resulting in integral value");
  9712. }
  9713. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  9714. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9715. ComplexValue LV;
  9716. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  9717. return false;
  9718. if (!LV.isComplexInt())
  9719. return Error(E);
  9720. return Success(LV.getComplexIntReal(), E);
  9721. }
  9722. return Visit(E->getSubExpr());
  9723. }
  9724. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9725. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  9726. ComplexValue LV;
  9727. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  9728. return false;
  9729. if (!LV.isComplexInt())
  9730. return Error(E);
  9731. return Success(LV.getComplexIntImag(), E);
  9732. }
  9733. VisitIgnoredValue(E->getSubExpr());
  9734. return Success(0, E);
  9735. }
  9736. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  9737. return Success(E->getPackLength(), E);
  9738. }
  9739. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  9740. return Success(E->getValue(), E);
  9741. }
  9742. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9743. switch (E->getOpcode()) {
  9744. default:
  9745. // Invalid unary operators
  9746. return Error(E);
  9747. case UO_Plus:
  9748. // The result is just the value.
  9749. return Visit(E->getSubExpr());
  9750. case UO_Minus: {
  9751. if (!Visit(E->getSubExpr())) return false;
  9752. if (!Result.isFixedPoint())
  9753. return Error(E);
  9754. bool Overflowed;
  9755. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  9756. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  9757. return false;
  9758. return Success(Negated, E);
  9759. }
  9760. case UO_LNot: {
  9761. bool bres;
  9762. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  9763. return false;
  9764. return Success(!bres, E);
  9765. }
  9766. }
  9767. }
  9768. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9769. const Expr *SubExpr = E->getSubExpr();
  9770. QualType DestType = E->getType();
  9771. assert(DestType->isFixedPointType() &&
  9772. "Expected destination type to be a fixed point type");
  9773. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  9774. switch (E->getCastKind()) {
  9775. case CK_FixedPointCast: {
  9776. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  9777. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  9778. return false;
  9779. bool Overflowed;
  9780. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  9781. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  9782. return false;
  9783. return Success(Result, E);
  9784. }
  9785. case CK_IntegralToFixedPoint: {
  9786. APSInt Src;
  9787. if (!EvaluateInteger(SubExpr, Src, Info))
  9788. return false;
  9789. bool Overflowed;
  9790. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  9791. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  9792. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  9793. return false;
  9794. return Success(IntResult, E);
  9795. }
  9796. case CK_NoOp:
  9797. case CK_LValueToRValue:
  9798. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9799. default:
  9800. return Error(E);
  9801. }
  9802. }
  9803. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9804. const Expr *LHS = E->getLHS();
  9805. const Expr *RHS = E->getRHS();
  9806. FixedPointSemantics ResultFXSema =
  9807. Info.Ctx.getFixedPointSemantics(E->getType());
  9808. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  9809. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  9810. return false;
  9811. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  9812. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  9813. return false;
  9814. switch (E->getOpcode()) {
  9815. case BO_Add: {
  9816. bool AddOverflow, ConversionOverflow;
  9817. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  9818. .convert(ResultFXSema, &ConversionOverflow);
  9819. if ((AddOverflow || ConversionOverflow) &&
  9820. !HandleOverflow(Info, E, Result, E->getType()))
  9821. return false;
  9822. return Success(Result, E);
  9823. }
  9824. default:
  9825. return false;
  9826. }
  9827. llvm_unreachable("Should've exited before this");
  9828. }
  9829. //===----------------------------------------------------------------------===//
  9830. // Float Evaluation
  9831. //===----------------------------------------------------------------------===//
  9832. namespace {
  9833. class FloatExprEvaluator
  9834. : public ExprEvaluatorBase<FloatExprEvaluator> {
  9835. APFloat &Result;
  9836. public:
  9837. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  9838. : ExprEvaluatorBaseTy(info), Result(result) {}
  9839. bool Success(const APValue &V, const Expr *e) {
  9840. Result = V.getFloat();
  9841. return true;
  9842. }
  9843. bool ZeroInitialization(const Expr *E) {
  9844. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  9845. return true;
  9846. }
  9847. bool VisitCallExpr(const CallExpr *E);
  9848. bool VisitUnaryOperator(const UnaryOperator *E);
  9849. bool VisitBinaryOperator(const BinaryOperator *E);
  9850. bool VisitFloatingLiteral(const FloatingLiteral *E);
  9851. bool VisitCastExpr(const CastExpr *E);
  9852. bool VisitUnaryReal(const UnaryOperator *E);
  9853. bool VisitUnaryImag(const UnaryOperator *E);
  9854. // FIXME: Missing: array subscript of vector, member of vector
  9855. };
  9856. } // end anonymous namespace
  9857. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  9858. assert(E->isRValue() && E->getType()->isRealFloatingType());
  9859. return FloatExprEvaluator(Info, Result).Visit(E);
  9860. }
  9861. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  9862. QualType ResultTy,
  9863. const Expr *Arg,
  9864. bool SNaN,
  9865. llvm::APFloat &Result) {
  9866. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  9867. if (!S) return false;
  9868. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  9869. llvm::APInt fill;
  9870. // Treat empty strings as if they were zero.
  9871. if (S->getString().empty())
  9872. fill = llvm::APInt(32, 0);
  9873. else if (S->getString().getAsInteger(0, fill))
  9874. return false;
  9875. if (Context.getTargetInfo().isNan2008()) {
  9876. if (SNaN)
  9877. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  9878. else
  9879. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  9880. } else {
  9881. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  9882. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  9883. // a different encoding to what became a standard in 2008, and for pre-
  9884. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  9885. // sNaN. This is now known as "legacy NaN" encoding.
  9886. if (SNaN)
  9887. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  9888. else
  9889. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  9890. }
  9891. return true;
  9892. }
  9893. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  9894. switch (E->getBuiltinCallee()) {
  9895. default:
  9896. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9897. case Builtin::BI__builtin_huge_val:
  9898. case Builtin::BI__builtin_huge_valf:
  9899. case Builtin::BI__builtin_huge_vall:
  9900. case Builtin::BI__builtin_huge_valf128:
  9901. case Builtin::BI__builtin_inf:
  9902. case Builtin::BI__builtin_inff:
  9903. case Builtin::BI__builtin_infl:
  9904. case Builtin::BI__builtin_inff128: {
  9905. const llvm::fltSemantics &Sem =
  9906. Info.Ctx.getFloatTypeSemantics(E->getType());
  9907. Result = llvm::APFloat::getInf(Sem);
  9908. return true;
  9909. }
  9910. case Builtin::BI__builtin_nans:
  9911. case Builtin::BI__builtin_nansf:
  9912. case Builtin::BI__builtin_nansl:
  9913. case Builtin::BI__builtin_nansf128:
  9914. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  9915. true, Result))
  9916. return Error(E);
  9917. return true;
  9918. case Builtin::BI__builtin_nan:
  9919. case Builtin::BI__builtin_nanf:
  9920. case Builtin::BI__builtin_nanl:
  9921. case Builtin::BI__builtin_nanf128:
  9922. // If this is __builtin_nan() turn this into a nan, otherwise we
  9923. // can't constant fold it.
  9924. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  9925. false, Result))
  9926. return Error(E);
  9927. return true;
  9928. case Builtin::BI__builtin_fabs:
  9929. case Builtin::BI__builtin_fabsf:
  9930. case Builtin::BI__builtin_fabsl:
  9931. case Builtin::BI__builtin_fabsf128:
  9932. if (!EvaluateFloat(E->getArg(0), Result, Info))
  9933. return false;
  9934. if (Result.isNegative())
  9935. Result.changeSign();
  9936. return true;
  9937. // FIXME: Builtin::BI__builtin_powi
  9938. // FIXME: Builtin::BI__builtin_powif
  9939. // FIXME: Builtin::BI__builtin_powil
  9940. case Builtin::BI__builtin_copysign:
  9941. case Builtin::BI__builtin_copysignf:
  9942. case Builtin::BI__builtin_copysignl:
  9943. case Builtin::BI__builtin_copysignf128: {
  9944. APFloat RHS(0.);
  9945. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  9946. !EvaluateFloat(E->getArg(1), RHS, Info))
  9947. return false;
  9948. Result.copySign(RHS);
  9949. return true;
  9950. }
  9951. }
  9952. }
  9953. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  9954. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9955. ComplexValue CV;
  9956. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  9957. return false;
  9958. Result = CV.FloatReal;
  9959. return true;
  9960. }
  9961. return Visit(E->getSubExpr());
  9962. }
  9963. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9964. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9965. ComplexValue CV;
  9966. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  9967. return false;
  9968. Result = CV.FloatImag;
  9969. return true;
  9970. }
  9971. VisitIgnoredValue(E->getSubExpr());
  9972. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  9973. Result = llvm::APFloat::getZero(Sem);
  9974. return true;
  9975. }
  9976. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9977. switch (E->getOpcode()) {
  9978. default: return Error(E);
  9979. case UO_Plus:
  9980. return EvaluateFloat(E->getSubExpr(), Result, Info);
  9981. case UO_Minus:
  9982. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  9983. return false;
  9984. Result.changeSign();
  9985. return true;
  9986. }
  9987. }
  9988. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9989. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  9990. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9991. APFloat RHS(0.0);
  9992. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  9993. if (!LHSOK && !Info.noteFailure())
  9994. return false;
  9995. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  9996. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  9997. }
  9998. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  9999. Result = E->getValue();
  10000. return true;
  10001. }
  10002. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10003. const Expr* SubExpr = E->getSubExpr();
  10004. switch (E->getCastKind()) {
  10005. default:
  10006. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10007. case CK_IntegralToFloating: {
  10008. APSInt IntResult;
  10009. return EvaluateInteger(SubExpr, IntResult, Info) &&
  10010. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  10011. E->getType(), Result);
  10012. }
  10013. case CK_FloatingCast: {
  10014. if (!Visit(SubExpr))
  10015. return false;
  10016. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  10017. Result);
  10018. }
  10019. case CK_FloatingComplexToReal: {
  10020. ComplexValue V;
  10021. if (!EvaluateComplex(SubExpr, V, Info))
  10022. return false;
  10023. Result = V.getComplexFloatReal();
  10024. return true;
  10025. }
  10026. }
  10027. }
  10028. //===----------------------------------------------------------------------===//
  10029. // Complex Evaluation (for float and integer)
  10030. //===----------------------------------------------------------------------===//
  10031. namespace {
  10032. class ComplexExprEvaluator
  10033. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  10034. ComplexValue &Result;
  10035. public:
  10036. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  10037. : ExprEvaluatorBaseTy(info), Result(Result) {}
  10038. bool Success(const APValue &V, const Expr *e) {
  10039. Result.setFrom(V);
  10040. return true;
  10041. }
  10042. bool ZeroInitialization(const Expr *E);
  10043. //===--------------------------------------------------------------------===//
  10044. // Visitor Methods
  10045. //===--------------------------------------------------------------------===//
  10046. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  10047. bool VisitCastExpr(const CastExpr *E);
  10048. bool VisitBinaryOperator(const BinaryOperator *E);
  10049. bool VisitUnaryOperator(const UnaryOperator *E);
  10050. bool VisitInitListExpr(const InitListExpr *E);
  10051. };
  10052. } // end anonymous namespace
  10053. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  10054. EvalInfo &Info) {
  10055. assert(E->isRValue() && E->getType()->isAnyComplexType());
  10056. return ComplexExprEvaluator(Info, Result).Visit(E);
  10057. }
  10058. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  10059. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  10060. if (ElemTy->isRealFloatingType()) {
  10061. Result.makeComplexFloat();
  10062. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  10063. Result.FloatReal = Zero;
  10064. Result.FloatImag = Zero;
  10065. } else {
  10066. Result.makeComplexInt();
  10067. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  10068. Result.IntReal = Zero;
  10069. Result.IntImag = Zero;
  10070. }
  10071. return true;
  10072. }
  10073. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  10074. const Expr* SubExpr = E->getSubExpr();
  10075. if (SubExpr->getType()->isRealFloatingType()) {
  10076. Result.makeComplexFloat();
  10077. APFloat &Imag = Result.FloatImag;
  10078. if (!EvaluateFloat(SubExpr, Imag, Info))
  10079. return false;
  10080. Result.FloatReal = APFloat(Imag.getSemantics());
  10081. return true;
  10082. } else {
  10083. assert(SubExpr->getType()->isIntegerType() &&
  10084. "Unexpected imaginary literal.");
  10085. Result.makeComplexInt();
  10086. APSInt &Imag = Result.IntImag;
  10087. if (!EvaluateInteger(SubExpr, Imag, Info))
  10088. return false;
  10089. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  10090. return true;
  10091. }
  10092. }
  10093. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10094. switch (E->getCastKind()) {
  10095. case CK_BitCast:
  10096. case CK_BaseToDerived:
  10097. case CK_DerivedToBase:
  10098. case CK_UncheckedDerivedToBase:
  10099. case CK_Dynamic:
  10100. case CK_ToUnion:
  10101. case CK_ArrayToPointerDecay:
  10102. case CK_FunctionToPointerDecay:
  10103. case CK_NullToPointer:
  10104. case CK_NullToMemberPointer:
  10105. case CK_BaseToDerivedMemberPointer:
  10106. case CK_DerivedToBaseMemberPointer:
  10107. case CK_MemberPointerToBoolean:
  10108. case CK_ReinterpretMemberPointer:
  10109. case CK_ConstructorConversion:
  10110. case CK_IntegralToPointer:
  10111. case CK_PointerToIntegral:
  10112. case CK_PointerToBoolean:
  10113. case CK_ToVoid:
  10114. case CK_VectorSplat:
  10115. case CK_IntegralCast:
  10116. case CK_BooleanToSignedIntegral:
  10117. case CK_IntegralToBoolean:
  10118. case CK_IntegralToFloating:
  10119. case CK_FloatingToIntegral:
  10120. case CK_FloatingToBoolean:
  10121. case CK_FloatingCast:
  10122. case CK_CPointerToObjCPointerCast:
  10123. case CK_BlockPointerToObjCPointerCast:
  10124. case CK_AnyPointerToBlockPointerCast:
  10125. case CK_ObjCObjectLValueCast:
  10126. case CK_FloatingComplexToReal:
  10127. case CK_FloatingComplexToBoolean:
  10128. case CK_IntegralComplexToReal:
  10129. case CK_IntegralComplexToBoolean:
  10130. case CK_ARCProduceObject:
  10131. case CK_ARCConsumeObject:
  10132. case CK_ARCReclaimReturnedObject:
  10133. case CK_ARCExtendBlockObject:
  10134. case CK_CopyAndAutoreleaseBlockObject:
  10135. case CK_BuiltinFnToFnPtr:
  10136. case CK_ZeroToOCLOpaqueType:
  10137. case CK_NonAtomicToAtomic:
  10138. case CK_AddressSpaceConversion:
  10139. case CK_IntToOCLSampler:
  10140. case CK_FixedPointCast:
  10141. case CK_FixedPointToBoolean:
  10142. case CK_FixedPointToIntegral:
  10143. case CK_IntegralToFixedPoint:
  10144. llvm_unreachable("invalid cast kind for complex value");
  10145. case CK_LValueToRValue:
  10146. case CK_AtomicToNonAtomic:
  10147. case CK_NoOp:
  10148. case CK_LValueToRValueBitCast:
  10149. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10150. case CK_Dependent:
  10151. case CK_LValueBitCast:
  10152. case CK_UserDefinedConversion:
  10153. return Error(E);
  10154. case CK_FloatingRealToComplex: {
  10155. APFloat &Real = Result.FloatReal;
  10156. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  10157. return false;
  10158. Result.makeComplexFloat();
  10159. Result.FloatImag = APFloat(Real.getSemantics());
  10160. return true;
  10161. }
  10162. case CK_FloatingComplexCast: {
  10163. if (!Visit(E->getSubExpr()))
  10164. return false;
  10165. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10166. QualType From
  10167. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10168. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  10169. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  10170. }
  10171. case CK_FloatingComplexToIntegralComplex: {
  10172. if (!Visit(E->getSubExpr()))
  10173. return false;
  10174. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10175. QualType From
  10176. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10177. Result.makeComplexInt();
  10178. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  10179. To, Result.IntReal) &&
  10180. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  10181. To, Result.IntImag);
  10182. }
  10183. case CK_IntegralRealToComplex: {
  10184. APSInt &Real = Result.IntReal;
  10185. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  10186. return false;
  10187. Result.makeComplexInt();
  10188. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  10189. return true;
  10190. }
  10191. case CK_IntegralComplexCast: {
  10192. if (!Visit(E->getSubExpr()))
  10193. return false;
  10194. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10195. QualType From
  10196. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10197. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  10198. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  10199. return true;
  10200. }
  10201. case CK_IntegralComplexToFloatingComplex: {
  10202. if (!Visit(E->getSubExpr()))
  10203. return false;
  10204. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  10205. QualType From
  10206. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  10207. Result.makeComplexFloat();
  10208. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  10209. To, Result.FloatReal) &&
  10210. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  10211. To, Result.FloatImag);
  10212. }
  10213. }
  10214. llvm_unreachable("unknown cast resulting in complex value");
  10215. }
  10216. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10217. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10218. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10219. // Track whether the LHS or RHS is real at the type system level. When this is
  10220. // the case we can simplify our evaluation strategy.
  10221. bool LHSReal = false, RHSReal = false;
  10222. bool LHSOK;
  10223. if (E->getLHS()->getType()->isRealFloatingType()) {
  10224. LHSReal = true;
  10225. APFloat &Real = Result.FloatReal;
  10226. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  10227. if (LHSOK) {
  10228. Result.makeComplexFloat();
  10229. Result.FloatImag = APFloat(Real.getSemantics());
  10230. }
  10231. } else {
  10232. LHSOK = Visit(E->getLHS());
  10233. }
  10234. if (!LHSOK && !Info.noteFailure())
  10235. return false;
  10236. ComplexValue RHS;
  10237. if (E->getRHS()->getType()->isRealFloatingType()) {
  10238. RHSReal = true;
  10239. APFloat &Real = RHS.FloatReal;
  10240. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  10241. return false;
  10242. RHS.makeComplexFloat();
  10243. RHS.FloatImag = APFloat(Real.getSemantics());
  10244. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  10245. return false;
  10246. assert(!(LHSReal && RHSReal) &&
  10247. "Cannot have both operands of a complex operation be real.");
  10248. switch (E->getOpcode()) {
  10249. default: return Error(E);
  10250. case BO_Add:
  10251. if (Result.isComplexFloat()) {
  10252. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  10253. APFloat::rmNearestTiesToEven);
  10254. if (LHSReal)
  10255. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  10256. else if (!RHSReal)
  10257. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  10258. APFloat::rmNearestTiesToEven);
  10259. } else {
  10260. Result.getComplexIntReal() += RHS.getComplexIntReal();
  10261. Result.getComplexIntImag() += RHS.getComplexIntImag();
  10262. }
  10263. break;
  10264. case BO_Sub:
  10265. if (Result.isComplexFloat()) {
  10266. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  10267. APFloat::rmNearestTiesToEven);
  10268. if (LHSReal) {
  10269. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  10270. Result.getComplexFloatImag().changeSign();
  10271. } else if (!RHSReal) {
  10272. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  10273. APFloat::rmNearestTiesToEven);
  10274. }
  10275. } else {
  10276. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  10277. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  10278. }
  10279. break;
  10280. case BO_Mul:
  10281. if (Result.isComplexFloat()) {
  10282. // This is an implementation of complex multiplication according to the
  10283. // constraints laid out in C11 Annex G. The implementation uses the
  10284. // following naming scheme:
  10285. // (a + ib) * (c + id)
  10286. ComplexValue LHS = Result;
  10287. APFloat &A = LHS.getComplexFloatReal();
  10288. APFloat &B = LHS.getComplexFloatImag();
  10289. APFloat &C = RHS.getComplexFloatReal();
  10290. APFloat &D = RHS.getComplexFloatImag();
  10291. APFloat &ResR = Result.getComplexFloatReal();
  10292. APFloat &ResI = Result.getComplexFloatImag();
  10293. if (LHSReal) {
  10294. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  10295. ResR = A * C;
  10296. ResI = A * D;
  10297. } else if (RHSReal) {
  10298. ResR = C * A;
  10299. ResI = C * B;
  10300. } else {
  10301. // In the fully general case, we need to handle NaNs and infinities
  10302. // robustly.
  10303. APFloat AC = A * C;
  10304. APFloat BD = B * D;
  10305. APFloat AD = A * D;
  10306. APFloat BC = B * C;
  10307. ResR = AC - BD;
  10308. ResI = AD + BC;
  10309. if (ResR.isNaN() && ResI.isNaN()) {
  10310. bool Recalc = false;
  10311. if (A.isInfinity() || B.isInfinity()) {
  10312. A = APFloat::copySign(
  10313. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  10314. B = APFloat::copySign(
  10315. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  10316. if (C.isNaN())
  10317. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  10318. if (D.isNaN())
  10319. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  10320. Recalc = true;
  10321. }
  10322. if (C.isInfinity() || D.isInfinity()) {
  10323. C = APFloat::copySign(
  10324. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  10325. D = APFloat::copySign(
  10326. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  10327. if (A.isNaN())
  10328. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  10329. if (B.isNaN())
  10330. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  10331. Recalc = true;
  10332. }
  10333. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  10334. AD.isInfinity() || BC.isInfinity())) {
  10335. if (A.isNaN())
  10336. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  10337. if (B.isNaN())
  10338. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  10339. if (C.isNaN())
  10340. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  10341. if (D.isNaN())
  10342. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  10343. Recalc = true;
  10344. }
  10345. if (Recalc) {
  10346. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  10347. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  10348. }
  10349. }
  10350. }
  10351. } else {
  10352. ComplexValue LHS = Result;
  10353. Result.getComplexIntReal() =
  10354. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  10355. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  10356. Result.getComplexIntImag() =
  10357. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  10358. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  10359. }
  10360. break;
  10361. case BO_Div:
  10362. if (Result.isComplexFloat()) {
  10363. // This is an implementation of complex division according to the
  10364. // constraints laid out in C11 Annex G. The implementation uses the
  10365. // following naming scheme:
  10366. // (a + ib) / (c + id)
  10367. ComplexValue LHS = Result;
  10368. APFloat &A = LHS.getComplexFloatReal();
  10369. APFloat &B = LHS.getComplexFloatImag();
  10370. APFloat &C = RHS.getComplexFloatReal();
  10371. APFloat &D = RHS.getComplexFloatImag();
  10372. APFloat &ResR = Result.getComplexFloatReal();
  10373. APFloat &ResI = Result.getComplexFloatImag();
  10374. if (RHSReal) {
  10375. ResR = A / C;
  10376. ResI = B / C;
  10377. } else {
  10378. if (LHSReal) {
  10379. // No real optimizations we can do here, stub out with zero.
  10380. B = APFloat::getZero(A.getSemantics());
  10381. }
  10382. int DenomLogB = 0;
  10383. APFloat MaxCD = maxnum(abs(C), abs(D));
  10384. if (MaxCD.isFinite()) {
  10385. DenomLogB = ilogb(MaxCD);
  10386. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  10387. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  10388. }
  10389. APFloat Denom = C * C + D * D;
  10390. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  10391. APFloat::rmNearestTiesToEven);
  10392. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  10393. APFloat::rmNearestTiesToEven);
  10394. if (ResR.isNaN() && ResI.isNaN()) {
  10395. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  10396. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  10397. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  10398. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  10399. D.isFinite()) {
  10400. A = APFloat::copySign(
  10401. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  10402. B = APFloat::copySign(
  10403. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  10404. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  10405. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  10406. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  10407. C = APFloat::copySign(
  10408. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  10409. D = APFloat::copySign(
  10410. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  10411. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  10412. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  10413. }
  10414. }
  10415. }
  10416. } else {
  10417. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  10418. return Error(E, diag::note_expr_divide_by_zero);
  10419. ComplexValue LHS = Result;
  10420. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  10421. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  10422. Result.getComplexIntReal() =
  10423. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  10424. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  10425. Result.getComplexIntImag() =
  10426. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  10427. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  10428. }
  10429. break;
  10430. }
  10431. return true;
  10432. }
  10433. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10434. // Get the operand value into 'Result'.
  10435. if (!Visit(E->getSubExpr()))
  10436. return false;
  10437. switch (E->getOpcode()) {
  10438. default:
  10439. return Error(E);
  10440. case UO_Extension:
  10441. return true;
  10442. case UO_Plus:
  10443. // The result is always just the subexpr.
  10444. return true;
  10445. case UO_Minus:
  10446. if (Result.isComplexFloat()) {
  10447. Result.getComplexFloatReal().changeSign();
  10448. Result.getComplexFloatImag().changeSign();
  10449. }
  10450. else {
  10451. Result.getComplexIntReal() = -Result.getComplexIntReal();
  10452. Result.getComplexIntImag() = -Result.getComplexIntImag();
  10453. }
  10454. return true;
  10455. case UO_Not:
  10456. if (Result.isComplexFloat())
  10457. Result.getComplexFloatImag().changeSign();
  10458. else
  10459. Result.getComplexIntImag() = -Result.getComplexIntImag();
  10460. return true;
  10461. }
  10462. }
  10463. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  10464. if (E->getNumInits() == 2) {
  10465. if (E->getType()->isComplexType()) {
  10466. Result.makeComplexFloat();
  10467. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  10468. return false;
  10469. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  10470. return false;
  10471. } else {
  10472. Result.makeComplexInt();
  10473. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  10474. return false;
  10475. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  10476. return false;
  10477. }
  10478. return true;
  10479. }
  10480. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  10481. }
  10482. //===----------------------------------------------------------------------===//
  10483. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  10484. // implicit conversion.
  10485. //===----------------------------------------------------------------------===//
  10486. namespace {
  10487. class AtomicExprEvaluator :
  10488. public ExprEvaluatorBase<AtomicExprEvaluator> {
  10489. const LValue *This;
  10490. APValue &Result;
  10491. public:
  10492. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  10493. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  10494. bool Success(const APValue &V, const Expr *E) {
  10495. Result = V;
  10496. return true;
  10497. }
  10498. bool ZeroInitialization(const Expr *E) {
  10499. ImplicitValueInitExpr VIE(
  10500. E->getType()->castAs<AtomicType>()->getValueType());
  10501. // For atomic-qualified class (and array) types in C++, initialize the
  10502. // _Atomic-wrapped subobject directly, in-place.
  10503. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  10504. : Evaluate(Result, Info, &VIE);
  10505. }
  10506. bool VisitCastExpr(const CastExpr *E) {
  10507. switch (E->getCastKind()) {
  10508. default:
  10509. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10510. case CK_NonAtomicToAtomic:
  10511. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  10512. : Evaluate(Result, Info, E->getSubExpr());
  10513. }
  10514. }
  10515. };
  10516. } // end anonymous namespace
  10517. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  10518. EvalInfo &Info) {
  10519. assert(E->isRValue() && E->getType()->isAtomicType());
  10520. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  10521. }
  10522. //===----------------------------------------------------------------------===//
  10523. // Void expression evaluation, primarily for a cast to void on the LHS of a
  10524. // comma operator
  10525. //===----------------------------------------------------------------------===//
  10526. namespace {
  10527. class VoidExprEvaluator
  10528. : public ExprEvaluatorBase<VoidExprEvaluator> {
  10529. public:
  10530. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  10531. bool Success(const APValue &V, const Expr *e) { return true; }
  10532. bool ZeroInitialization(const Expr *E) { return true; }
  10533. bool VisitCastExpr(const CastExpr *E) {
  10534. switch (E->getCastKind()) {
  10535. default:
  10536. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10537. case CK_ToVoid:
  10538. VisitIgnoredValue(E->getSubExpr());
  10539. return true;
  10540. }
  10541. }
  10542. bool VisitCallExpr(const CallExpr *E) {
  10543. switch (E->getBuiltinCallee()) {
  10544. default:
  10545. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10546. case Builtin::BI__assume:
  10547. case Builtin::BI__builtin_assume:
  10548. // The argument is not evaluated!
  10549. return true;
  10550. }
  10551. }
  10552. };
  10553. } // end anonymous namespace
  10554. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  10555. assert(E->isRValue() && E->getType()->isVoidType());
  10556. return VoidExprEvaluator(Info).Visit(E);
  10557. }
  10558. //===----------------------------------------------------------------------===//
  10559. // Top level Expr::EvaluateAsRValue method.
  10560. //===----------------------------------------------------------------------===//
  10561. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  10562. // In C, function designators are not lvalues, but we evaluate them as if they
  10563. // are.
  10564. QualType T = E->getType();
  10565. if (E->isGLValue() || T->isFunctionType()) {
  10566. LValue LV;
  10567. if (!EvaluateLValue(E, LV, Info))
  10568. return false;
  10569. LV.moveInto(Result);
  10570. } else if (T->isVectorType()) {
  10571. if (!EvaluateVector(E, Result, Info))
  10572. return false;
  10573. } else if (T->isIntegralOrEnumerationType()) {
  10574. if (!IntExprEvaluator(Info, Result).Visit(E))
  10575. return false;
  10576. } else if (T->hasPointerRepresentation()) {
  10577. LValue LV;
  10578. if (!EvaluatePointer(E, LV, Info))
  10579. return false;
  10580. LV.moveInto(Result);
  10581. } else if (T->isRealFloatingType()) {
  10582. llvm::APFloat F(0.0);
  10583. if (!EvaluateFloat(E, F, Info))
  10584. return false;
  10585. Result = APValue(F);
  10586. } else if (T->isAnyComplexType()) {
  10587. ComplexValue C;
  10588. if (!EvaluateComplex(E, C, Info))
  10589. return false;
  10590. C.moveInto(Result);
  10591. } else if (T->isFixedPointType()) {
  10592. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  10593. } else if (T->isMemberPointerType()) {
  10594. MemberPtr P;
  10595. if (!EvaluateMemberPointer(E, P, Info))
  10596. return false;
  10597. P.moveInto(Result);
  10598. return true;
  10599. } else if (T->isArrayType()) {
  10600. LValue LV;
  10601. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10602. if (!EvaluateArray(E, LV, Value, Info))
  10603. return false;
  10604. Result = Value;
  10605. } else if (T->isRecordType()) {
  10606. LValue LV;
  10607. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10608. if (!EvaluateRecord(E, LV, Value, Info))
  10609. return false;
  10610. Result = Value;
  10611. } else if (T->isVoidType()) {
  10612. if (!Info.getLangOpts().CPlusPlus11)
  10613. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  10614. << E->getType();
  10615. if (!EvaluateVoid(E, Info))
  10616. return false;
  10617. } else if (T->isAtomicType()) {
  10618. QualType Unqual = T.getAtomicUnqualifiedType();
  10619. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  10620. LValue LV;
  10621. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10622. if (!EvaluateAtomic(E, &LV, Value, Info))
  10623. return false;
  10624. } else {
  10625. if (!EvaluateAtomic(E, nullptr, Result, Info))
  10626. return false;
  10627. }
  10628. } else if (Info.getLangOpts().CPlusPlus11) {
  10629. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  10630. return false;
  10631. } else {
  10632. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10633. return false;
  10634. }
  10635. return true;
  10636. }
  10637. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  10638. /// cases, the in-place evaluation is essential, since later initializers for
  10639. /// an object can indirectly refer to subobjects which were initialized earlier.
  10640. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  10641. const Expr *E, bool AllowNonLiteralTypes) {
  10642. assert(!E->isValueDependent());
  10643. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  10644. return false;
  10645. if (E->isRValue()) {
  10646. // Evaluate arrays and record types in-place, so that later initializers can
  10647. // refer to earlier-initialized members of the object.
  10648. QualType T = E->getType();
  10649. if (T->isArrayType())
  10650. return EvaluateArray(E, This, Result, Info);
  10651. else if (T->isRecordType())
  10652. return EvaluateRecord(E, This, Result, Info);
  10653. else if (T->isAtomicType()) {
  10654. QualType Unqual = T.getAtomicUnqualifiedType();
  10655. if (Unqual->isArrayType() || Unqual->isRecordType())
  10656. return EvaluateAtomic(E, &This, Result, Info);
  10657. }
  10658. }
  10659. // For any other type, in-place evaluation is unimportant.
  10660. return Evaluate(Result, Info, E);
  10661. }
  10662. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  10663. /// lvalue-to-rvalue cast if it is an lvalue.
  10664. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  10665. if (Info.EnableNewConstInterp) {
  10666. auto &InterpCtx = Info.Ctx.getInterpContext();
  10667. switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
  10668. case interp::InterpResult::Success:
  10669. return true;
  10670. case interp::InterpResult::Fail:
  10671. return false;
  10672. case interp::InterpResult::Bail:
  10673. break;
  10674. }
  10675. }
  10676. if (E->getType().isNull())
  10677. return false;
  10678. if (!CheckLiteralType(Info, E))
  10679. return false;
  10680. if (!::Evaluate(Result, Info, E))
  10681. return false;
  10682. if (E->isGLValue()) {
  10683. LValue LV;
  10684. LV.setFrom(Info.Ctx, Result);
  10685. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  10686. return false;
  10687. }
  10688. // Check this core constant expression is a constant expression.
  10689. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  10690. }
  10691. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  10692. const ASTContext &Ctx, bool &IsConst) {
  10693. // Fast-path evaluations of integer literals, since we sometimes see files
  10694. // containing vast quantities of these.
  10695. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  10696. Result.Val = APValue(APSInt(L->getValue(),
  10697. L->getType()->isUnsignedIntegerType()));
  10698. IsConst = true;
  10699. return true;
  10700. }
  10701. // This case should be rare, but we need to check it before we check on
  10702. // the type below.
  10703. if (Exp->getType().isNull()) {
  10704. IsConst = false;
  10705. return true;
  10706. }
  10707. // FIXME: Evaluating values of large array and record types can cause
  10708. // performance problems. Only do so in C++11 for now.
  10709. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  10710. Exp->getType()->isRecordType()) &&
  10711. !Ctx.getLangOpts().CPlusPlus11) {
  10712. IsConst = false;
  10713. return true;
  10714. }
  10715. return false;
  10716. }
  10717. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  10718. Expr::SideEffectsKind SEK) {
  10719. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  10720. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  10721. }
  10722. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  10723. const ASTContext &Ctx, EvalInfo &Info) {
  10724. bool IsConst;
  10725. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  10726. return IsConst;
  10727. return EvaluateAsRValue(Info, E, Result.Val);
  10728. }
  10729. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  10730. const ASTContext &Ctx,
  10731. Expr::SideEffectsKind AllowSideEffects,
  10732. EvalInfo &Info) {
  10733. if (!E->getType()->isIntegralOrEnumerationType())
  10734. return false;
  10735. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  10736. !ExprResult.Val.isInt() ||
  10737. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10738. return false;
  10739. return true;
  10740. }
  10741. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  10742. const ASTContext &Ctx,
  10743. Expr::SideEffectsKind AllowSideEffects,
  10744. EvalInfo &Info) {
  10745. if (!E->getType()->isFixedPointType())
  10746. return false;
  10747. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  10748. return false;
  10749. if (!ExprResult.Val.isFixedPoint() ||
  10750. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10751. return false;
  10752. return true;
  10753. }
  10754. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  10755. /// any crazy technique (that has nothing to do with language standards) that
  10756. /// we want to. If this function returns true, it returns the folded constant
  10757. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  10758. /// will be applied to the result.
  10759. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  10760. bool InConstantContext) const {
  10761. assert(!isValueDependent() &&
  10762. "Expression evaluator can't be called on a dependent expression.");
  10763. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10764. Info.InConstantContext = InConstantContext;
  10765. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  10766. }
  10767. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  10768. bool InConstantContext) const {
  10769. assert(!isValueDependent() &&
  10770. "Expression evaluator can't be called on a dependent expression.");
  10771. EvalResult Scratch;
  10772. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  10773. HandleConversionToBool(Scratch.Val, Result);
  10774. }
  10775. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  10776. SideEffectsKind AllowSideEffects,
  10777. bool InConstantContext) const {
  10778. assert(!isValueDependent() &&
  10779. "Expression evaluator can't be called on a dependent expression.");
  10780. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10781. Info.InConstantContext = InConstantContext;
  10782. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  10783. }
  10784. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  10785. SideEffectsKind AllowSideEffects,
  10786. bool InConstantContext) const {
  10787. assert(!isValueDependent() &&
  10788. "Expression evaluator can't be called on a dependent expression.");
  10789. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10790. Info.InConstantContext = InConstantContext;
  10791. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  10792. }
  10793. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  10794. SideEffectsKind AllowSideEffects,
  10795. bool InConstantContext) const {
  10796. assert(!isValueDependent() &&
  10797. "Expression evaluator can't be called on a dependent expression.");
  10798. if (!getType()->isRealFloatingType())
  10799. return false;
  10800. EvalResult ExprResult;
  10801. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  10802. !ExprResult.Val.isFloat() ||
  10803. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10804. return false;
  10805. Result = ExprResult.Val.getFloat();
  10806. return true;
  10807. }
  10808. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  10809. bool InConstantContext) const {
  10810. assert(!isValueDependent() &&
  10811. "Expression evaluator can't be called on a dependent expression.");
  10812. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  10813. Info.InConstantContext = InConstantContext;
  10814. LValue LV;
  10815. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  10816. !CheckLValueConstantExpression(Info, getExprLoc(),
  10817. Ctx.getLValueReferenceType(getType()), LV,
  10818. Expr::EvaluateForCodeGen))
  10819. return false;
  10820. LV.moveInto(Result.Val);
  10821. return true;
  10822. }
  10823. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  10824. const ASTContext &Ctx) const {
  10825. assert(!isValueDependent() &&
  10826. "Expression evaluator can't be called on a dependent expression.");
  10827. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  10828. EvalInfo Info(Ctx, Result, EM);
  10829. Info.InConstantContext = true;
  10830. if (!::Evaluate(Result.Val, Info, this))
  10831. return false;
  10832. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  10833. Usage);
  10834. }
  10835. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  10836. const VarDecl *VD,
  10837. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  10838. assert(!isValueDependent() &&
  10839. "Expression evaluator can't be called on a dependent expression.");
  10840. // FIXME: Evaluating initializers for large array and record types can cause
  10841. // performance problems. Only do so in C++11 for now.
  10842. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  10843. !Ctx.getLangOpts().CPlusPlus11)
  10844. return false;
  10845. Expr::EvalStatus EStatus;
  10846. EStatus.Diag = &Notes;
  10847. EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
  10848. ? EvalInfo::EM_ConstantExpression
  10849. : EvalInfo::EM_ConstantFold);
  10850. Info.setEvaluatingDecl(VD, Value);
  10851. Info.InConstantContext = true;
  10852. SourceLocation DeclLoc = VD->getLocation();
  10853. QualType DeclTy = VD->getType();
  10854. if (Info.EnableNewConstInterp) {
  10855. auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
  10856. switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
  10857. case interp::InterpResult::Fail:
  10858. // Bail out if an error was encountered.
  10859. return false;
  10860. case interp::InterpResult::Success:
  10861. // Evaluation succeeded and value was set.
  10862. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
  10863. case interp::InterpResult::Bail:
  10864. // Evaluate the value again for the tree evaluator to use.
  10865. break;
  10866. }
  10867. }
  10868. LValue LVal;
  10869. LVal.set(VD);
  10870. // C++11 [basic.start.init]p2:
  10871. // Variables with static storage duration or thread storage duration shall be
  10872. // zero-initialized before any other initialization takes place.
  10873. // This behavior is not present in C.
  10874. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  10875. !DeclTy->isReferenceType()) {
  10876. ImplicitValueInitExpr VIE(DeclTy);
  10877. if (!EvaluateInPlace(Value, Info, LVal, &VIE,
  10878. /*AllowNonLiteralTypes=*/true))
  10879. return false;
  10880. }
  10881. if (!EvaluateInPlace(Value, Info, LVal, this,
  10882. /*AllowNonLiteralTypes=*/true) ||
  10883. EStatus.HasSideEffects)
  10884. return false;
  10885. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
  10886. }
  10887. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  10888. /// constant folded, but discard the result.
  10889. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  10890. assert(!isValueDependent() &&
  10891. "Expression evaluator can't be called on a dependent expression.");
  10892. EvalResult Result;
  10893. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  10894. !hasUnacceptableSideEffect(Result, SEK);
  10895. }
  10896. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  10897. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  10898. assert(!isValueDependent() &&
  10899. "Expression evaluator can't be called on a dependent expression.");
  10900. EvalResult EVResult;
  10901. EVResult.Diag = Diag;
  10902. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  10903. Info.InConstantContext = true;
  10904. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  10905. (void)Result;
  10906. assert(Result && "Could not evaluate expression");
  10907. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  10908. return EVResult.Val.getInt();
  10909. }
  10910. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  10911. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  10912. assert(!isValueDependent() &&
  10913. "Expression evaluator can't be called on a dependent expression.");
  10914. EvalResult EVResult;
  10915. EVResult.Diag = Diag;
  10916. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
  10917. Info.InConstantContext = true;
  10918. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  10919. (void)Result;
  10920. assert(Result && "Could not evaluate expression");
  10921. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  10922. return EVResult.Val.getInt();
  10923. }
  10924. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  10925. assert(!isValueDependent() &&
  10926. "Expression evaluator can't be called on a dependent expression.");
  10927. bool IsConst;
  10928. EvalResult EVResult;
  10929. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  10930. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
  10931. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  10932. }
  10933. }
  10934. bool Expr::EvalResult::isGlobalLValue() const {
  10935. assert(Val.isLValue());
  10936. return IsGlobalLValue(Val.getLValueBase());
  10937. }
  10938. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  10939. /// an integer constant expression.
  10940. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  10941. /// comma, etc
  10942. // CheckICE - This function does the fundamental ICE checking: the returned
  10943. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  10944. // and a (possibly null) SourceLocation indicating the location of the problem.
  10945. //
  10946. // Note that to reduce code duplication, this helper does no evaluation
  10947. // itself; the caller checks whether the expression is evaluatable, and
  10948. // in the rare cases where CheckICE actually cares about the evaluated
  10949. // value, it calls into Evaluate.
  10950. namespace {
  10951. enum ICEKind {
  10952. /// This expression is an ICE.
  10953. IK_ICE,
  10954. /// This expression is not an ICE, but if it isn't evaluated, it's
  10955. /// a legal subexpression for an ICE. This return value is used to handle
  10956. /// the comma operator in C99 mode, and non-constant subexpressions.
  10957. IK_ICEIfUnevaluated,
  10958. /// This expression is not an ICE, and is not a legal subexpression for one.
  10959. IK_NotICE
  10960. };
  10961. struct ICEDiag {
  10962. ICEKind Kind;
  10963. SourceLocation Loc;
  10964. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  10965. };
  10966. }
  10967. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  10968. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  10969. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  10970. Expr::EvalResult EVResult;
  10971. Expr::EvalStatus Status;
  10972. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  10973. Info.InConstantContext = true;
  10974. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  10975. !EVResult.Val.isInt())
  10976. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10977. return NoDiag();
  10978. }
  10979. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  10980. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  10981. if (!E->getType()->isIntegralOrEnumerationType())
  10982. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10983. switch (E->getStmtClass()) {
  10984. #define ABSTRACT_STMT(Node)
  10985. #define STMT(Node, Base) case Expr::Node##Class:
  10986. #define EXPR(Node, Base)
  10987. #include "clang/AST/StmtNodes.inc"
  10988. case Expr::PredefinedExprClass:
  10989. case Expr::FloatingLiteralClass:
  10990. case Expr::ImaginaryLiteralClass:
  10991. case Expr::StringLiteralClass:
  10992. case Expr::ArraySubscriptExprClass:
  10993. case Expr::OMPArraySectionExprClass:
  10994. case Expr::MemberExprClass:
  10995. case Expr::CompoundAssignOperatorClass:
  10996. case Expr::CompoundLiteralExprClass:
  10997. case Expr::ExtVectorElementExprClass:
  10998. case Expr::DesignatedInitExprClass:
  10999. case Expr::ArrayInitLoopExprClass:
  11000. case Expr::ArrayInitIndexExprClass:
  11001. case Expr::NoInitExprClass:
  11002. case Expr::DesignatedInitUpdateExprClass:
  11003. case Expr::ImplicitValueInitExprClass:
  11004. case Expr::ParenListExprClass:
  11005. case Expr::VAArgExprClass:
  11006. case Expr::AddrLabelExprClass:
  11007. case Expr::StmtExprClass:
  11008. case Expr::CXXMemberCallExprClass:
  11009. case Expr::CUDAKernelCallExprClass:
  11010. case Expr::CXXDynamicCastExprClass:
  11011. case Expr::CXXTypeidExprClass:
  11012. case Expr::CXXUuidofExprClass:
  11013. case Expr::MSPropertyRefExprClass:
  11014. case Expr::MSPropertySubscriptExprClass:
  11015. case Expr::CXXNullPtrLiteralExprClass:
  11016. case Expr::UserDefinedLiteralClass:
  11017. case Expr::CXXThisExprClass:
  11018. case Expr::CXXThrowExprClass:
  11019. case Expr::CXXNewExprClass:
  11020. case Expr::CXXDeleteExprClass:
  11021. case Expr::CXXPseudoDestructorExprClass:
  11022. case Expr::UnresolvedLookupExprClass:
  11023. case Expr::TypoExprClass:
  11024. case Expr::DependentScopeDeclRefExprClass:
  11025. case Expr::CXXConstructExprClass:
  11026. case Expr::CXXInheritedCtorInitExprClass:
  11027. case Expr::CXXStdInitializerListExprClass:
  11028. case Expr::CXXBindTemporaryExprClass:
  11029. case Expr::ExprWithCleanupsClass:
  11030. case Expr::CXXTemporaryObjectExprClass:
  11031. case Expr::CXXUnresolvedConstructExprClass:
  11032. case Expr::CXXDependentScopeMemberExprClass:
  11033. case Expr::UnresolvedMemberExprClass:
  11034. case Expr::ObjCStringLiteralClass:
  11035. case Expr::ObjCBoxedExprClass:
  11036. case Expr::ObjCArrayLiteralClass:
  11037. case Expr::ObjCDictionaryLiteralClass:
  11038. case Expr::ObjCEncodeExprClass:
  11039. case Expr::ObjCMessageExprClass:
  11040. case Expr::ObjCSelectorExprClass:
  11041. case Expr::ObjCProtocolExprClass:
  11042. case Expr::ObjCIvarRefExprClass:
  11043. case Expr::ObjCPropertyRefExprClass:
  11044. case Expr::ObjCSubscriptRefExprClass:
  11045. case Expr::ObjCIsaExprClass:
  11046. case Expr::ObjCAvailabilityCheckExprClass:
  11047. case Expr::ShuffleVectorExprClass:
  11048. case Expr::ConvertVectorExprClass:
  11049. case Expr::BlockExprClass:
  11050. case Expr::NoStmtClass:
  11051. case Expr::OpaqueValueExprClass:
  11052. case Expr::PackExpansionExprClass:
  11053. case Expr::SubstNonTypeTemplateParmPackExprClass:
  11054. case Expr::FunctionParmPackExprClass:
  11055. case Expr::AsTypeExprClass:
  11056. case Expr::ObjCIndirectCopyRestoreExprClass:
  11057. case Expr::MaterializeTemporaryExprClass:
  11058. case Expr::PseudoObjectExprClass:
  11059. case Expr::AtomicExprClass:
  11060. case Expr::LambdaExprClass:
  11061. case Expr::CXXFoldExprClass:
  11062. case Expr::CoawaitExprClass:
  11063. case Expr::DependentCoawaitExprClass:
  11064. case Expr::CoyieldExprClass:
  11065. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11066. case Expr::InitListExprClass: {
  11067. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  11068. // form "T x = { a };" is equivalent to "T x = a;".
  11069. // Unless we're initializing a reference, T is a scalar as it is known to be
  11070. // of integral or enumeration type.
  11071. if (E->isRValue())
  11072. if (cast<InitListExpr>(E)->getNumInits() == 1)
  11073. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  11074. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11075. }
  11076. case Expr::SizeOfPackExprClass:
  11077. case Expr::GNUNullExprClass:
  11078. case Expr::SourceLocExprClass:
  11079. return NoDiag();
  11080. case Expr::SubstNonTypeTemplateParmExprClass:
  11081. return
  11082. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  11083. case Expr::ConstantExprClass:
  11084. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  11085. case Expr::ParenExprClass:
  11086. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  11087. case Expr::GenericSelectionExprClass:
  11088. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  11089. case Expr::IntegerLiteralClass:
  11090. case Expr::FixedPointLiteralClass:
  11091. case Expr::CharacterLiteralClass:
  11092. case Expr::ObjCBoolLiteralExprClass:
  11093. case Expr::CXXBoolLiteralExprClass:
  11094. case Expr::CXXScalarValueInitExprClass:
  11095. case Expr::TypeTraitExprClass:
  11096. case Expr::ArrayTypeTraitExprClass:
  11097. case Expr::ExpressionTraitExprClass:
  11098. case Expr::CXXNoexceptExprClass:
  11099. return NoDiag();
  11100. case Expr::CallExprClass:
  11101. case Expr::CXXOperatorCallExprClass: {
  11102. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  11103. // constant expressions, but they can never be ICEs because an ICE cannot
  11104. // contain an operand of (pointer to) function type.
  11105. const CallExpr *CE = cast<CallExpr>(E);
  11106. if (CE->getBuiltinCallee())
  11107. return CheckEvalInICE(E, Ctx);
  11108. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11109. }
  11110. case Expr::DeclRefExprClass: {
  11111. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  11112. return NoDiag();
  11113. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  11114. if (Ctx.getLangOpts().CPlusPlus &&
  11115. D && IsConstNonVolatile(D->getType())) {
  11116. // Parameter variables are never constants. Without this check,
  11117. // getAnyInitializer() can find a default argument, which leads
  11118. // to chaos.
  11119. if (isa<ParmVarDecl>(D))
  11120. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11121. // C++ 7.1.5.1p2
  11122. // A variable of non-volatile const-qualified integral or enumeration
  11123. // type initialized by an ICE can be used in ICEs.
  11124. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  11125. if (!Dcl->getType()->isIntegralOrEnumerationType())
  11126. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11127. const VarDecl *VD;
  11128. // Look for a declaration of this variable that has an initializer, and
  11129. // check whether it is an ICE.
  11130. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  11131. return NoDiag();
  11132. else
  11133. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11134. }
  11135. }
  11136. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11137. }
  11138. case Expr::UnaryOperatorClass: {
  11139. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  11140. switch (Exp->getOpcode()) {
  11141. case UO_PostInc:
  11142. case UO_PostDec:
  11143. case UO_PreInc:
  11144. case UO_PreDec:
  11145. case UO_AddrOf:
  11146. case UO_Deref:
  11147. case UO_Coawait:
  11148. // C99 6.6/3 allows increment and decrement within unevaluated
  11149. // subexpressions of constant expressions, but they can never be ICEs
  11150. // because an ICE cannot contain an lvalue operand.
  11151. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11152. case UO_Extension:
  11153. case UO_LNot:
  11154. case UO_Plus:
  11155. case UO_Minus:
  11156. case UO_Not:
  11157. case UO_Real:
  11158. case UO_Imag:
  11159. return CheckICE(Exp->getSubExpr(), Ctx);
  11160. }
  11161. llvm_unreachable("invalid unary operator class");
  11162. }
  11163. case Expr::OffsetOfExprClass: {
  11164. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  11165. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  11166. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  11167. // compliance: we should warn earlier for offsetof expressions with
  11168. // array subscripts that aren't ICEs, and if the array subscripts
  11169. // are ICEs, the value of the offsetof must be an integer constant.
  11170. return CheckEvalInICE(E, Ctx);
  11171. }
  11172. case Expr::UnaryExprOrTypeTraitExprClass: {
  11173. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  11174. if ((Exp->getKind() == UETT_SizeOf) &&
  11175. Exp->getTypeOfArgument()->isVariableArrayType())
  11176. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11177. return NoDiag();
  11178. }
  11179. case Expr::BinaryOperatorClass: {
  11180. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  11181. switch (Exp->getOpcode()) {
  11182. case BO_PtrMemD:
  11183. case BO_PtrMemI:
  11184. case BO_Assign:
  11185. case BO_MulAssign:
  11186. case BO_DivAssign:
  11187. case BO_RemAssign:
  11188. case BO_AddAssign:
  11189. case BO_SubAssign:
  11190. case BO_ShlAssign:
  11191. case BO_ShrAssign:
  11192. case BO_AndAssign:
  11193. case BO_XorAssign:
  11194. case BO_OrAssign:
  11195. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  11196. // constant expressions, but they can never be ICEs because an ICE cannot
  11197. // contain an lvalue operand.
  11198. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11199. case BO_Mul:
  11200. case BO_Div:
  11201. case BO_Rem:
  11202. case BO_Add:
  11203. case BO_Sub:
  11204. case BO_Shl:
  11205. case BO_Shr:
  11206. case BO_LT:
  11207. case BO_GT:
  11208. case BO_LE:
  11209. case BO_GE:
  11210. case BO_EQ:
  11211. case BO_NE:
  11212. case BO_And:
  11213. case BO_Xor:
  11214. case BO_Or:
  11215. case BO_Comma:
  11216. case BO_Cmp: {
  11217. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  11218. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  11219. if (Exp->getOpcode() == BO_Div ||
  11220. Exp->getOpcode() == BO_Rem) {
  11221. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  11222. // we don't evaluate one.
  11223. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  11224. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  11225. if (REval == 0)
  11226. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11227. if (REval.isSigned() && REval.isAllOnesValue()) {
  11228. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  11229. if (LEval.isMinSignedValue())
  11230. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11231. }
  11232. }
  11233. }
  11234. if (Exp->getOpcode() == BO_Comma) {
  11235. if (Ctx.getLangOpts().C99) {
  11236. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  11237. // if it isn't evaluated.
  11238. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  11239. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  11240. } else {
  11241. // In both C89 and C++, commas in ICEs are illegal.
  11242. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11243. }
  11244. }
  11245. return Worst(LHSResult, RHSResult);
  11246. }
  11247. case BO_LAnd:
  11248. case BO_LOr: {
  11249. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  11250. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  11251. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  11252. // Rare case where the RHS has a comma "side-effect"; we need
  11253. // to actually check the condition to see whether the side
  11254. // with the comma is evaluated.
  11255. if ((Exp->getOpcode() == BO_LAnd) !=
  11256. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  11257. return RHSResult;
  11258. return NoDiag();
  11259. }
  11260. return Worst(LHSResult, RHSResult);
  11261. }
  11262. }
  11263. llvm_unreachable("invalid binary operator kind");
  11264. }
  11265. case Expr::ImplicitCastExprClass:
  11266. case Expr::CStyleCastExprClass:
  11267. case Expr::CXXFunctionalCastExprClass:
  11268. case Expr::CXXStaticCastExprClass:
  11269. case Expr::CXXReinterpretCastExprClass:
  11270. case Expr::CXXConstCastExprClass:
  11271. case Expr::ObjCBridgedCastExprClass: {
  11272. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  11273. if (isa<ExplicitCastExpr>(E)) {
  11274. if (const FloatingLiteral *FL
  11275. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  11276. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  11277. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  11278. APSInt IgnoredVal(DestWidth, !DestSigned);
  11279. bool Ignored;
  11280. // If the value does not fit in the destination type, the behavior is
  11281. // undefined, so we are not required to treat it as a constant
  11282. // expression.
  11283. if (FL->getValue().convertToInteger(IgnoredVal,
  11284. llvm::APFloat::rmTowardZero,
  11285. &Ignored) & APFloat::opInvalidOp)
  11286. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11287. return NoDiag();
  11288. }
  11289. }
  11290. switch (cast<CastExpr>(E)->getCastKind()) {
  11291. case CK_LValueToRValue:
  11292. case CK_AtomicToNonAtomic:
  11293. case CK_NonAtomicToAtomic:
  11294. case CK_NoOp:
  11295. case CK_IntegralToBoolean:
  11296. case CK_IntegralCast:
  11297. return CheckICE(SubExpr, Ctx);
  11298. default:
  11299. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11300. }
  11301. }
  11302. case Expr::BinaryConditionalOperatorClass: {
  11303. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  11304. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  11305. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  11306. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  11307. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  11308. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  11309. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  11310. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  11311. return FalseResult;
  11312. }
  11313. case Expr::ConditionalOperatorClass: {
  11314. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  11315. // If the condition (ignoring parens) is a __builtin_constant_p call,
  11316. // then only the true side is actually considered in an integer constant
  11317. // expression, and it is fully evaluated. This is an important GNU
  11318. // extension. See GCC PR38377 for discussion.
  11319. if (const CallExpr *CallCE
  11320. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  11321. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  11322. return CheckEvalInICE(E, Ctx);
  11323. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  11324. if (CondResult.Kind == IK_NotICE)
  11325. return CondResult;
  11326. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  11327. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  11328. if (TrueResult.Kind == IK_NotICE)
  11329. return TrueResult;
  11330. if (FalseResult.Kind == IK_NotICE)
  11331. return FalseResult;
  11332. if (CondResult.Kind == IK_ICEIfUnevaluated)
  11333. return CondResult;
  11334. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  11335. return NoDiag();
  11336. // Rare case where the diagnostics depend on which side is evaluated
  11337. // Note that if we get here, CondResult is 0, and at least one of
  11338. // TrueResult and FalseResult is non-zero.
  11339. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  11340. return FalseResult;
  11341. return TrueResult;
  11342. }
  11343. case Expr::CXXDefaultArgExprClass:
  11344. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  11345. case Expr::CXXDefaultInitExprClass:
  11346. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  11347. case Expr::ChooseExprClass: {
  11348. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  11349. }
  11350. case Expr::BuiltinBitCastExprClass: {
  11351. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  11352. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11353. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  11354. }
  11355. }
  11356. llvm_unreachable("Invalid StmtClass!");
  11357. }
  11358. /// Evaluate an expression as a C++11 integral constant expression.
  11359. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  11360. const Expr *E,
  11361. llvm::APSInt *Value,
  11362. SourceLocation *Loc) {
  11363. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  11364. if (Loc) *Loc = E->getExprLoc();
  11365. return false;
  11366. }
  11367. APValue Result;
  11368. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  11369. return false;
  11370. if (!Result.isInt()) {
  11371. if (Loc) *Loc = E->getExprLoc();
  11372. return false;
  11373. }
  11374. if (Value) *Value = Result.getInt();
  11375. return true;
  11376. }
  11377. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  11378. SourceLocation *Loc) const {
  11379. assert(!isValueDependent() &&
  11380. "Expression evaluator can't be called on a dependent expression.");
  11381. if (Ctx.getLangOpts().CPlusPlus11)
  11382. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  11383. ICEDiag D = CheckICE(this, Ctx);
  11384. if (D.Kind != IK_ICE) {
  11385. if (Loc) *Loc = D.Loc;
  11386. return false;
  11387. }
  11388. return true;
  11389. }
  11390. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  11391. SourceLocation *Loc, bool isEvaluated) const {
  11392. assert(!isValueDependent() &&
  11393. "Expression evaluator can't be called on a dependent expression.");
  11394. if (Ctx.getLangOpts().CPlusPlus11)
  11395. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  11396. if (!isIntegerConstantExpr(Ctx, Loc))
  11397. return false;
  11398. // The only possible side-effects here are due to UB discovered in the
  11399. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  11400. // required to treat the expression as an ICE, so we produce the folded
  11401. // value.
  11402. EvalResult ExprResult;
  11403. Expr::EvalStatus Status;
  11404. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  11405. Info.InConstantContext = true;
  11406. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  11407. llvm_unreachable("ICE cannot be evaluated!");
  11408. Value = ExprResult.Val.getInt();
  11409. return true;
  11410. }
  11411. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  11412. assert(!isValueDependent() &&
  11413. "Expression evaluator can't be called on a dependent expression.");
  11414. return CheckICE(this, Ctx).Kind == IK_ICE;
  11415. }
  11416. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  11417. SourceLocation *Loc) const {
  11418. assert(!isValueDependent() &&
  11419. "Expression evaluator can't be called on a dependent expression.");
  11420. // We support this checking in C++98 mode in order to diagnose compatibility
  11421. // issues.
  11422. assert(Ctx.getLangOpts().CPlusPlus);
  11423. // Build evaluation settings.
  11424. Expr::EvalStatus Status;
  11425. SmallVector<PartialDiagnosticAt, 8> Diags;
  11426. Status.Diag = &Diags;
  11427. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  11428. APValue Scratch;
  11429. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  11430. if (!Diags.empty()) {
  11431. IsConstExpr = false;
  11432. if (Loc) *Loc = Diags[0].first;
  11433. } else if (!IsConstExpr) {
  11434. // FIXME: This shouldn't happen.
  11435. if (Loc) *Loc = getExprLoc();
  11436. }
  11437. return IsConstExpr;
  11438. }
  11439. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  11440. const FunctionDecl *Callee,
  11441. ArrayRef<const Expr*> Args,
  11442. const Expr *This) const {
  11443. assert(!isValueDependent() &&
  11444. "Expression evaluator can't be called on a dependent expression.");
  11445. Expr::EvalStatus Status;
  11446. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  11447. Info.InConstantContext = true;
  11448. LValue ThisVal;
  11449. const LValue *ThisPtr = nullptr;
  11450. if (This) {
  11451. #ifndef NDEBUG
  11452. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  11453. assert(MD && "Don't provide `this` for non-methods.");
  11454. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  11455. #endif
  11456. if (EvaluateObjectArgument(Info, This, ThisVal))
  11457. ThisPtr = &ThisVal;
  11458. if (Info.EvalStatus.HasSideEffects)
  11459. return false;
  11460. }
  11461. ArgVector ArgValues(Args.size());
  11462. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  11463. I != E; ++I) {
  11464. if ((*I)->isValueDependent() ||
  11465. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  11466. // If evaluation fails, throw away the argument entirely.
  11467. ArgValues[I - Args.begin()] = APValue();
  11468. if (Info.EvalStatus.HasSideEffects)
  11469. return false;
  11470. }
  11471. // Build fake call to Callee.
  11472. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  11473. ArgValues.data());
  11474. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  11475. }
  11476. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  11477. SmallVectorImpl<
  11478. PartialDiagnosticAt> &Diags) {
  11479. // FIXME: It would be useful to check constexpr function templates, but at the
  11480. // moment the constant expression evaluator cannot cope with the non-rigorous
  11481. // ASTs which we build for dependent expressions.
  11482. if (FD->isDependentContext())
  11483. return true;
  11484. Expr::EvalStatus Status;
  11485. Status.Diag = &Diags;
  11486. EvalInfo Info(FD->getASTContext(), Status,
  11487. EvalInfo::EM_PotentialConstantExpression);
  11488. Info.InConstantContext = true;
  11489. // The constexpr VM attempts to compile all methods to bytecode here.
  11490. if (Info.EnableNewConstInterp) {
  11491. auto &InterpCtx = Info.Ctx.getInterpContext();
  11492. switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
  11493. case interp::InterpResult::Success:
  11494. case interp::InterpResult::Fail:
  11495. return Diags.empty();
  11496. case interp::InterpResult::Bail:
  11497. break;
  11498. }
  11499. }
  11500. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  11501. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  11502. // Fabricate an arbitrary expression on the stack and pretend that it
  11503. // is a temporary being used as the 'this' pointer.
  11504. LValue This;
  11505. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  11506. This.set({&VIE, Info.CurrentCall->Index});
  11507. ArrayRef<const Expr*> Args;
  11508. APValue Scratch;
  11509. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  11510. // Evaluate the call as a constant initializer, to allow the construction
  11511. // of objects of non-literal types.
  11512. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  11513. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  11514. } else {
  11515. SourceLocation Loc = FD->getLocation();
  11516. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  11517. Args, FD->getBody(), Info, Scratch, nullptr);
  11518. }
  11519. return Diags.empty();
  11520. }
  11521. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  11522. const FunctionDecl *FD,
  11523. SmallVectorImpl<
  11524. PartialDiagnosticAt> &Diags) {
  11525. assert(!E->isValueDependent() &&
  11526. "Expression evaluator can't be called on a dependent expression.");
  11527. Expr::EvalStatus Status;
  11528. Status.Diag = &Diags;
  11529. EvalInfo Info(FD->getASTContext(), Status,
  11530. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  11531. Info.InConstantContext = true;
  11532. // Fabricate a call stack frame to give the arguments a plausible cover story.
  11533. ArrayRef<const Expr*> Args;
  11534. ArgVector ArgValues(0);
  11535. bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
  11536. (void)Success;
  11537. assert(Success &&
  11538. "Failed to set up arguments for potential constant evaluation");
  11539. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  11540. APValue ResultScratch;
  11541. Evaluate(ResultScratch, Info, E);
  11542. return Diags.empty();
  11543. }
  11544. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  11545. unsigned Type) const {
  11546. if (!getType()->isPointerType())
  11547. return false;
  11548. Expr::EvalStatus Status;
  11549. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  11550. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  11551. }