ExprConstant.cpp 408 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Expr constant evaluator.
  11. //
  12. // Constant expression evaluation produces four main results:
  13. //
  14. // * A success/failure flag indicating whether constant folding was successful.
  15. // This is the 'bool' return value used by most of the code in this file. A
  16. // 'false' return value indicates that constant folding has failed, and any
  17. // appropriate diagnostic has already been produced.
  18. //
  19. // * An evaluated result, valid only if constant folding has not failed.
  20. //
  21. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  22. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  23. // where it is possible to determine the evaluated result regardless.
  24. //
  25. // * A set of notes indicating why the evaluation was not a constant expression
  26. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  27. // too, why the expression could not be folded.
  28. //
  29. // If we are checking for a potential constant expression, failure to constant
  30. // fold a potential constant sub-expression will be indicated by a 'false'
  31. // return value (the expression could not be folded) and no diagnostic (the
  32. // expression is not necessarily non-constant).
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #include "clang/AST/APValue.h"
  36. #include "clang/AST/ASTContext.h"
  37. #include "clang/AST/ASTDiagnostic.h"
  38. #include "clang/AST/ASTLambda.h"
  39. #include "clang/AST/CharUnits.h"
  40. #include "clang/AST/Expr.h"
  41. #include "clang/AST/RecordLayout.h"
  42. #include "clang/AST/StmtVisitor.h"
  43. #include "clang/AST/TypeLoc.h"
  44. #include "clang/Basic/Builtins.h"
  45. #include "clang/Basic/TargetInfo.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <cstring>
  48. #include <functional>
  49. #define DEBUG_TYPE "exprconstant"
  50. using namespace clang;
  51. using llvm::APSInt;
  52. using llvm::APFloat;
  53. static bool IsGlobalLValue(APValue::LValueBase B);
  54. namespace {
  55. struct LValue;
  56. struct CallStackFrame;
  57. struct EvalInfo;
  58. static QualType getType(APValue::LValueBase B) {
  59. if (!B) return QualType();
  60. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  61. // FIXME: It's unclear where we're supposed to take the type from, and
  62. // this actually matters for arrays of unknown bound. Eg:
  63. //
  64. // extern int arr[]; void f() { extern int arr[3]; };
  65. // constexpr int *p = &arr[1]; // valid?
  66. //
  67. // For now, we take the array bound from the most recent declaration.
  68. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  69. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  70. QualType T = Redecl->getType();
  71. if (!T->isIncompleteArrayType())
  72. return T;
  73. }
  74. return D->getType();
  75. }
  76. const Expr *Base = B.get<const Expr*>();
  77. // For a materialized temporary, the type of the temporary we materialized
  78. // may not be the type of the expression.
  79. if (const MaterializeTemporaryExpr *MTE =
  80. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  81. SmallVector<const Expr *, 2> CommaLHSs;
  82. SmallVector<SubobjectAdjustment, 2> Adjustments;
  83. const Expr *Temp = MTE->GetTemporaryExpr();
  84. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  85. Adjustments);
  86. // Keep any cv-qualifiers from the reference if we generated a temporary
  87. // for it directly. Otherwise use the type after adjustment.
  88. if (!Adjustments.empty())
  89. return Inner->getType();
  90. }
  91. return Base->getType();
  92. }
  93. /// Get an LValue path entry, which is known to not be an array index, as a
  94. /// field or base class.
  95. static
  96. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  97. APValue::BaseOrMemberType Value;
  98. Value.setFromOpaqueValue(E.BaseOrMember);
  99. return Value;
  100. }
  101. /// Get an LValue path entry, which is known to not be an array index, as a
  102. /// field declaration.
  103. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  104. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  105. }
  106. /// Get an LValue path entry, which is known to not be an array index, as a
  107. /// base class declaration.
  108. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  109. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  110. }
  111. /// Determine whether this LValue path entry for a base class names a virtual
  112. /// base class.
  113. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  114. return getAsBaseOrMember(E).getInt();
  115. }
  116. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  117. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  118. const FunctionDecl *Callee = CE->getDirectCallee();
  119. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  120. }
  121. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  122. /// This will look through a single cast.
  123. ///
  124. /// Returns null if we couldn't unwrap a function with alloc_size.
  125. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  126. if (!E->getType()->isPointerType())
  127. return nullptr;
  128. E = E->IgnoreParens();
  129. // If we're doing a variable assignment from e.g. malloc(N), there will
  130. // probably be a cast of some kind. In exotic cases, we might also see a
  131. // top-level ExprWithCleanups. Ignore them either way.
  132. if (const auto *FE = dyn_cast<FullExpr>(E))
  133. E = FE->getSubExpr()->IgnoreParens();
  134. if (const auto *Cast = dyn_cast<CastExpr>(E))
  135. E = Cast->getSubExpr()->IgnoreParens();
  136. if (const auto *CE = dyn_cast<CallExpr>(E))
  137. return getAllocSizeAttr(CE) ? CE : nullptr;
  138. return nullptr;
  139. }
  140. /// Determines whether or not the given Base contains a call to a function
  141. /// with the alloc_size attribute.
  142. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  143. const auto *E = Base.dyn_cast<const Expr *>();
  144. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  145. }
  146. /// The bound to claim that an array of unknown bound has.
  147. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  148. /// to an arbitrary value that's likely to loudly break things if it's used.
  149. static const uint64_t AssumedSizeForUnsizedArray =
  150. std::numeric_limits<uint64_t>::max() / 2;
  151. /// Determines if an LValue with the given LValueBase will have an unsized
  152. /// array in its designator.
  153. /// Find the path length and type of the most-derived subobject in the given
  154. /// path, and find the size of the containing array, if any.
  155. static unsigned
  156. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  157. ArrayRef<APValue::LValuePathEntry> Path,
  158. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  159. bool &FirstEntryIsUnsizedArray) {
  160. // This only accepts LValueBases from APValues, and APValues don't support
  161. // arrays that lack size info.
  162. assert(!isBaseAnAllocSizeCall(Base) &&
  163. "Unsized arrays shouldn't appear here");
  164. unsigned MostDerivedLength = 0;
  165. Type = getType(Base);
  166. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  167. if (Type->isArrayType()) {
  168. const ArrayType *AT = Ctx.getAsArrayType(Type);
  169. Type = AT->getElementType();
  170. MostDerivedLength = I + 1;
  171. IsArray = true;
  172. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  173. ArraySize = CAT->getSize().getZExtValue();
  174. } else {
  175. assert(I == 0 && "unexpected unsized array designator");
  176. FirstEntryIsUnsizedArray = true;
  177. ArraySize = AssumedSizeForUnsizedArray;
  178. }
  179. } else if (Type->isAnyComplexType()) {
  180. const ComplexType *CT = Type->castAs<ComplexType>();
  181. Type = CT->getElementType();
  182. ArraySize = 2;
  183. MostDerivedLength = I + 1;
  184. IsArray = true;
  185. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  186. Type = FD->getType();
  187. ArraySize = 0;
  188. MostDerivedLength = I + 1;
  189. IsArray = false;
  190. } else {
  191. // Path[I] describes a base class.
  192. ArraySize = 0;
  193. IsArray = false;
  194. }
  195. }
  196. return MostDerivedLength;
  197. }
  198. // The order of this enum is important for diagnostics.
  199. enum CheckSubobjectKind {
  200. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  201. CSK_This, CSK_Real, CSK_Imag
  202. };
  203. /// A path from a glvalue to a subobject of that glvalue.
  204. struct SubobjectDesignator {
  205. /// True if the subobject was named in a manner not supported by C++11. Such
  206. /// lvalues can still be folded, but they are not core constant expressions
  207. /// and we cannot perform lvalue-to-rvalue conversions on them.
  208. unsigned Invalid : 1;
  209. /// Is this a pointer one past the end of an object?
  210. unsigned IsOnePastTheEnd : 1;
  211. /// Indicator of whether the first entry is an unsized array.
  212. unsigned FirstEntryIsAnUnsizedArray : 1;
  213. /// Indicator of whether the most-derived object is an array element.
  214. unsigned MostDerivedIsArrayElement : 1;
  215. /// The length of the path to the most-derived object of which this is a
  216. /// subobject.
  217. unsigned MostDerivedPathLength : 28;
  218. /// The size of the array of which the most-derived object is an element.
  219. /// This will always be 0 if the most-derived object is not an array
  220. /// element. 0 is not an indicator of whether or not the most-derived object
  221. /// is an array, however, because 0-length arrays are allowed.
  222. ///
  223. /// If the current array is an unsized array, the value of this is
  224. /// undefined.
  225. uint64_t MostDerivedArraySize;
  226. /// The type of the most derived object referred to by this address.
  227. QualType MostDerivedType;
  228. typedef APValue::LValuePathEntry PathEntry;
  229. /// The entries on the path from the glvalue to the designated subobject.
  230. SmallVector<PathEntry, 8> Entries;
  231. SubobjectDesignator() : Invalid(true) {}
  232. explicit SubobjectDesignator(QualType T)
  233. : Invalid(false), IsOnePastTheEnd(false),
  234. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  235. MostDerivedPathLength(0), MostDerivedArraySize(0),
  236. MostDerivedType(T) {}
  237. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  238. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  239. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  240. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  241. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  242. if (!Invalid) {
  243. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  244. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  245. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  246. if (V.getLValueBase()) {
  247. bool IsArray = false;
  248. bool FirstIsUnsizedArray = false;
  249. MostDerivedPathLength = findMostDerivedSubobject(
  250. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  251. MostDerivedType, IsArray, FirstIsUnsizedArray);
  252. MostDerivedIsArrayElement = IsArray;
  253. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  254. }
  255. }
  256. }
  257. void setInvalid() {
  258. Invalid = true;
  259. Entries.clear();
  260. }
  261. /// Determine whether the most derived subobject is an array without a
  262. /// known bound.
  263. bool isMostDerivedAnUnsizedArray() const {
  264. assert(!Invalid && "Calling this makes no sense on invalid designators");
  265. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  266. }
  267. /// Determine what the most derived array's size is. Results in an assertion
  268. /// failure if the most derived array lacks a size.
  269. uint64_t getMostDerivedArraySize() const {
  270. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  271. return MostDerivedArraySize;
  272. }
  273. /// Determine whether this is a one-past-the-end pointer.
  274. bool isOnePastTheEnd() const {
  275. assert(!Invalid);
  276. if (IsOnePastTheEnd)
  277. return true;
  278. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  279. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  280. return true;
  281. return false;
  282. }
  283. /// Get the range of valid index adjustments in the form
  284. /// {maximum value that can be subtracted from this pointer,
  285. /// maximum value that can be added to this pointer}
  286. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  287. if (Invalid || isMostDerivedAnUnsizedArray())
  288. return {0, 0};
  289. // [expr.add]p4: For the purposes of these operators, a pointer to a
  290. // nonarray object behaves the same as a pointer to the first element of
  291. // an array of length one with the type of the object as its element type.
  292. bool IsArray = MostDerivedPathLength == Entries.size() &&
  293. MostDerivedIsArrayElement;
  294. uint64_t ArrayIndex =
  295. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  296. uint64_t ArraySize =
  297. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  298. return {ArrayIndex, ArraySize - ArrayIndex};
  299. }
  300. /// Check that this refers to a valid subobject.
  301. bool isValidSubobject() const {
  302. if (Invalid)
  303. return false;
  304. return !isOnePastTheEnd();
  305. }
  306. /// Check that this refers to a valid subobject, and if not, produce a
  307. /// relevant diagnostic and set the designator as invalid.
  308. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  309. /// Get the type of the designated object.
  310. QualType getType(ASTContext &Ctx) const {
  311. assert(!Invalid && "invalid designator has no subobject type");
  312. return MostDerivedPathLength == Entries.size()
  313. ? MostDerivedType
  314. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  315. }
  316. /// Update this designator to refer to the first element within this array.
  317. void addArrayUnchecked(const ConstantArrayType *CAT) {
  318. PathEntry Entry;
  319. Entry.ArrayIndex = 0;
  320. Entries.push_back(Entry);
  321. // This is a most-derived object.
  322. MostDerivedType = CAT->getElementType();
  323. MostDerivedIsArrayElement = true;
  324. MostDerivedArraySize = CAT->getSize().getZExtValue();
  325. MostDerivedPathLength = Entries.size();
  326. }
  327. /// Update this designator to refer to the first element within the array of
  328. /// elements of type T. This is an array of unknown size.
  329. void addUnsizedArrayUnchecked(QualType ElemTy) {
  330. PathEntry Entry;
  331. Entry.ArrayIndex = 0;
  332. Entries.push_back(Entry);
  333. MostDerivedType = ElemTy;
  334. MostDerivedIsArrayElement = true;
  335. // The value in MostDerivedArraySize is undefined in this case. So, set it
  336. // to an arbitrary value that's likely to loudly break things if it's
  337. // used.
  338. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  339. MostDerivedPathLength = Entries.size();
  340. }
  341. /// Update this designator to refer to the given base or member of this
  342. /// object.
  343. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  344. PathEntry Entry;
  345. APValue::BaseOrMemberType Value(D, Virtual);
  346. Entry.BaseOrMember = Value.getOpaqueValue();
  347. Entries.push_back(Entry);
  348. // If this isn't a base class, it's a new most-derived object.
  349. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  350. MostDerivedType = FD->getType();
  351. MostDerivedIsArrayElement = false;
  352. MostDerivedArraySize = 0;
  353. MostDerivedPathLength = Entries.size();
  354. }
  355. }
  356. /// Update this designator to refer to the given complex component.
  357. void addComplexUnchecked(QualType EltTy, bool Imag) {
  358. PathEntry Entry;
  359. Entry.ArrayIndex = Imag;
  360. Entries.push_back(Entry);
  361. // This is technically a most-derived object, though in practice this
  362. // is unlikely to matter.
  363. MostDerivedType = EltTy;
  364. MostDerivedIsArrayElement = true;
  365. MostDerivedArraySize = 2;
  366. MostDerivedPathLength = Entries.size();
  367. }
  368. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  369. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  370. const APSInt &N);
  371. /// Add N to the address of this subobject.
  372. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  373. if (Invalid || !N) return;
  374. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  375. if (isMostDerivedAnUnsizedArray()) {
  376. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  377. // Can't verify -- trust that the user is doing the right thing (or if
  378. // not, trust that the caller will catch the bad behavior).
  379. // FIXME: Should we reject if this overflows, at least?
  380. Entries.back().ArrayIndex += TruncatedN;
  381. return;
  382. }
  383. // [expr.add]p4: For the purposes of these operators, a pointer to a
  384. // nonarray object behaves the same as a pointer to the first element of
  385. // an array of length one with the type of the object as its element type.
  386. bool IsArray = MostDerivedPathLength == Entries.size() &&
  387. MostDerivedIsArrayElement;
  388. uint64_t ArrayIndex =
  389. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  390. uint64_t ArraySize =
  391. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  392. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  393. // Calculate the actual index in a wide enough type, so we can include
  394. // it in the note.
  395. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  396. (llvm::APInt&)N += ArrayIndex;
  397. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  398. diagnosePointerArithmetic(Info, E, N);
  399. setInvalid();
  400. return;
  401. }
  402. ArrayIndex += TruncatedN;
  403. assert(ArrayIndex <= ArraySize &&
  404. "bounds check succeeded for out-of-bounds index");
  405. if (IsArray)
  406. Entries.back().ArrayIndex = ArrayIndex;
  407. else
  408. IsOnePastTheEnd = (ArrayIndex != 0);
  409. }
  410. };
  411. /// A stack frame in the constexpr call stack.
  412. struct CallStackFrame {
  413. EvalInfo &Info;
  414. /// Parent - The caller of this stack frame.
  415. CallStackFrame *Caller;
  416. /// Callee - The function which was called.
  417. const FunctionDecl *Callee;
  418. /// This - The binding for the this pointer in this call, if any.
  419. const LValue *This;
  420. /// Arguments - Parameter bindings for this function call, indexed by
  421. /// parameters' function scope indices.
  422. APValue *Arguments;
  423. // Note that we intentionally use std::map here so that references to
  424. // values are stable.
  425. typedef std::pair<const void *, unsigned> MapKeyTy;
  426. typedef std::map<MapKeyTy, APValue> MapTy;
  427. /// Temporaries - Temporary lvalues materialized within this stack frame.
  428. MapTy Temporaries;
  429. /// CallLoc - The location of the call expression for this call.
  430. SourceLocation CallLoc;
  431. /// Index - The call index of this call.
  432. unsigned Index;
  433. /// The stack of integers for tracking version numbers for temporaries.
  434. SmallVector<unsigned, 2> TempVersionStack = {1};
  435. unsigned CurTempVersion = TempVersionStack.back();
  436. unsigned getTempVersion() const { return TempVersionStack.back(); }
  437. void pushTempVersion() {
  438. TempVersionStack.push_back(++CurTempVersion);
  439. }
  440. void popTempVersion() {
  441. TempVersionStack.pop_back();
  442. }
  443. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  444. // on the overall stack usage of deeply-recursing constexpr evaluataions.
  445. // (We should cache this map rather than recomputing it repeatedly.)
  446. // But let's try this and see how it goes; we can look into caching the map
  447. // as a later change.
  448. /// LambdaCaptureFields - Mapping from captured variables/this to
  449. /// corresponding data members in the closure class.
  450. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  451. FieldDecl *LambdaThisCaptureField;
  452. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  453. const FunctionDecl *Callee, const LValue *This,
  454. APValue *Arguments);
  455. ~CallStackFrame();
  456. // Return the temporary for Key whose version number is Version.
  457. APValue *getTemporary(const void *Key, unsigned Version) {
  458. MapKeyTy KV(Key, Version);
  459. auto LB = Temporaries.lower_bound(KV);
  460. if (LB != Temporaries.end() && LB->first == KV)
  461. return &LB->second;
  462. // Pair (Key,Version) wasn't found in the map. Check that no elements
  463. // in the map have 'Key' as their key.
  464. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  465. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  466. "Element with key 'Key' found in map");
  467. return nullptr;
  468. }
  469. // Return the current temporary for Key in the map.
  470. APValue *getCurrentTemporary(const void *Key) {
  471. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  472. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  473. return &std::prev(UB)->second;
  474. return nullptr;
  475. }
  476. // Return the version number of the current temporary for Key.
  477. unsigned getCurrentTemporaryVersion(const void *Key) const {
  478. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  479. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  480. return std::prev(UB)->first.second;
  481. return 0;
  482. }
  483. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  484. };
  485. /// Temporarily override 'this'.
  486. class ThisOverrideRAII {
  487. public:
  488. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  489. : Frame(Frame), OldThis(Frame.This) {
  490. if (Enable)
  491. Frame.This = NewThis;
  492. }
  493. ~ThisOverrideRAII() {
  494. Frame.This = OldThis;
  495. }
  496. private:
  497. CallStackFrame &Frame;
  498. const LValue *OldThis;
  499. };
  500. /// A partial diagnostic which we might know in advance that we are not going
  501. /// to emit.
  502. class OptionalDiagnostic {
  503. PartialDiagnostic *Diag;
  504. public:
  505. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  506. : Diag(Diag) {}
  507. template<typename T>
  508. OptionalDiagnostic &operator<<(const T &v) {
  509. if (Diag)
  510. *Diag << v;
  511. return *this;
  512. }
  513. OptionalDiagnostic &operator<<(const APSInt &I) {
  514. if (Diag) {
  515. SmallVector<char, 32> Buffer;
  516. I.toString(Buffer);
  517. *Diag << StringRef(Buffer.data(), Buffer.size());
  518. }
  519. return *this;
  520. }
  521. OptionalDiagnostic &operator<<(const APFloat &F) {
  522. if (Diag) {
  523. // FIXME: Force the precision of the source value down so we don't
  524. // print digits which are usually useless (we don't really care here if
  525. // we truncate a digit by accident in edge cases). Ideally,
  526. // APFloat::toString would automatically print the shortest
  527. // representation which rounds to the correct value, but it's a bit
  528. // tricky to implement.
  529. unsigned precision =
  530. llvm::APFloat::semanticsPrecision(F.getSemantics());
  531. precision = (precision * 59 + 195) / 196;
  532. SmallVector<char, 32> Buffer;
  533. F.toString(Buffer, precision);
  534. *Diag << StringRef(Buffer.data(), Buffer.size());
  535. }
  536. return *this;
  537. }
  538. };
  539. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  540. class Cleanup {
  541. llvm::PointerIntPair<APValue*, 1, bool> Value;
  542. public:
  543. Cleanup(APValue *Val, bool IsLifetimeExtended)
  544. : Value(Val, IsLifetimeExtended) {}
  545. bool isLifetimeExtended() const { return Value.getInt(); }
  546. void endLifetime() {
  547. *Value.getPointer() = APValue();
  548. }
  549. };
  550. /// EvalInfo - This is a private struct used by the evaluator to capture
  551. /// information about a subexpression as it is folded. It retains information
  552. /// about the AST context, but also maintains information about the folded
  553. /// expression.
  554. ///
  555. /// If an expression could be evaluated, it is still possible it is not a C
  556. /// "integer constant expression" or constant expression. If not, this struct
  557. /// captures information about how and why not.
  558. ///
  559. /// One bit of information passed *into* the request for constant folding
  560. /// indicates whether the subexpression is "evaluated" or not according to C
  561. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  562. /// evaluate the expression regardless of what the RHS is, but C only allows
  563. /// certain things in certain situations.
  564. struct EvalInfo {
  565. ASTContext &Ctx;
  566. /// EvalStatus - Contains information about the evaluation.
  567. Expr::EvalStatus &EvalStatus;
  568. /// CurrentCall - The top of the constexpr call stack.
  569. CallStackFrame *CurrentCall;
  570. /// CallStackDepth - The number of calls in the call stack right now.
  571. unsigned CallStackDepth;
  572. /// NextCallIndex - The next call index to assign.
  573. unsigned NextCallIndex;
  574. /// StepsLeft - The remaining number of evaluation steps we're permitted
  575. /// to perform. This is essentially a limit for the number of statements
  576. /// we will evaluate.
  577. unsigned StepsLeft;
  578. /// BottomFrame - The frame in which evaluation started. This must be
  579. /// initialized after CurrentCall and CallStackDepth.
  580. CallStackFrame BottomFrame;
  581. /// A stack of values whose lifetimes end at the end of some surrounding
  582. /// evaluation frame.
  583. llvm::SmallVector<Cleanup, 16> CleanupStack;
  584. /// EvaluatingDecl - This is the declaration whose initializer is being
  585. /// evaluated, if any.
  586. APValue::LValueBase EvaluatingDecl;
  587. /// EvaluatingDeclValue - This is the value being constructed for the
  588. /// declaration whose initializer is being evaluated, if any.
  589. APValue *EvaluatingDeclValue;
  590. /// EvaluatingObject - Pair of the AST node that an lvalue represents and
  591. /// the call index that that lvalue was allocated in.
  592. typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
  593. EvaluatingObject;
  594. /// EvaluatingConstructors - Set of objects that are currently being
  595. /// constructed.
  596. llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
  597. struct EvaluatingConstructorRAII {
  598. EvalInfo &EI;
  599. EvaluatingObject Object;
  600. bool DidInsert;
  601. EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
  602. : EI(EI), Object(Object) {
  603. DidInsert = EI.EvaluatingConstructors.insert(Object).second;
  604. }
  605. ~EvaluatingConstructorRAII() {
  606. if (DidInsert) EI.EvaluatingConstructors.erase(Object);
  607. }
  608. };
  609. bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
  610. unsigned Version) {
  611. return EvaluatingConstructors.count(
  612. EvaluatingObject(Decl, {CallIndex, Version}));
  613. }
  614. /// The current array initialization index, if we're performing array
  615. /// initialization.
  616. uint64_t ArrayInitIndex = -1;
  617. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  618. /// notes attached to it will also be stored, otherwise they will not be.
  619. bool HasActiveDiagnostic;
  620. /// Have we emitted a diagnostic explaining why we couldn't constant
  621. /// fold (not just why it's not strictly a constant expression)?
  622. bool HasFoldFailureDiagnostic;
  623. /// Whether or not we're currently speculatively evaluating.
  624. bool IsSpeculativelyEvaluating;
  625. enum EvaluationMode {
  626. /// Evaluate as a constant expression. Stop if we find that the expression
  627. /// is not a constant expression.
  628. EM_ConstantExpression,
  629. /// Evaluate as a potential constant expression. Keep going if we hit a
  630. /// construct that we can't evaluate yet (because we don't yet know the
  631. /// value of something) but stop if we hit something that could never be
  632. /// a constant expression.
  633. EM_PotentialConstantExpression,
  634. /// Fold the expression to a constant. Stop if we hit a side-effect that
  635. /// we can't model.
  636. EM_ConstantFold,
  637. /// Evaluate the expression looking for integer overflow and similar
  638. /// issues. Don't worry about side-effects, and try to visit all
  639. /// subexpressions.
  640. EM_EvaluateForOverflow,
  641. /// Evaluate in any way we know how. Don't worry about side-effects that
  642. /// can't be modeled.
  643. EM_IgnoreSideEffects,
  644. /// Evaluate as a constant expression. Stop if we find that the expression
  645. /// is not a constant expression. Some expressions can be retried in the
  646. /// optimizer if we don't constant fold them here, but in an unevaluated
  647. /// context we try to fold them immediately since the optimizer never
  648. /// gets a chance to look at it.
  649. EM_ConstantExpressionUnevaluated,
  650. /// Evaluate as a potential constant expression. Keep going if we hit a
  651. /// construct that we can't evaluate yet (because we don't yet know the
  652. /// value of something) but stop if we hit something that could never be
  653. /// a constant expression. Some expressions can be retried in the
  654. /// optimizer if we don't constant fold them here, but in an unevaluated
  655. /// context we try to fold them immediately since the optimizer never
  656. /// gets a chance to look at it.
  657. EM_PotentialConstantExpressionUnevaluated,
  658. } EvalMode;
  659. /// Are we checking whether the expression is a potential constant
  660. /// expression?
  661. bool checkingPotentialConstantExpression() const {
  662. return EvalMode == EM_PotentialConstantExpression ||
  663. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  664. }
  665. /// Are we checking an expression for overflow?
  666. // FIXME: We should check for any kind of undefined or suspicious behavior
  667. // in such constructs, not just overflow.
  668. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  669. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  670. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  671. CallStackDepth(0), NextCallIndex(1),
  672. StepsLeft(getLangOpts().ConstexprStepLimit),
  673. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  674. EvaluatingDecl((const ValueDecl *)nullptr),
  675. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  676. HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
  677. EvalMode(Mode) {}
  678. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  679. EvaluatingDecl = Base;
  680. EvaluatingDeclValue = &Value;
  681. EvaluatingConstructors.insert({Base, {0, 0}});
  682. }
  683. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  684. bool CheckCallLimit(SourceLocation Loc) {
  685. // Don't perform any constexpr calls (other than the call we're checking)
  686. // when checking a potential constant expression.
  687. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  688. return false;
  689. if (NextCallIndex == 0) {
  690. // NextCallIndex has wrapped around.
  691. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  692. return false;
  693. }
  694. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  695. return true;
  696. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  697. << getLangOpts().ConstexprCallDepth;
  698. return false;
  699. }
  700. CallStackFrame *getCallFrame(unsigned CallIndex) {
  701. assert(CallIndex && "no call index in getCallFrame");
  702. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  703. // be null in this loop.
  704. CallStackFrame *Frame = CurrentCall;
  705. while (Frame->Index > CallIndex)
  706. Frame = Frame->Caller;
  707. return (Frame->Index == CallIndex) ? Frame : nullptr;
  708. }
  709. bool nextStep(const Stmt *S) {
  710. if (!StepsLeft) {
  711. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  712. return false;
  713. }
  714. --StepsLeft;
  715. return true;
  716. }
  717. private:
  718. /// Add a diagnostic to the diagnostics list.
  719. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  720. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  721. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  722. return EvalStatus.Diag->back().second;
  723. }
  724. /// Add notes containing a call stack to the current point of evaluation.
  725. void addCallStack(unsigned Limit);
  726. private:
  727. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  728. unsigned ExtraNotes, bool IsCCEDiag) {
  729. if (EvalStatus.Diag) {
  730. // If we have a prior diagnostic, it will be noting that the expression
  731. // isn't a constant expression. This diagnostic is more important,
  732. // unless we require this evaluation to produce a constant expression.
  733. //
  734. // FIXME: We might want to show both diagnostics to the user in
  735. // EM_ConstantFold mode.
  736. if (!EvalStatus.Diag->empty()) {
  737. switch (EvalMode) {
  738. case EM_ConstantFold:
  739. case EM_IgnoreSideEffects:
  740. case EM_EvaluateForOverflow:
  741. if (!HasFoldFailureDiagnostic)
  742. break;
  743. // We've already failed to fold something. Keep that diagnostic.
  744. LLVM_FALLTHROUGH;
  745. case EM_ConstantExpression:
  746. case EM_PotentialConstantExpression:
  747. case EM_ConstantExpressionUnevaluated:
  748. case EM_PotentialConstantExpressionUnevaluated:
  749. HasActiveDiagnostic = false;
  750. return OptionalDiagnostic();
  751. }
  752. }
  753. unsigned CallStackNotes = CallStackDepth - 1;
  754. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  755. if (Limit)
  756. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  757. if (checkingPotentialConstantExpression())
  758. CallStackNotes = 0;
  759. HasActiveDiagnostic = true;
  760. HasFoldFailureDiagnostic = !IsCCEDiag;
  761. EvalStatus.Diag->clear();
  762. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  763. addDiag(Loc, DiagId);
  764. if (!checkingPotentialConstantExpression())
  765. addCallStack(Limit);
  766. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  767. }
  768. HasActiveDiagnostic = false;
  769. return OptionalDiagnostic();
  770. }
  771. public:
  772. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  773. OptionalDiagnostic
  774. FFDiag(SourceLocation Loc,
  775. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  776. unsigned ExtraNotes = 0) {
  777. return Diag(Loc, DiagId, ExtraNotes, false);
  778. }
  779. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  780. = diag::note_invalid_subexpr_in_const_expr,
  781. unsigned ExtraNotes = 0) {
  782. if (EvalStatus.Diag)
  783. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  784. HasActiveDiagnostic = false;
  785. return OptionalDiagnostic();
  786. }
  787. /// Diagnose that the evaluation does not produce a C++11 core constant
  788. /// expression.
  789. ///
  790. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  791. /// EM_PotentialConstantExpression mode and we produce one of these.
  792. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  793. = diag::note_invalid_subexpr_in_const_expr,
  794. unsigned ExtraNotes = 0) {
  795. // Don't override a previous diagnostic. Don't bother collecting
  796. // diagnostics if we're evaluating for overflow.
  797. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  798. HasActiveDiagnostic = false;
  799. return OptionalDiagnostic();
  800. }
  801. return Diag(Loc, DiagId, ExtraNotes, true);
  802. }
  803. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  804. = diag::note_invalid_subexpr_in_const_expr,
  805. unsigned ExtraNotes = 0) {
  806. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  807. }
  808. /// Add a note to a prior diagnostic.
  809. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  810. if (!HasActiveDiagnostic)
  811. return OptionalDiagnostic();
  812. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  813. }
  814. /// Add a stack of notes to a prior diagnostic.
  815. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  816. if (HasActiveDiagnostic) {
  817. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  818. Diags.begin(), Diags.end());
  819. }
  820. }
  821. /// Should we continue evaluation after encountering a side-effect that we
  822. /// couldn't model?
  823. bool keepEvaluatingAfterSideEffect() {
  824. switch (EvalMode) {
  825. case EM_PotentialConstantExpression:
  826. case EM_PotentialConstantExpressionUnevaluated:
  827. case EM_EvaluateForOverflow:
  828. case EM_IgnoreSideEffects:
  829. return true;
  830. case EM_ConstantExpression:
  831. case EM_ConstantExpressionUnevaluated:
  832. case EM_ConstantFold:
  833. return false;
  834. }
  835. llvm_unreachable("Missed EvalMode case");
  836. }
  837. /// Note that we have had a side-effect, and determine whether we should
  838. /// keep evaluating.
  839. bool noteSideEffect() {
  840. EvalStatus.HasSideEffects = true;
  841. return keepEvaluatingAfterSideEffect();
  842. }
  843. /// Should we continue evaluation after encountering undefined behavior?
  844. bool keepEvaluatingAfterUndefinedBehavior() {
  845. switch (EvalMode) {
  846. case EM_EvaluateForOverflow:
  847. case EM_IgnoreSideEffects:
  848. case EM_ConstantFold:
  849. return true;
  850. case EM_PotentialConstantExpression:
  851. case EM_PotentialConstantExpressionUnevaluated:
  852. case EM_ConstantExpression:
  853. case EM_ConstantExpressionUnevaluated:
  854. return false;
  855. }
  856. llvm_unreachable("Missed EvalMode case");
  857. }
  858. /// Note that we hit something that was technically undefined behavior, but
  859. /// that we can evaluate past it (such as signed overflow or floating-point
  860. /// division by zero.)
  861. bool noteUndefinedBehavior() {
  862. EvalStatus.HasUndefinedBehavior = true;
  863. return keepEvaluatingAfterUndefinedBehavior();
  864. }
  865. /// Should we continue evaluation as much as possible after encountering a
  866. /// construct which can't be reduced to a value?
  867. bool keepEvaluatingAfterFailure() {
  868. if (!StepsLeft)
  869. return false;
  870. switch (EvalMode) {
  871. case EM_PotentialConstantExpression:
  872. case EM_PotentialConstantExpressionUnevaluated:
  873. case EM_EvaluateForOverflow:
  874. return true;
  875. case EM_ConstantExpression:
  876. case EM_ConstantExpressionUnevaluated:
  877. case EM_ConstantFold:
  878. case EM_IgnoreSideEffects:
  879. return false;
  880. }
  881. llvm_unreachable("Missed EvalMode case");
  882. }
  883. /// Notes that we failed to evaluate an expression that other expressions
  884. /// directly depend on, and determine if we should keep evaluating. This
  885. /// should only be called if we actually intend to keep evaluating.
  886. ///
  887. /// Call noteSideEffect() instead if we may be able to ignore the value that
  888. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  889. ///
  890. /// (Foo(), 1) // use noteSideEffect
  891. /// (Foo() || true) // use noteSideEffect
  892. /// Foo() + 1 // use noteFailure
  893. LLVM_NODISCARD bool noteFailure() {
  894. // Failure when evaluating some expression often means there is some
  895. // subexpression whose evaluation was skipped. Therefore, (because we
  896. // don't track whether we skipped an expression when unwinding after an
  897. // evaluation failure) every evaluation failure that bubbles up from a
  898. // subexpression implies that a side-effect has potentially happened. We
  899. // skip setting the HasSideEffects flag to true until we decide to
  900. // continue evaluating after that point, which happens here.
  901. bool KeepGoing = keepEvaluatingAfterFailure();
  902. EvalStatus.HasSideEffects |= KeepGoing;
  903. return KeepGoing;
  904. }
  905. class ArrayInitLoopIndex {
  906. EvalInfo &Info;
  907. uint64_t OuterIndex;
  908. public:
  909. ArrayInitLoopIndex(EvalInfo &Info)
  910. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  911. Info.ArrayInitIndex = 0;
  912. }
  913. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  914. operator uint64_t&() { return Info.ArrayInitIndex; }
  915. };
  916. };
  917. /// Object used to treat all foldable expressions as constant expressions.
  918. struct FoldConstant {
  919. EvalInfo &Info;
  920. bool Enabled;
  921. bool HadNoPriorDiags;
  922. EvalInfo::EvaluationMode OldMode;
  923. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  924. : Info(Info),
  925. Enabled(Enabled),
  926. HadNoPriorDiags(Info.EvalStatus.Diag &&
  927. Info.EvalStatus.Diag->empty() &&
  928. !Info.EvalStatus.HasSideEffects),
  929. OldMode(Info.EvalMode) {
  930. if (Enabled &&
  931. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  932. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  933. Info.EvalMode = EvalInfo::EM_ConstantFold;
  934. }
  935. void keepDiagnostics() { Enabled = false; }
  936. ~FoldConstant() {
  937. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  938. !Info.EvalStatus.HasSideEffects)
  939. Info.EvalStatus.Diag->clear();
  940. Info.EvalMode = OldMode;
  941. }
  942. };
  943. /// RAII object used to set the current evaluation mode to ignore
  944. /// side-effects.
  945. struct IgnoreSideEffectsRAII {
  946. EvalInfo &Info;
  947. EvalInfo::EvaluationMode OldMode;
  948. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  949. : Info(Info), OldMode(Info.EvalMode) {
  950. if (!Info.checkingPotentialConstantExpression())
  951. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  952. }
  953. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  954. };
  955. /// RAII object used to optionally suppress diagnostics and side-effects from
  956. /// a speculative evaluation.
  957. class SpeculativeEvaluationRAII {
  958. EvalInfo *Info = nullptr;
  959. Expr::EvalStatus OldStatus;
  960. bool OldIsSpeculativelyEvaluating;
  961. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  962. Info = Other.Info;
  963. OldStatus = Other.OldStatus;
  964. OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
  965. Other.Info = nullptr;
  966. }
  967. void maybeRestoreState() {
  968. if (!Info)
  969. return;
  970. Info->EvalStatus = OldStatus;
  971. Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
  972. }
  973. public:
  974. SpeculativeEvaluationRAII() = default;
  975. SpeculativeEvaluationRAII(
  976. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  977. : Info(&Info), OldStatus(Info.EvalStatus),
  978. OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
  979. Info.EvalStatus.Diag = NewDiag;
  980. Info.IsSpeculativelyEvaluating = true;
  981. }
  982. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  983. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  984. moveFromAndCancel(std::move(Other));
  985. }
  986. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  987. maybeRestoreState();
  988. moveFromAndCancel(std::move(Other));
  989. return *this;
  990. }
  991. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  992. };
  993. /// RAII object wrapping a full-expression or block scope, and handling
  994. /// the ending of the lifetime of temporaries created within it.
  995. template<bool IsFullExpression>
  996. class ScopeRAII {
  997. EvalInfo &Info;
  998. unsigned OldStackSize;
  999. public:
  1000. ScopeRAII(EvalInfo &Info)
  1001. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1002. // Push a new temporary version. This is needed to distinguish between
  1003. // temporaries created in different iterations of a loop.
  1004. Info.CurrentCall->pushTempVersion();
  1005. }
  1006. ~ScopeRAII() {
  1007. // Body moved to a static method to encourage the compiler to inline away
  1008. // instances of this class.
  1009. cleanup(Info, OldStackSize);
  1010. Info.CurrentCall->popTempVersion();
  1011. }
  1012. private:
  1013. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  1014. unsigned NewEnd = OldStackSize;
  1015. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  1016. I != N; ++I) {
  1017. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  1018. // Full-expression cleanup of a lifetime-extended temporary: nothing
  1019. // to do, just move this cleanup to the right place in the stack.
  1020. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  1021. ++NewEnd;
  1022. } else {
  1023. // End the lifetime of the object.
  1024. Info.CleanupStack[I].endLifetime();
  1025. }
  1026. }
  1027. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1028. Info.CleanupStack.end());
  1029. }
  1030. };
  1031. typedef ScopeRAII<false> BlockScopeRAII;
  1032. typedef ScopeRAII<true> FullExpressionRAII;
  1033. }
  1034. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1035. CheckSubobjectKind CSK) {
  1036. if (Invalid)
  1037. return false;
  1038. if (isOnePastTheEnd()) {
  1039. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1040. << CSK;
  1041. setInvalid();
  1042. return false;
  1043. }
  1044. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1045. // must actually be at least one array element; even a VLA cannot have a
  1046. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1047. return true;
  1048. }
  1049. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1050. const Expr *E) {
  1051. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1052. // Do not set the designator as invalid: we can represent this situation,
  1053. // and correct handling of __builtin_object_size requires us to do so.
  1054. }
  1055. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1056. const Expr *E,
  1057. const APSInt &N) {
  1058. // If we're complaining, we must be able to statically determine the size of
  1059. // the most derived array.
  1060. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1061. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1062. << N << /*array*/ 0
  1063. << static_cast<unsigned>(getMostDerivedArraySize());
  1064. else
  1065. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1066. << N << /*non-array*/ 1;
  1067. setInvalid();
  1068. }
  1069. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1070. const FunctionDecl *Callee, const LValue *This,
  1071. APValue *Arguments)
  1072. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1073. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1074. Info.CurrentCall = this;
  1075. ++Info.CallStackDepth;
  1076. }
  1077. CallStackFrame::~CallStackFrame() {
  1078. assert(Info.CurrentCall == this && "calls retired out of order");
  1079. --Info.CallStackDepth;
  1080. Info.CurrentCall = Caller;
  1081. }
  1082. APValue &CallStackFrame::createTemporary(const void *Key,
  1083. bool IsLifetimeExtended) {
  1084. unsigned Version = Info.CurrentCall->getTempVersion();
  1085. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1086. assert(Result.isUninit() && "temporary created multiple times");
  1087. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1088. return Result;
  1089. }
  1090. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  1091. void EvalInfo::addCallStack(unsigned Limit) {
  1092. // Determine which calls to skip, if any.
  1093. unsigned ActiveCalls = CallStackDepth - 1;
  1094. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  1095. if (Limit && Limit < ActiveCalls) {
  1096. SkipStart = Limit / 2 + Limit % 2;
  1097. SkipEnd = ActiveCalls - Limit / 2;
  1098. }
  1099. // Walk the call stack and add the diagnostics.
  1100. unsigned CallIdx = 0;
  1101. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  1102. Frame = Frame->Caller, ++CallIdx) {
  1103. // Skip this call?
  1104. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  1105. if (CallIdx == SkipStart) {
  1106. // Note that we're skipping calls.
  1107. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  1108. << unsigned(ActiveCalls - Limit);
  1109. }
  1110. continue;
  1111. }
  1112. // Use a different note for an inheriting constructor, because from the
  1113. // user's perspective it's not really a function at all.
  1114. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  1115. if (CD->isInheritingConstructor()) {
  1116. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  1117. << CD->getParent();
  1118. continue;
  1119. }
  1120. }
  1121. SmallVector<char, 128> Buffer;
  1122. llvm::raw_svector_ostream Out(Buffer);
  1123. describeCall(Frame, Out);
  1124. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  1125. }
  1126. }
  1127. namespace {
  1128. struct ComplexValue {
  1129. private:
  1130. bool IsInt;
  1131. public:
  1132. APSInt IntReal, IntImag;
  1133. APFloat FloatReal, FloatImag;
  1134. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1135. void makeComplexFloat() { IsInt = false; }
  1136. bool isComplexFloat() const { return !IsInt; }
  1137. APFloat &getComplexFloatReal() { return FloatReal; }
  1138. APFloat &getComplexFloatImag() { return FloatImag; }
  1139. void makeComplexInt() { IsInt = true; }
  1140. bool isComplexInt() const { return IsInt; }
  1141. APSInt &getComplexIntReal() { return IntReal; }
  1142. APSInt &getComplexIntImag() { return IntImag; }
  1143. void moveInto(APValue &v) const {
  1144. if (isComplexFloat())
  1145. v = APValue(FloatReal, FloatImag);
  1146. else
  1147. v = APValue(IntReal, IntImag);
  1148. }
  1149. void setFrom(const APValue &v) {
  1150. assert(v.isComplexFloat() || v.isComplexInt());
  1151. if (v.isComplexFloat()) {
  1152. makeComplexFloat();
  1153. FloatReal = v.getComplexFloatReal();
  1154. FloatImag = v.getComplexFloatImag();
  1155. } else {
  1156. makeComplexInt();
  1157. IntReal = v.getComplexIntReal();
  1158. IntImag = v.getComplexIntImag();
  1159. }
  1160. }
  1161. };
  1162. struct LValue {
  1163. APValue::LValueBase Base;
  1164. CharUnits Offset;
  1165. SubobjectDesignator Designator;
  1166. bool IsNullPtr : 1;
  1167. bool InvalidBase : 1;
  1168. const APValue::LValueBase getLValueBase() const { return Base; }
  1169. CharUnits &getLValueOffset() { return Offset; }
  1170. const CharUnits &getLValueOffset() const { return Offset; }
  1171. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1172. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1173. bool isNullPointer() const { return IsNullPtr;}
  1174. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1175. unsigned getLValueVersion() const { return Base.getVersion(); }
  1176. void moveInto(APValue &V) const {
  1177. if (Designator.Invalid)
  1178. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1179. else {
  1180. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1181. V = APValue(Base, Offset, Designator.Entries,
  1182. Designator.IsOnePastTheEnd, IsNullPtr);
  1183. }
  1184. }
  1185. void setFrom(ASTContext &Ctx, const APValue &V) {
  1186. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1187. Base = V.getLValueBase();
  1188. Offset = V.getLValueOffset();
  1189. InvalidBase = false;
  1190. Designator = SubobjectDesignator(Ctx, V);
  1191. IsNullPtr = V.isNullPointer();
  1192. }
  1193. void set(APValue::LValueBase B, bool BInvalid = false) {
  1194. #ifndef NDEBUG
  1195. // We only allow a few types of invalid bases. Enforce that here.
  1196. if (BInvalid) {
  1197. const auto *E = B.get<const Expr *>();
  1198. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1199. "Unexpected type of invalid base");
  1200. }
  1201. #endif
  1202. Base = B;
  1203. Offset = CharUnits::fromQuantity(0);
  1204. InvalidBase = BInvalid;
  1205. Designator = SubobjectDesignator(getType(B));
  1206. IsNullPtr = false;
  1207. }
  1208. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1209. Base = (Expr *)nullptr;
  1210. Offset = CharUnits::fromQuantity(TargetVal);
  1211. InvalidBase = false;
  1212. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1213. IsNullPtr = true;
  1214. }
  1215. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1216. set(B, true);
  1217. }
  1218. // Check that this LValue is not based on a null pointer. If it is, produce
  1219. // a diagnostic and mark the designator as invalid.
  1220. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1221. CheckSubobjectKind CSK) {
  1222. if (Designator.Invalid)
  1223. return false;
  1224. if (IsNullPtr) {
  1225. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  1226. << CSK;
  1227. Designator.setInvalid();
  1228. return false;
  1229. }
  1230. return true;
  1231. }
  1232. // Check this LValue refers to an object. If not, set the designator to be
  1233. // invalid and emit a diagnostic.
  1234. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1235. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1236. Designator.checkSubobject(Info, E, CSK);
  1237. }
  1238. void addDecl(EvalInfo &Info, const Expr *E,
  1239. const Decl *D, bool Virtual = false) {
  1240. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1241. Designator.addDeclUnchecked(D, Virtual);
  1242. }
  1243. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1244. if (!Designator.Entries.empty()) {
  1245. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1246. Designator.setInvalid();
  1247. return;
  1248. }
  1249. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1250. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1251. Designator.FirstEntryIsAnUnsizedArray = true;
  1252. Designator.addUnsizedArrayUnchecked(ElemTy);
  1253. }
  1254. }
  1255. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1256. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1257. Designator.addArrayUnchecked(CAT);
  1258. }
  1259. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1260. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1261. Designator.addComplexUnchecked(EltTy, Imag);
  1262. }
  1263. void clearIsNullPointer() {
  1264. IsNullPtr = false;
  1265. }
  1266. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1267. const APSInt &Index, CharUnits ElementSize) {
  1268. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1269. // but we're not required to diagnose it and it's valid in C++.)
  1270. if (!Index)
  1271. return;
  1272. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1273. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1274. // offsets.
  1275. uint64_t Offset64 = Offset.getQuantity();
  1276. uint64_t ElemSize64 = ElementSize.getQuantity();
  1277. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1278. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1279. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1280. Designator.adjustIndex(Info, E, Index);
  1281. clearIsNullPointer();
  1282. }
  1283. void adjustOffset(CharUnits N) {
  1284. Offset += N;
  1285. if (N.getQuantity())
  1286. clearIsNullPointer();
  1287. }
  1288. };
  1289. struct MemberPtr {
  1290. MemberPtr() {}
  1291. explicit MemberPtr(const ValueDecl *Decl) :
  1292. DeclAndIsDerivedMember(Decl, false), Path() {}
  1293. /// The member or (direct or indirect) field referred to by this member
  1294. /// pointer, or 0 if this is a null member pointer.
  1295. const ValueDecl *getDecl() const {
  1296. return DeclAndIsDerivedMember.getPointer();
  1297. }
  1298. /// Is this actually a member of some type derived from the relevant class?
  1299. bool isDerivedMember() const {
  1300. return DeclAndIsDerivedMember.getInt();
  1301. }
  1302. /// Get the class which the declaration actually lives in.
  1303. const CXXRecordDecl *getContainingRecord() const {
  1304. return cast<CXXRecordDecl>(
  1305. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1306. }
  1307. void moveInto(APValue &V) const {
  1308. V = APValue(getDecl(), isDerivedMember(), Path);
  1309. }
  1310. void setFrom(const APValue &V) {
  1311. assert(V.isMemberPointer());
  1312. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1313. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1314. Path.clear();
  1315. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1316. Path.insert(Path.end(), P.begin(), P.end());
  1317. }
  1318. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1319. /// whether the member is a member of some class derived from the class type
  1320. /// of the member pointer.
  1321. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1322. /// Path - The path of base/derived classes from the member declaration's
  1323. /// class (exclusive) to the class type of the member pointer (inclusive).
  1324. SmallVector<const CXXRecordDecl*, 4> Path;
  1325. /// Perform a cast towards the class of the Decl (either up or down the
  1326. /// hierarchy).
  1327. bool castBack(const CXXRecordDecl *Class) {
  1328. assert(!Path.empty());
  1329. const CXXRecordDecl *Expected;
  1330. if (Path.size() >= 2)
  1331. Expected = Path[Path.size() - 2];
  1332. else
  1333. Expected = getContainingRecord();
  1334. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1335. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1336. // if B does not contain the original member and is not a base or
  1337. // derived class of the class containing the original member, the result
  1338. // of the cast is undefined.
  1339. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1340. // (D::*). We consider that to be a language defect.
  1341. return false;
  1342. }
  1343. Path.pop_back();
  1344. return true;
  1345. }
  1346. /// Perform a base-to-derived member pointer cast.
  1347. bool castToDerived(const CXXRecordDecl *Derived) {
  1348. if (!getDecl())
  1349. return true;
  1350. if (!isDerivedMember()) {
  1351. Path.push_back(Derived);
  1352. return true;
  1353. }
  1354. if (!castBack(Derived))
  1355. return false;
  1356. if (Path.empty())
  1357. DeclAndIsDerivedMember.setInt(false);
  1358. return true;
  1359. }
  1360. /// Perform a derived-to-base member pointer cast.
  1361. bool castToBase(const CXXRecordDecl *Base) {
  1362. if (!getDecl())
  1363. return true;
  1364. if (Path.empty())
  1365. DeclAndIsDerivedMember.setInt(true);
  1366. if (isDerivedMember()) {
  1367. Path.push_back(Base);
  1368. return true;
  1369. }
  1370. return castBack(Base);
  1371. }
  1372. };
  1373. /// Compare two member pointers, which are assumed to be of the same type.
  1374. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1375. if (!LHS.getDecl() || !RHS.getDecl())
  1376. return !LHS.getDecl() && !RHS.getDecl();
  1377. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1378. return false;
  1379. return LHS.Path == RHS.Path;
  1380. }
  1381. }
  1382. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1383. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1384. const LValue &This, const Expr *E,
  1385. bool AllowNonLiteralTypes = false);
  1386. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1387. bool InvalidBaseOK = false);
  1388. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1389. bool InvalidBaseOK = false);
  1390. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1391. EvalInfo &Info);
  1392. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1393. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1394. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1395. EvalInfo &Info);
  1396. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1397. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1398. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1399. EvalInfo &Info);
  1400. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1401. //===----------------------------------------------------------------------===//
  1402. // Misc utilities
  1403. //===----------------------------------------------------------------------===//
  1404. /// A helper function to create a temporary and set an LValue.
  1405. template <class KeyTy>
  1406. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1407. LValue &LV, CallStackFrame &Frame) {
  1408. LV.set({Key, Frame.Info.CurrentCall->Index,
  1409. Frame.Info.CurrentCall->getTempVersion()});
  1410. return Frame.createTemporary(Key, IsLifetimeExtended);
  1411. }
  1412. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1413. /// preserving its value (by extending by up to one bit as needed).
  1414. static void negateAsSigned(APSInt &Int) {
  1415. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1416. Int = Int.extend(Int.getBitWidth() + 1);
  1417. Int.setIsSigned(true);
  1418. }
  1419. Int = -Int;
  1420. }
  1421. /// Produce a string describing the given constexpr call.
  1422. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1423. unsigned ArgIndex = 0;
  1424. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1425. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1426. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1427. if (!IsMemberCall)
  1428. Out << *Frame->Callee << '(';
  1429. if (Frame->This && IsMemberCall) {
  1430. APValue Val;
  1431. Frame->This->moveInto(Val);
  1432. Val.printPretty(Out, Frame->Info.Ctx,
  1433. Frame->This->Designator.MostDerivedType);
  1434. // FIXME: Add parens around Val if needed.
  1435. Out << "->" << *Frame->Callee << '(';
  1436. IsMemberCall = false;
  1437. }
  1438. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1439. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1440. if (ArgIndex > (unsigned)IsMemberCall)
  1441. Out << ", ";
  1442. const ParmVarDecl *Param = *I;
  1443. const APValue &Arg = Frame->Arguments[ArgIndex];
  1444. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1445. if (ArgIndex == 0 && IsMemberCall)
  1446. Out << "->" << *Frame->Callee << '(';
  1447. }
  1448. Out << ')';
  1449. }
  1450. /// Evaluate an expression to see if it had side-effects, and discard its
  1451. /// result.
  1452. /// \return \c true if the caller should keep evaluating.
  1453. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1454. APValue Scratch;
  1455. if (!Evaluate(Scratch, Info, E))
  1456. // We don't need the value, but we might have skipped a side effect here.
  1457. return Info.noteSideEffect();
  1458. return true;
  1459. }
  1460. /// Should this call expression be treated as a string literal?
  1461. static bool IsStringLiteralCall(const CallExpr *E) {
  1462. unsigned Builtin = E->getBuiltinCallee();
  1463. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1464. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1465. }
  1466. static bool IsGlobalLValue(APValue::LValueBase B) {
  1467. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1468. // constant expression of pointer type that evaluates to...
  1469. // ... a null pointer value, or a prvalue core constant expression of type
  1470. // std::nullptr_t.
  1471. if (!B) return true;
  1472. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1473. // ... the address of an object with static storage duration,
  1474. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1475. return VD->hasGlobalStorage();
  1476. // ... the address of a function,
  1477. return isa<FunctionDecl>(D);
  1478. }
  1479. const Expr *E = B.get<const Expr*>();
  1480. switch (E->getStmtClass()) {
  1481. default:
  1482. return false;
  1483. case Expr::CompoundLiteralExprClass: {
  1484. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1485. return CLE->isFileScope() && CLE->isLValue();
  1486. }
  1487. case Expr::MaterializeTemporaryExprClass:
  1488. // A materialized temporary might have been lifetime-extended to static
  1489. // storage duration.
  1490. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1491. // A string literal has static storage duration.
  1492. case Expr::StringLiteralClass:
  1493. case Expr::PredefinedExprClass:
  1494. case Expr::ObjCStringLiteralClass:
  1495. case Expr::ObjCEncodeExprClass:
  1496. case Expr::CXXTypeidExprClass:
  1497. case Expr::CXXUuidofExprClass:
  1498. return true;
  1499. case Expr::CallExprClass:
  1500. return IsStringLiteralCall(cast<CallExpr>(E));
  1501. // For GCC compatibility, &&label has static storage duration.
  1502. case Expr::AddrLabelExprClass:
  1503. return true;
  1504. // A Block literal expression may be used as the initialization value for
  1505. // Block variables at global or local static scope.
  1506. case Expr::BlockExprClass:
  1507. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1508. case Expr::ImplicitValueInitExprClass:
  1509. // FIXME:
  1510. // We can never form an lvalue with an implicit value initialization as its
  1511. // base through expression evaluation, so these only appear in one case: the
  1512. // implicit variable declaration we invent when checking whether a constexpr
  1513. // constructor can produce a constant expression. We must assume that such
  1514. // an expression might be a global lvalue.
  1515. return true;
  1516. }
  1517. }
  1518. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1519. return LVal.Base.dyn_cast<const ValueDecl*>();
  1520. }
  1521. static bool IsLiteralLValue(const LValue &Value) {
  1522. if (Value.getLValueCallIndex())
  1523. return false;
  1524. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1525. return E && !isa<MaterializeTemporaryExpr>(E);
  1526. }
  1527. static bool IsWeakLValue(const LValue &Value) {
  1528. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1529. return Decl && Decl->isWeak();
  1530. }
  1531. static bool isZeroSized(const LValue &Value) {
  1532. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1533. if (Decl && isa<VarDecl>(Decl)) {
  1534. QualType Ty = Decl->getType();
  1535. if (Ty->isArrayType())
  1536. return Ty->isIncompleteType() ||
  1537. Decl->getASTContext().getTypeSize(Ty) == 0;
  1538. }
  1539. return false;
  1540. }
  1541. static bool HasSameBase(const LValue &A, const LValue &B) {
  1542. if (!A.getLValueBase())
  1543. return !B.getLValueBase();
  1544. if (!B.getLValueBase())
  1545. return false;
  1546. if (A.getLValueBase().getOpaqueValue() !=
  1547. B.getLValueBase().getOpaqueValue()) {
  1548. const Decl *ADecl = GetLValueBaseDecl(A);
  1549. if (!ADecl)
  1550. return false;
  1551. const Decl *BDecl = GetLValueBaseDecl(B);
  1552. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1553. return false;
  1554. }
  1555. return IsGlobalLValue(A.getLValueBase()) ||
  1556. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1557. A.getLValueVersion() == B.getLValueVersion());
  1558. }
  1559. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1560. assert(Base && "no location for a null lvalue");
  1561. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1562. if (VD)
  1563. Info.Note(VD->getLocation(), diag::note_declared_at);
  1564. else
  1565. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1566. diag::note_constexpr_temporary_here);
  1567. }
  1568. /// Check that this reference or pointer core constant expression is a valid
  1569. /// value for an address or reference constant expression. Return true if we
  1570. /// can fold this expression, whether or not it's a constant expression.
  1571. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1572. QualType Type, const LValue &LVal,
  1573. Expr::ConstExprUsage Usage) {
  1574. bool IsReferenceType = Type->isReferenceType();
  1575. APValue::LValueBase Base = LVal.getLValueBase();
  1576. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1577. // Check that the object is a global. Note that the fake 'this' object we
  1578. // manufacture when checking potential constant expressions is conservatively
  1579. // assumed to be global here.
  1580. if (!IsGlobalLValue(Base)) {
  1581. if (Info.getLangOpts().CPlusPlus11) {
  1582. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1583. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1584. << IsReferenceType << !Designator.Entries.empty()
  1585. << !!VD << VD;
  1586. NoteLValueLocation(Info, Base);
  1587. } else {
  1588. Info.FFDiag(Loc);
  1589. }
  1590. // Don't allow references to temporaries to escape.
  1591. return false;
  1592. }
  1593. assert((Info.checkingPotentialConstantExpression() ||
  1594. LVal.getLValueCallIndex() == 0) &&
  1595. "have call index for global lvalue");
  1596. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1597. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1598. // Check if this is a thread-local variable.
  1599. if (Var->getTLSKind())
  1600. return false;
  1601. // A dllimport variable never acts like a constant.
  1602. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1603. return false;
  1604. }
  1605. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1606. // __declspec(dllimport) must be handled very carefully:
  1607. // We must never initialize an expression with the thunk in C++.
  1608. // Doing otherwise would allow the same id-expression to yield
  1609. // different addresses for the same function in different translation
  1610. // units. However, this means that we must dynamically initialize the
  1611. // expression with the contents of the import address table at runtime.
  1612. //
  1613. // The C language has no notion of ODR; furthermore, it has no notion of
  1614. // dynamic initialization. This means that we are permitted to
  1615. // perform initialization with the address of the thunk.
  1616. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1617. FD->hasAttr<DLLImportAttr>())
  1618. return false;
  1619. }
  1620. }
  1621. // Allow address constant expressions to be past-the-end pointers. This is
  1622. // an extension: the standard requires them to point to an object.
  1623. if (!IsReferenceType)
  1624. return true;
  1625. // A reference constant expression must refer to an object.
  1626. if (!Base) {
  1627. // FIXME: diagnostic
  1628. Info.CCEDiag(Loc);
  1629. return true;
  1630. }
  1631. // Does this refer one past the end of some object?
  1632. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1633. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1634. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1635. << !Designator.Entries.empty() << !!VD << VD;
  1636. NoteLValueLocation(Info, Base);
  1637. }
  1638. return true;
  1639. }
  1640. /// Member pointers are constant expressions unless they point to a
  1641. /// non-virtual dllimport member function.
  1642. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1643. SourceLocation Loc,
  1644. QualType Type,
  1645. const APValue &Value,
  1646. Expr::ConstExprUsage Usage) {
  1647. const ValueDecl *Member = Value.getMemberPointerDecl();
  1648. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1649. if (!FD)
  1650. return true;
  1651. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1652. !FD->hasAttr<DLLImportAttr>();
  1653. }
  1654. /// Check that this core constant expression is of literal type, and if not,
  1655. /// produce an appropriate diagnostic.
  1656. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1657. const LValue *This = nullptr) {
  1658. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1659. return true;
  1660. // C++1y: A constant initializer for an object o [...] may also invoke
  1661. // constexpr constructors for o and its subobjects even if those objects
  1662. // are of non-literal class types.
  1663. //
  1664. // C++11 missed this detail for aggregates, so classes like this:
  1665. // struct foo_t { union { int i; volatile int j; } u; };
  1666. // are not (obviously) initializable like so:
  1667. // __attribute__((__require_constant_initialization__))
  1668. // static const foo_t x = {{0}};
  1669. // because "i" is a subobject with non-literal initialization (due to the
  1670. // volatile member of the union). See:
  1671. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1672. // Therefore, we use the C++1y behavior.
  1673. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1674. return true;
  1675. // Prvalue constant expressions must be of literal types.
  1676. if (Info.getLangOpts().CPlusPlus11)
  1677. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1678. << E->getType();
  1679. else
  1680. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1681. return false;
  1682. }
  1683. /// Check that this core constant expression value is a valid value for a
  1684. /// constant expression. If not, report an appropriate diagnostic. Does not
  1685. /// check that the expression is of literal type.
  1686. static bool
  1687. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1688. const APValue &Value,
  1689. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1690. if (Value.isUninit()) {
  1691. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1692. << true << Type;
  1693. return false;
  1694. }
  1695. // We allow _Atomic(T) to be initialized from anything that T can be
  1696. // initialized from.
  1697. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1698. Type = AT->getValueType();
  1699. // Core issue 1454: For a literal constant expression of array or class type,
  1700. // each subobject of its value shall have been initialized by a constant
  1701. // expression.
  1702. if (Value.isArray()) {
  1703. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1704. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1705. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1706. Value.getArrayInitializedElt(I), Usage))
  1707. return false;
  1708. }
  1709. if (!Value.hasArrayFiller())
  1710. return true;
  1711. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1712. Usage);
  1713. }
  1714. if (Value.isUnion() && Value.getUnionField()) {
  1715. return CheckConstantExpression(Info, DiagLoc,
  1716. Value.getUnionField()->getType(),
  1717. Value.getUnionValue(), Usage);
  1718. }
  1719. if (Value.isStruct()) {
  1720. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1721. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1722. unsigned BaseIndex = 0;
  1723. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1724. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1725. Value.getStructBase(BaseIndex), Usage))
  1726. return false;
  1727. ++BaseIndex;
  1728. }
  1729. }
  1730. for (const auto *I : RD->fields()) {
  1731. if (I->isUnnamedBitfield())
  1732. continue;
  1733. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1734. Value.getStructField(I->getFieldIndex()),
  1735. Usage))
  1736. return false;
  1737. }
  1738. }
  1739. if (Value.isLValue()) {
  1740. LValue LVal;
  1741. LVal.setFrom(Info.Ctx, Value);
  1742. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1743. }
  1744. if (Value.isMemberPointer())
  1745. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1746. // Everything else is fine.
  1747. return true;
  1748. }
  1749. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1750. // A null base expression indicates a null pointer. These are always
  1751. // evaluatable, and they are false unless the offset is zero.
  1752. if (!Value.getLValueBase()) {
  1753. Result = !Value.getLValueOffset().isZero();
  1754. return true;
  1755. }
  1756. // We have a non-null base. These are generally known to be true, but if it's
  1757. // a weak declaration it can be null at runtime.
  1758. Result = true;
  1759. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1760. return !Decl || !Decl->isWeak();
  1761. }
  1762. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1763. switch (Val.getKind()) {
  1764. case APValue::Uninitialized:
  1765. return false;
  1766. case APValue::Int:
  1767. Result = Val.getInt().getBoolValue();
  1768. return true;
  1769. case APValue::Float:
  1770. Result = !Val.getFloat().isZero();
  1771. return true;
  1772. case APValue::ComplexInt:
  1773. Result = Val.getComplexIntReal().getBoolValue() ||
  1774. Val.getComplexIntImag().getBoolValue();
  1775. return true;
  1776. case APValue::ComplexFloat:
  1777. Result = !Val.getComplexFloatReal().isZero() ||
  1778. !Val.getComplexFloatImag().isZero();
  1779. return true;
  1780. case APValue::LValue:
  1781. return EvalPointerValueAsBool(Val, Result);
  1782. case APValue::MemberPointer:
  1783. Result = Val.getMemberPointerDecl();
  1784. return true;
  1785. case APValue::Vector:
  1786. case APValue::Array:
  1787. case APValue::Struct:
  1788. case APValue::Union:
  1789. case APValue::AddrLabelDiff:
  1790. return false;
  1791. }
  1792. llvm_unreachable("unknown APValue kind");
  1793. }
  1794. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1795. EvalInfo &Info) {
  1796. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1797. APValue Val;
  1798. if (!Evaluate(Val, Info, E))
  1799. return false;
  1800. return HandleConversionToBool(Val, Result);
  1801. }
  1802. template<typename T>
  1803. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1804. const T &SrcValue, QualType DestType) {
  1805. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1806. << SrcValue << DestType;
  1807. return Info.noteUndefinedBehavior();
  1808. }
  1809. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1810. QualType SrcType, const APFloat &Value,
  1811. QualType DestType, APSInt &Result) {
  1812. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1813. // Determine whether we are converting to unsigned or signed.
  1814. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1815. Result = APSInt(DestWidth, !DestSigned);
  1816. bool ignored;
  1817. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1818. & APFloat::opInvalidOp)
  1819. return HandleOverflow(Info, E, Value, DestType);
  1820. return true;
  1821. }
  1822. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1823. QualType SrcType, QualType DestType,
  1824. APFloat &Result) {
  1825. APFloat Value = Result;
  1826. bool ignored;
  1827. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1828. APFloat::rmNearestTiesToEven, &ignored)
  1829. & APFloat::opOverflow)
  1830. return HandleOverflow(Info, E, Value, DestType);
  1831. return true;
  1832. }
  1833. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1834. QualType DestType, QualType SrcType,
  1835. const APSInt &Value) {
  1836. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1837. APSInt Result = Value;
  1838. // Figure out if this is a truncate, extend or noop cast.
  1839. // If the input is signed, do a sign extend, noop, or truncate.
  1840. Result = Result.extOrTrunc(DestWidth);
  1841. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1842. return Result;
  1843. }
  1844. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1845. QualType SrcType, const APSInt &Value,
  1846. QualType DestType, APFloat &Result) {
  1847. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1848. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1849. APFloat::rmNearestTiesToEven)
  1850. & APFloat::opOverflow)
  1851. return HandleOverflow(Info, E, Value, DestType);
  1852. return true;
  1853. }
  1854. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1855. APValue &Value, const FieldDecl *FD) {
  1856. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1857. if (!Value.isInt()) {
  1858. // Trying to store a pointer-cast-to-integer into a bitfield.
  1859. // FIXME: In this case, we should provide the diagnostic for casting
  1860. // a pointer to an integer.
  1861. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1862. Info.FFDiag(E);
  1863. return false;
  1864. }
  1865. APSInt &Int = Value.getInt();
  1866. unsigned OldBitWidth = Int.getBitWidth();
  1867. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1868. if (NewBitWidth < OldBitWidth)
  1869. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1870. return true;
  1871. }
  1872. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1873. llvm::APInt &Res) {
  1874. APValue SVal;
  1875. if (!Evaluate(SVal, Info, E))
  1876. return false;
  1877. if (SVal.isInt()) {
  1878. Res = SVal.getInt();
  1879. return true;
  1880. }
  1881. if (SVal.isFloat()) {
  1882. Res = SVal.getFloat().bitcastToAPInt();
  1883. return true;
  1884. }
  1885. if (SVal.isVector()) {
  1886. QualType VecTy = E->getType();
  1887. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1888. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1889. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1890. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1891. Res = llvm::APInt::getNullValue(VecSize);
  1892. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1893. APValue &Elt = SVal.getVectorElt(i);
  1894. llvm::APInt EltAsInt;
  1895. if (Elt.isInt()) {
  1896. EltAsInt = Elt.getInt();
  1897. } else if (Elt.isFloat()) {
  1898. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1899. } else {
  1900. // Don't try to handle vectors of anything other than int or float
  1901. // (not sure if it's possible to hit this case).
  1902. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1903. return false;
  1904. }
  1905. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1906. if (BigEndian)
  1907. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1908. else
  1909. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1910. }
  1911. return true;
  1912. }
  1913. // Give up if the input isn't an int, float, or vector. For example, we
  1914. // reject "(v4i16)(intptr_t)&a".
  1915. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1916. return false;
  1917. }
  1918. /// Perform the given integer operation, which is known to need at most BitWidth
  1919. /// bits, and check for overflow in the original type (if that type was not an
  1920. /// unsigned type).
  1921. template<typename Operation>
  1922. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1923. const APSInt &LHS, const APSInt &RHS,
  1924. unsigned BitWidth, Operation Op,
  1925. APSInt &Result) {
  1926. if (LHS.isUnsigned()) {
  1927. Result = Op(LHS, RHS);
  1928. return true;
  1929. }
  1930. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1931. Result = Value.trunc(LHS.getBitWidth());
  1932. if (Result.extend(BitWidth) != Value) {
  1933. if (Info.checkingForOverflow())
  1934. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1935. diag::warn_integer_constant_overflow)
  1936. << Result.toString(10) << E->getType();
  1937. else
  1938. return HandleOverflow(Info, E, Value, E->getType());
  1939. }
  1940. return true;
  1941. }
  1942. /// Perform the given binary integer operation.
  1943. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1944. BinaryOperatorKind Opcode, APSInt RHS,
  1945. APSInt &Result) {
  1946. switch (Opcode) {
  1947. default:
  1948. Info.FFDiag(E);
  1949. return false;
  1950. case BO_Mul:
  1951. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1952. std::multiplies<APSInt>(), Result);
  1953. case BO_Add:
  1954. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1955. std::plus<APSInt>(), Result);
  1956. case BO_Sub:
  1957. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1958. std::minus<APSInt>(), Result);
  1959. case BO_And: Result = LHS & RHS; return true;
  1960. case BO_Xor: Result = LHS ^ RHS; return true;
  1961. case BO_Or: Result = LHS | RHS; return true;
  1962. case BO_Div:
  1963. case BO_Rem:
  1964. if (RHS == 0) {
  1965. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  1966. return false;
  1967. }
  1968. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1969. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  1970. // this operation and gives the two's complement result.
  1971. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1972. LHS.isSigned() && LHS.isMinSignedValue())
  1973. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  1974. E->getType());
  1975. return true;
  1976. case BO_Shl: {
  1977. if (Info.getLangOpts().OpenCL)
  1978. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1979. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1980. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1981. RHS.isUnsigned());
  1982. else if (RHS.isSigned() && RHS.isNegative()) {
  1983. // During constant-folding, a negative shift is an opposite shift. Such
  1984. // a shift is not a constant expression.
  1985. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1986. RHS = -RHS;
  1987. goto shift_right;
  1988. }
  1989. shift_left:
  1990. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  1991. // the shifted type.
  1992. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1993. if (SA != RHS) {
  1994. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1995. << RHS << E->getType() << LHS.getBitWidth();
  1996. } else if (LHS.isSigned()) {
  1997. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  1998. // operand, and must not overflow the corresponding unsigned type.
  1999. if (LHS.isNegative())
  2000. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2001. else if (LHS.countLeadingZeros() < SA)
  2002. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2003. }
  2004. Result = LHS << SA;
  2005. return true;
  2006. }
  2007. case BO_Shr: {
  2008. if (Info.getLangOpts().OpenCL)
  2009. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2010. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2011. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2012. RHS.isUnsigned());
  2013. else if (RHS.isSigned() && RHS.isNegative()) {
  2014. // During constant-folding, a negative shift is an opposite shift. Such a
  2015. // shift is not a constant expression.
  2016. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2017. RHS = -RHS;
  2018. goto shift_left;
  2019. }
  2020. shift_right:
  2021. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2022. // shifted type.
  2023. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2024. if (SA != RHS)
  2025. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2026. << RHS << E->getType() << LHS.getBitWidth();
  2027. Result = LHS >> SA;
  2028. return true;
  2029. }
  2030. case BO_LT: Result = LHS < RHS; return true;
  2031. case BO_GT: Result = LHS > RHS; return true;
  2032. case BO_LE: Result = LHS <= RHS; return true;
  2033. case BO_GE: Result = LHS >= RHS; return true;
  2034. case BO_EQ: Result = LHS == RHS; return true;
  2035. case BO_NE: Result = LHS != RHS; return true;
  2036. case BO_Cmp:
  2037. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2038. }
  2039. }
  2040. /// Perform the given binary floating-point operation, in-place, on LHS.
  2041. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2042. APFloat &LHS, BinaryOperatorKind Opcode,
  2043. const APFloat &RHS) {
  2044. switch (Opcode) {
  2045. default:
  2046. Info.FFDiag(E);
  2047. return false;
  2048. case BO_Mul:
  2049. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2050. break;
  2051. case BO_Add:
  2052. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2053. break;
  2054. case BO_Sub:
  2055. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2056. break;
  2057. case BO_Div:
  2058. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2059. break;
  2060. }
  2061. if (LHS.isInfinity() || LHS.isNaN()) {
  2062. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2063. return Info.noteUndefinedBehavior();
  2064. }
  2065. return true;
  2066. }
  2067. /// Cast an lvalue referring to a base subobject to a derived class, by
  2068. /// truncating the lvalue's path to the given length.
  2069. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2070. const RecordDecl *TruncatedType,
  2071. unsigned TruncatedElements) {
  2072. SubobjectDesignator &D = Result.Designator;
  2073. // Check we actually point to a derived class object.
  2074. if (TruncatedElements == D.Entries.size())
  2075. return true;
  2076. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2077. "not casting to a derived class");
  2078. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2079. return false;
  2080. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2081. const RecordDecl *RD = TruncatedType;
  2082. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2083. if (RD->isInvalidDecl()) return false;
  2084. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2085. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2086. if (isVirtualBaseClass(D.Entries[I]))
  2087. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2088. else
  2089. Result.Offset -= Layout.getBaseClassOffset(Base);
  2090. RD = Base;
  2091. }
  2092. D.Entries.resize(TruncatedElements);
  2093. return true;
  2094. }
  2095. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2096. const CXXRecordDecl *Derived,
  2097. const CXXRecordDecl *Base,
  2098. const ASTRecordLayout *RL = nullptr) {
  2099. if (!RL) {
  2100. if (Derived->isInvalidDecl()) return false;
  2101. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2102. }
  2103. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2104. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2105. return true;
  2106. }
  2107. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2108. const CXXRecordDecl *DerivedDecl,
  2109. const CXXBaseSpecifier *Base) {
  2110. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2111. if (!Base->isVirtual())
  2112. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2113. SubobjectDesignator &D = Obj.Designator;
  2114. if (D.Invalid)
  2115. return false;
  2116. // Extract most-derived object and corresponding type.
  2117. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2118. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2119. return false;
  2120. // Find the virtual base class.
  2121. if (DerivedDecl->isInvalidDecl()) return false;
  2122. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2123. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2124. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2125. return true;
  2126. }
  2127. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2128. QualType Type, LValue &Result) {
  2129. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2130. PathE = E->path_end();
  2131. PathI != PathE; ++PathI) {
  2132. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2133. *PathI))
  2134. return false;
  2135. Type = (*PathI)->getType();
  2136. }
  2137. return true;
  2138. }
  2139. /// Update LVal to refer to the given field, which must be a member of the type
  2140. /// currently described by LVal.
  2141. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2142. const FieldDecl *FD,
  2143. const ASTRecordLayout *RL = nullptr) {
  2144. if (!RL) {
  2145. if (FD->getParent()->isInvalidDecl()) return false;
  2146. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2147. }
  2148. unsigned I = FD->getFieldIndex();
  2149. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2150. LVal.addDecl(Info, E, FD);
  2151. return true;
  2152. }
  2153. /// Update LVal to refer to the given indirect field.
  2154. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2155. LValue &LVal,
  2156. const IndirectFieldDecl *IFD) {
  2157. for (const auto *C : IFD->chain())
  2158. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2159. return false;
  2160. return true;
  2161. }
  2162. /// Get the size of the given type in char units.
  2163. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2164. QualType Type, CharUnits &Size) {
  2165. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2166. // extension.
  2167. if (Type->isVoidType() || Type->isFunctionType()) {
  2168. Size = CharUnits::One();
  2169. return true;
  2170. }
  2171. if (Type->isDependentType()) {
  2172. Info.FFDiag(Loc);
  2173. return false;
  2174. }
  2175. if (!Type->isConstantSizeType()) {
  2176. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2177. // FIXME: Better diagnostic.
  2178. Info.FFDiag(Loc);
  2179. return false;
  2180. }
  2181. Size = Info.Ctx.getTypeSizeInChars(Type);
  2182. return true;
  2183. }
  2184. /// Update a pointer value to model pointer arithmetic.
  2185. /// \param Info - Information about the ongoing evaluation.
  2186. /// \param E - The expression being evaluated, for diagnostic purposes.
  2187. /// \param LVal - The pointer value to be updated.
  2188. /// \param EltTy - The pointee type represented by LVal.
  2189. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2190. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2191. LValue &LVal, QualType EltTy,
  2192. APSInt Adjustment) {
  2193. CharUnits SizeOfPointee;
  2194. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2195. return false;
  2196. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2197. return true;
  2198. }
  2199. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2200. LValue &LVal, QualType EltTy,
  2201. int64_t Adjustment) {
  2202. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2203. APSInt::get(Adjustment));
  2204. }
  2205. /// Update an lvalue to refer to a component of a complex number.
  2206. /// \param Info - Information about the ongoing evaluation.
  2207. /// \param LVal - The lvalue to be updated.
  2208. /// \param EltTy - The complex number's component type.
  2209. /// \param Imag - False for the real component, true for the imaginary.
  2210. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2211. LValue &LVal, QualType EltTy,
  2212. bool Imag) {
  2213. if (Imag) {
  2214. CharUnits SizeOfComponent;
  2215. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2216. return false;
  2217. LVal.Offset += SizeOfComponent;
  2218. }
  2219. LVal.addComplex(Info, E, EltTy, Imag);
  2220. return true;
  2221. }
  2222. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2223. QualType Type, const LValue &LVal,
  2224. APValue &RVal);
  2225. /// Try to evaluate the initializer for a variable declaration.
  2226. ///
  2227. /// \param Info Information about the ongoing evaluation.
  2228. /// \param E An expression to be used when printing diagnostics.
  2229. /// \param VD The variable whose initializer should be obtained.
  2230. /// \param Frame The frame in which the variable was created. Must be null
  2231. /// if this variable is not local to the evaluation.
  2232. /// \param Result Filled in with a pointer to the value of the variable.
  2233. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2234. const VarDecl *VD, CallStackFrame *Frame,
  2235. APValue *&Result, const LValue *LVal) {
  2236. // If this is a parameter to an active constexpr function call, perform
  2237. // argument substitution.
  2238. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2239. // Assume arguments of a potential constant expression are unknown
  2240. // constant expressions.
  2241. if (Info.checkingPotentialConstantExpression())
  2242. return false;
  2243. if (!Frame || !Frame->Arguments) {
  2244. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2245. return false;
  2246. }
  2247. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2248. return true;
  2249. }
  2250. // If this is a local variable, dig out its value.
  2251. if (Frame) {
  2252. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2253. : Frame->getCurrentTemporary(VD);
  2254. if (!Result) {
  2255. // Assume variables referenced within a lambda's call operator that were
  2256. // not declared within the call operator are captures and during checking
  2257. // of a potential constant expression, assume they are unknown constant
  2258. // expressions.
  2259. assert(isLambdaCallOperator(Frame->Callee) &&
  2260. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2261. "missing value for local variable");
  2262. if (Info.checkingPotentialConstantExpression())
  2263. return false;
  2264. // FIXME: implement capture evaluation during constant expr evaluation.
  2265. Info.FFDiag(E->getBeginLoc(),
  2266. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2267. << "captures not currently allowed";
  2268. return false;
  2269. }
  2270. return true;
  2271. }
  2272. // Dig out the initializer, and use the declaration which it's attached to.
  2273. const Expr *Init = VD->getAnyInitializer(VD);
  2274. if (!Init || Init->isValueDependent()) {
  2275. // If we're checking a potential constant expression, the variable could be
  2276. // initialized later.
  2277. if (!Info.checkingPotentialConstantExpression())
  2278. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2279. return false;
  2280. }
  2281. // If we're currently evaluating the initializer of this declaration, use that
  2282. // in-flight value.
  2283. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2284. Result = Info.EvaluatingDeclValue;
  2285. return true;
  2286. }
  2287. // Never evaluate the initializer of a weak variable. We can't be sure that
  2288. // this is the definition which will be used.
  2289. if (VD->isWeak()) {
  2290. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2291. return false;
  2292. }
  2293. // Check that we can fold the initializer. In C++, we will have already done
  2294. // this in the cases where it matters for conformance.
  2295. SmallVector<PartialDiagnosticAt, 8> Notes;
  2296. if (!VD->evaluateValue(Notes)) {
  2297. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2298. Notes.size() + 1) << VD;
  2299. Info.Note(VD->getLocation(), diag::note_declared_at);
  2300. Info.addNotes(Notes);
  2301. return false;
  2302. } else if (!VD->checkInitIsICE()) {
  2303. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2304. Notes.size() + 1) << VD;
  2305. Info.Note(VD->getLocation(), diag::note_declared_at);
  2306. Info.addNotes(Notes);
  2307. }
  2308. Result = VD->getEvaluatedValue();
  2309. return true;
  2310. }
  2311. static bool IsConstNonVolatile(QualType T) {
  2312. Qualifiers Quals = T.getQualifiers();
  2313. return Quals.hasConst() && !Quals.hasVolatile();
  2314. }
  2315. /// Get the base index of the given base class within an APValue representing
  2316. /// the given derived class.
  2317. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2318. const CXXRecordDecl *Base) {
  2319. Base = Base->getCanonicalDecl();
  2320. unsigned Index = 0;
  2321. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2322. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2323. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2324. return Index;
  2325. }
  2326. llvm_unreachable("base class missing from derived class's bases list");
  2327. }
  2328. /// Extract the value of a character from a string literal.
  2329. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2330. uint64_t Index) {
  2331. // FIXME: Support MakeStringConstant
  2332. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2333. std::string Str;
  2334. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2335. assert(Index <= Str.size() && "Index too large");
  2336. return APSInt::getUnsigned(Str.c_str()[Index]);
  2337. }
  2338. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2339. Lit = PE->getFunctionName();
  2340. const StringLiteral *S = cast<StringLiteral>(Lit);
  2341. const ConstantArrayType *CAT =
  2342. Info.Ctx.getAsConstantArrayType(S->getType());
  2343. assert(CAT && "string literal isn't an array");
  2344. QualType CharType = CAT->getElementType();
  2345. assert(CharType->isIntegerType() && "unexpected character type");
  2346. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2347. CharType->isUnsignedIntegerType());
  2348. if (Index < S->getLength())
  2349. Value = S->getCodeUnit(Index);
  2350. return Value;
  2351. }
  2352. // Expand a string literal into an array of characters.
  2353. static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
  2354. APValue &Result) {
  2355. const StringLiteral *S = cast<StringLiteral>(Lit);
  2356. const ConstantArrayType *CAT =
  2357. Info.Ctx.getAsConstantArrayType(S->getType());
  2358. assert(CAT && "string literal isn't an array");
  2359. QualType CharType = CAT->getElementType();
  2360. assert(CharType->isIntegerType() && "unexpected character type");
  2361. unsigned Elts = CAT->getSize().getZExtValue();
  2362. Result = APValue(APValue::UninitArray(),
  2363. std::min(S->getLength(), Elts), Elts);
  2364. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2365. CharType->isUnsignedIntegerType());
  2366. if (Result.hasArrayFiller())
  2367. Result.getArrayFiller() = APValue(Value);
  2368. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2369. Value = S->getCodeUnit(I);
  2370. Result.getArrayInitializedElt(I) = APValue(Value);
  2371. }
  2372. }
  2373. // Expand an array so that it has more than Index filled elements.
  2374. static void expandArray(APValue &Array, unsigned Index) {
  2375. unsigned Size = Array.getArraySize();
  2376. assert(Index < Size);
  2377. // Always at least double the number of elements for which we store a value.
  2378. unsigned OldElts = Array.getArrayInitializedElts();
  2379. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2380. NewElts = std::min(Size, std::max(NewElts, 8u));
  2381. // Copy the data across.
  2382. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2383. for (unsigned I = 0; I != OldElts; ++I)
  2384. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2385. for (unsigned I = OldElts; I != NewElts; ++I)
  2386. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2387. if (NewValue.hasArrayFiller())
  2388. NewValue.getArrayFiller() = Array.getArrayFiller();
  2389. Array.swap(NewValue);
  2390. }
  2391. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2392. /// conversion. If it's of class type, we may assume that the copy operation
  2393. /// is trivial. Note that this is never true for a union type with fields
  2394. /// (because the copy always "reads" the active member) and always true for
  2395. /// a non-class type.
  2396. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2397. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2398. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2399. return true;
  2400. if (RD->isEmpty())
  2401. return false;
  2402. for (auto *Field : RD->fields())
  2403. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2404. return true;
  2405. for (auto &BaseSpec : RD->bases())
  2406. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2407. return true;
  2408. return false;
  2409. }
  2410. /// Diagnose an attempt to read from any unreadable field within the specified
  2411. /// type, which might be a class type.
  2412. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2413. QualType T) {
  2414. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2415. if (!RD)
  2416. return false;
  2417. if (!RD->hasMutableFields())
  2418. return false;
  2419. for (auto *Field : RD->fields()) {
  2420. // If we're actually going to read this field in some way, then it can't
  2421. // be mutable. If we're in a union, then assigning to a mutable field
  2422. // (even an empty one) can change the active member, so that's not OK.
  2423. // FIXME: Add core issue number for the union case.
  2424. if (Field->isMutable() &&
  2425. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2426. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2427. Info.Note(Field->getLocation(), diag::note_declared_at);
  2428. return true;
  2429. }
  2430. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2431. return true;
  2432. }
  2433. for (auto &BaseSpec : RD->bases())
  2434. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2435. return true;
  2436. // All mutable fields were empty, and thus not actually read.
  2437. return false;
  2438. }
  2439. /// Kinds of access we can perform on an object, for diagnostics.
  2440. enum AccessKinds {
  2441. AK_Read,
  2442. AK_Assign,
  2443. AK_Increment,
  2444. AK_Decrement
  2445. };
  2446. namespace {
  2447. /// A handle to a complete object (an object that is not a subobject of
  2448. /// another object).
  2449. struct CompleteObject {
  2450. /// The value of the complete object.
  2451. APValue *Value;
  2452. /// The type of the complete object.
  2453. QualType Type;
  2454. bool LifetimeStartedInEvaluation;
  2455. CompleteObject() : Value(nullptr) {}
  2456. CompleteObject(APValue *Value, QualType Type,
  2457. bool LifetimeStartedInEvaluation)
  2458. : Value(Value), Type(Type),
  2459. LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
  2460. assert(Value && "missing value for complete object");
  2461. }
  2462. explicit operator bool() const { return Value; }
  2463. };
  2464. } // end anonymous namespace
  2465. /// Find the designated sub-object of an rvalue.
  2466. template<typename SubobjectHandler>
  2467. typename SubobjectHandler::result_type
  2468. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2469. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2470. if (Sub.Invalid)
  2471. // A diagnostic will have already been produced.
  2472. return handler.failed();
  2473. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2474. if (Info.getLangOpts().CPlusPlus11)
  2475. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2476. ? diag::note_constexpr_access_past_end
  2477. : diag::note_constexpr_access_unsized_array)
  2478. << handler.AccessKind;
  2479. else
  2480. Info.FFDiag(E);
  2481. return handler.failed();
  2482. }
  2483. APValue *O = Obj.Value;
  2484. QualType ObjType = Obj.Type;
  2485. const FieldDecl *LastField = nullptr;
  2486. const bool MayReadMutableMembers =
  2487. Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
  2488. // Walk the designator's path to find the subobject.
  2489. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2490. if (O->isUninit()) {
  2491. if (!Info.checkingPotentialConstantExpression())
  2492. Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
  2493. return handler.failed();
  2494. }
  2495. if (I == N) {
  2496. // If we are reading an object of class type, there may still be more
  2497. // things we need to check: if there are any mutable subobjects, we
  2498. // cannot perform this read. (This only happens when performing a trivial
  2499. // copy or assignment.)
  2500. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2501. !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
  2502. return handler.failed();
  2503. if (!handler.found(*O, ObjType))
  2504. return false;
  2505. // If we modified a bit-field, truncate it to the right width.
  2506. if (handler.AccessKind != AK_Read &&
  2507. LastField && LastField->isBitField() &&
  2508. !truncateBitfieldValue(Info, E, *O, LastField))
  2509. return false;
  2510. return true;
  2511. }
  2512. LastField = nullptr;
  2513. if (ObjType->isArrayType()) {
  2514. // Next subobject is an array element.
  2515. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2516. assert(CAT && "vla in literal type?");
  2517. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2518. if (CAT->getSize().ule(Index)) {
  2519. // Note, it should not be possible to form a pointer with a valid
  2520. // designator which points more than one past the end of the array.
  2521. if (Info.getLangOpts().CPlusPlus11)
  2522. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2523. << handler.AccessKind;
  2524. else
  2525. Info.FFDiag(E);
  2526. return handler.failed();
  2527. }
  2528. ObjType = CAT->getElementType();
  2529. // An array object is represented as either an Array APValue or as an
  2530. // LValue which refers to a string literal.
  2531. if (O->isLValue()) {
  2532. assert(I == N - 1 && "extracting subobject of character?");
  2533. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  2534. if (handler.AccessKind != AK_Read)
  2535. expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
  2536. *O);
  2537. else
  2538. return handler.foundString(*O, ObjType, Index);
  2539. }
  2540. if (O->getArrayInitializedElts() > Index)
  2541. O = &O->getArrayInitializedElt(Index);
  2542. else if (handler.AccessKind != AK_Read) {
  2543. expandArray(*O, Index);
  2544. O = &O->getArrayInitializedElt(Index);
  2545. } else
  2546. O = &O->getArrayFiller();
  2547. } else if (ObjType->isAnyComplexType()) {
  2548. // Next subobject is a complex number.
  2549. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2550. if (Index > 1) {
  2551. if (Info.getLangOpts().CPlusPlus11)
  2552. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2553. << handler.AccessKind;
  2554. else
  2555. Info.FFDiag(E);
  2556. return handler.failed();
  2557. }
  2558. bool WasConstQualified = ObjType.isConstQualified();
  2559. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2560. if (WasConstQualified)
  2561. ObjType.addConst();
  2562. assert(I == N - 1 && "extracting subobject of scalar?");
  2563. if (O->isComplexInt()) {
  2564. return handler.found(Index ? O->getComplexIntImag()
  2565. : O->getComplexIntReal(), ObjType);
  2566. } else {
  2567. assert(O->isComplexFloat());
  2568. return handler.found(Index ? O->getComplexFloatImag()
  2569. : O->getComplexFloatReal(), ObjType);
  2570. }
  2571. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2572. // In C++14 onwards, it is permitted to read a mutable member whose
  2573. // lifetime began within the evaluation.
  2574. // FIXME: Should we also allow this in C++11?
  2575. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2576. !MayReadMutableMembers) {
  2577. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2578. << Field;
  2579. Info.Note(Field->getLocation(), diag::note_declared_at);
  2580. return handler.failed();
  2581. }
  2582. // Next subobject is a class, struct or union field.
  2583. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2584. if (RD->isUnion()) {
  2585. const FieldDecl *UnionField = O->getUnionField();
  2586. if (!UnionField ||
  2587. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2588. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2589. << handler.AccessKind << Field << !UnionField << UnionField;
  2590. return handler.failed();
  2591. }
  2592. O = &O->getUnionValue();
  2593. } else
  2594. O = &O->getStructField(Field->getFieldIndex());
  2595. bool WasConstQualified = ObjType.isConstQualified();
  2596. ObjType = Field->getType();
  2597. if (WasConstQualified && !Field->isMutable())
  2598. ObjType.addConst();
  2599. if (ObjType.isVolatileQualified()) {
  2600. if (Info.getLangOpts().CPlusPlus) {
  2601. // FIXME: Include a description of the path to the volatile subobject.
  2602. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2603. << handler.AccessKind << 2 << Field;
  2604. Info.Note(Field->getLocation(), diag::note_declared_at);
  2605. } else {
  2606. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2607. }
  2608. return handler.failed();
  2609. }
  2610. LastField = Field;
  2611. } else {
  2612. // Next subobject is a base class.
  2613. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2614. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2615. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2616. bool WasConstQualified = ObjType.isConstQualified();
  2617. ObjType = Info.Ctx.getRecordType(Base);
  2618. if (WasConstQualified)
  2619. ObjType.addConst();
  2620. }
  2621. }
  2622. }
  2623. namespace {
  2624. struct ExtractSubobjectHandler {
  2625. EvalInfo &Info;
  2626. APValue &Result;
  2627. static const AccessKinds AccessKind = AK_Read;
  2628. typedef bool result_type;
  2629. bool failed() { return false; }
  2630. bool found(APValue &Subobj, QualType SubobjType) {
  2631. Result = Subobj;
  2632. return true;
  2633. }
  2634. bool found(APSInt &Value, QualType SubobjType) {
  2635. Result = APValue(Value);
  2636. return true;
  2637. }
  2638. bool found(APFloat &Value, QualType SubobjType) {
  2639. Result = APValue(Value);
  2640. return true;
  2641. }
  2642. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2643. Result = APValue(extractStringLiteralCharacter(
  2644. Info, Subobj.getLValueBase().get<const Expr *>(), Character));
  2645. return true;
  2646. }
  2647. };
  2648. } // end anonymous namespace
  2649. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2650. /// Extract the designated sub-object of an rvalue.
  2651. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2652. const CompleteObject &Obj,
  2653. const SubobjectDesignator &Sub,
  2654. APValue &Result) {
  2655. ExtractSubobjectHandler Handler = { Info, Result };
  2656. return findSubobject(Info, E, Obj, Sub, Handler);
  2657. }
  2658. namespace {
  2659. struct ModifySubobjectHandler {
  2660. EvalInfo &Info;
  2661. APValue &NewVal;
  2662. const Expr *E;
  2663. typedef bool result_type;
  2664. static const AccessKinds AccessKind = AK_Assign;
  2665. bool checkConst(QualType QT) {
  2666. // Assigning to a const object has undefined behavior.
  2667. if (QT.isConstQualified()) {
  2668. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2669. return false;
  2670. }
  2671. return true;
  2672. }
  2673. bool failed() { return false; }
  2674. bool found(APValue &Subobj, QualType SubobjType) {
  2675. if (!checkConst(SubobjType))
  2676. return false;
  2677. // We've been given ownership of NewVal, so just swap it in.
  2678. Subobj.swap(NewVal);
  2679. return true;
  2680. }
  2681. bool found(APSInt &Value, QualType SubobjType) {
  2682. if (!checkConst(SubobjType))
  2683. return false;
  2684. if (!NewVal.isInt()) {
  2685. // Maybe trying to write a cast pointer value into a complex?
  2686. Info.FFDiag(E);
  2687. return false;
  2688. }
  2689. Value = NewVal.getInt();
  2690. return true;
  2691. }
  2692. bool found(APFloat &Value, QualType SubobjType) {
  2693. if (!checkConst(SubobjType))
  2694. return false;
  2695. Value = NewVal.getFloat();
  2696. return true;
  2697. }
  2698. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2699. llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
  2700. }
  2701. };
  2702. } // end anonymous namespace
  2703. const AccessKinds ModifySubobjectHandler::AccessKind;
  2704. /// Update the designated sub-object of an rvalue to the given value.
  2705. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2706. const CompleteObject &Obj,
  2707. const SubobjectDesignator &Sub,
  2708. APValue &NewVal) {
  2709. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2710. return findSubobject(Info, E, Obj, Sub, Handler);
  2711. }
  2712. /// Find the position where two subobject designators diverge, or equivalently
  2713. /// the length of the common initial subsequence.
  2714. static unsigned FindDesignatorMismatch(QualType ObjType,
  2715. const SubobjectDesignator &A,
  2716. const SubobjectDesignator &B,
  2717. bool &WasArrayIndex) {
  2718. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2719. for (/**/; I != N; ++I) {
  2720. if (!ObjType.isNull() &&
  2721. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2722. // Next subobject is an array element.
  2723. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  2724. WasArrayIndex = true;
  2725. return I;
  2726. }
  2727. if (ObjType->isAnyComplexType())
  2728. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2729. else
  2730. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2731. } else {
  2732. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  2733. WasArrayIndex = false;
  2734. return I;
  2735. }
  2736. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2737. // Next subobject is a field.
  2738. ObjType = FD->getType();
  2739. else
  2740. // Next subobject is a base class.
  2741. ObjType = QualType();
  2742. }
  2743. }
  2744. WasArrayIndex = false;
  2745. return I;
  2746. }
  2747. /// Determine whether the given subobject designators refer to elements of the
  2748. /// same array object.
  2749. static bool AreElementsOfSameArray(QualType ObjType,
  2750. const SubobjectDesignator &A,
  2751. const SubobjectDesignator &B) {
  2752. if (A.Entries.size() != B.Entries.size())
  2753. return false;
  2754. bool IsArray = A.MostDerivedIsArrayElement;
  2755. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2756. // A is a subobject of the array element.
  2757. return false;
  2758. // If A (and B) designates an array element, the last entry will be the array
  2759. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2760. // of length 1' case, and the entire path must match.
  2761. bool WasArrayIndex;
  2762. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2763. return CommonLength >= A.Entries.size() - IsArray;
  2764. }
  2765. /// Find the complete object to which an LValue refers.
  2766. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2767. AccessKinds AK, const LValue &LVal,
  2768. QualType LValType) {
  2769. if (!LVal.Base) {
  2770. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2771. return CompleteObject();
  2772. }
  2773. CallStackFrame *Frame = nullptr;
  2774. if (LVal.getLValueCallIndex()) {
  2775. Frame = Info.getCallFrame(LVal.getLValueCallIndex());
  2776. if (!Frame) {
  2777. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2778. << AK << LVal.Base.is<const ValueDecl*>();
  2779. NoteLValueLocation(Info, LVal.Base);
  2780. return CompleteObject();
  2781. }
  2782. }
  2783. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2784. // is not a constant expression (even if the object is non-volatile). We also
  2785. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2786. // semantics.
  2787. if (LValType.isVolatileQualified()) {
  2788. if (Info.getLangOpts().CPlusPlus)
  2789. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2790. << AK << LValType;
  2791. else
  2792. Info.FFDiag(E);
  2793. return CompleteObject();
  2794. }
  2795. // Compute value storage location and type of base object.
  2796. APValue *BaseVal = nullptr;
  2797. QualType BaseType = getType(LVal.Base);
  2798. bool LifetimeStartedInEvaluation = Frame;
  2799. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2800. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2801. // In C++11, constexpr, non-volatile variables initialized with constant
  2802. // expressions are constant expressions too. Inside constexpr functions,
  2803. // parameters are constant expressions even if they're non-const.
  2804. // In C++1y, objects local to a constant expression (those with a Frame) are
  2805. // both readable and writable inside constant expressions.
  2806. // In C, such things can also be folded, although they are not ICEs.
  2807. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2808. if (VD) {
  2809. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2810. VD = VDef;
  2811. }
  2812. if (!VD || VD->isInvalidDecl()) {
  2813. Info.FFDiag(E);
  2814. return CompleteObject();
  2815. }
  2816. // Accesses of volatile-qualified objects are not allowed.
  2817. if (BaseType.isVolatileQualified()) {
  2818. if (Info.getLangOpts().CPlusPlus) {
  2819. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2820. << AK << 1 << VD;
  2821. Info.Note(VD->getLocation(), diag::note_declared_at);
  2822. } else {
  2823. Info.FFDiag(E);
  2824. }
  2825. return CompleteObject();
  2826. }
  2827. // Unless we're looking at a local variable or argument in a constexpr call,
  2828. // the variable we're reading must be const.
  2829. if (!Frame) {
  2830. if (Info.getLangOpts().CPlusPlus14 &&
  2831. VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
  2832. // OK, we can read and modify an object if we're in the process of
  2833. // evaluating its initializer, because its lifetime began in this
  2834. // evaluation.
  2835. } else if (AK != AK_Read) {
  2836. // All the remaining cases only permit reading.
  2837. Info.FFDiag(E, diag::note_constexpr_modify_global);
  2838. return CompleteObject();
  2839. } else if (VD->isConstexpr()) {
  2840. // OK, we can read this variable.
  2841. } else if (BaseType->isIntegralOrEnumerationType()) {
  2842. // In OpenCL if a variable is in constant address space it is a const value.
  2843. if (!(BaseType.isConstQualified() ||
  2844. (Info.getLangOpts().OpenCL &&
  2845. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  2846. if (Info.getLangOpts().CPlusPlus) {
  2847. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2848. Info.Note(VD->getLocation(), diag::note_declared_at);
  2849. } else {
  2850. Info.FFDiag(E);
  2851. }
  2852. return CompleteObject();
  2853. }
  2854. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2855. // We support folding of const floating-point types, in order to make
  2856. // static const data members of such types (supported as an extension)
  2857. // more useful.
  2858. if (Info.getLangOpts().CPlusPlus11) {
  2859. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2860. Info.Note(VD->getLocation(), diag::note_declared_at);
  2861. } else {
  2862. Info.CCEDiag(E);
  2863. }
  2864. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  2865. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  2866. // Keep evaluating to see what we can do.
  2867. } else {
  2868. // FIXME: Allow folding of values of any literal type in all languages.
  2869. if (Info.checkingPotentialConstantExpression() &&
  2870. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  2871. // The definition of this variable could be constexpr. We can't
  2872. // access it right now, but may be able to in future.
  2873. } else if (Info.getLangOpts().CPlusPlus11) {
  2874. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2875. Info.Note(VD->getLocation(), diag::note_declared_at);
  2876. } else {
  2877. Info.FFDiag(E);
  2878. }
  2879. return CompleteObject();
  2880. }
  2881. }
  2882. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  2883. return CompleteObject();
  2884. } else {
  2885. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2886. if (!Frame) {
  2887. if (const MaterializeTemporaryExpr *MTE =
  2888. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  2889. assert(MTE->getStorageDuration() == SD_Static &&
  2890. "should have a frame for a non-global materialized temporary");
  2891. // Per C++1y [expr.const]p2:
  2892. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2893. // - a [...] glvalue of integral or enumeration type that refers to
  2894. // a non-volatile const object [...]
  2895. // [...]
  2896. // - a [...] glvalue of literal type that refers to a non-volatile
  2897. // object whose lifetime began within the evaluation of e.
  2898. //
  2899. // C++11 misses the 'began within the evaluation of e' check and
  2900. // instead allows all temporaries, including things like:
  2901. // int &&r = 1;
  2902. // int x = ++r;
  2903. // constexpr int k = r;
  2904. // Therefore we use the C++14 rules in C++11 too.
  2905. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2906. const ValueDecl *ED = MTE->getExtendingDecl();
  2907. if (!(BaseType.isConstQualified() &&
  2908. BaseType->isIntegralOrEnumerationType()) &&
  2909. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2910. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2911. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2912. return CompleteObject();
  2913. }
  2914. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2915. assert(BaseVal && "got reference to unevaluated temporary");
  2916. LifetimeStartedInEvaluation = true;
  2917. } else {
  2918. Info.FFDiag(E);
  2919. return CompleteObject();
  2920. }
  2921. } else {
  2922. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  2923. assert(BaseVal && "missing value for temporary");
  2924. }
  2925. // Volatile temporary objects cannot be accessed in constant expressions.
  2926. if (BaseType.isVolatileQualified()) {
  2927. if (Info.getLangOpts().CPlusPlus) {
  2928. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2929. << AK << 0;
  2930. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  2931. } else {
  2932. Info.FFDiag(E);
  2933. }
  2934. return CompleteObject();
  2935. }
  2936. }
  2937. // During the construction of an object, it is not yet 'const'.
  2938. // FIXME: This doesn't do quite the right thing for const subobjects of the
  2939. // object under construction.
  2940. if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
  2941. LVal.getLValueCallIndex(),
  2942. LVal.getLValueVersion())) {
  2943. BaseType = Info.Ctx.getCanonicalType(BaseType);
  2944. BaseType.removeLocalConst();
  2945. LifetimeStartedInEvaluation = true;
  2946. }
  2947. // In C++14, we can't safely access any mutable state when we might be
  2948. // evaluating after an unmodeled side effect.
  2949. //
  2950. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2951. // to be read here (but take care with 'mutable' fields).
  2952. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  2953. Info.EvalStatus.HasSideEffects) ||
  2954. (AK != AK_Read && Info.IsSpeculativelyEvaluating))
  2955. return CompleteObject();
  2956. return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
  2957. }
  2958. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2959. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2960. /// glvalue referred to by an entity of reference type.
  2961. ///
  2962. /// \param Info - Information about the ongoing evaluation.
  2963. /// \param Conv - The expression for which we are performing the conversion.
  2964. /// Used for diagnostics.
  2965. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  2966. /// case of a non-class type).
  2967. /// \param LVal - The glvalue on which we are attempting to perform this action.
  2968. /// \param RVal - The produced value will be placed here.
  2969. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2970. QualType Type,
  2971. const LValue &LVal, APValue &RVal) {
  2972. if (LVal.Designator.Invalid)
  2973. return false;
  2974. // Check for special cases where there is no existing APValue to look at.
  2975. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2976. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  2977. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  2978. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  2979. // initializer until now for such expressions. Such an expression can't be
  2980. // an ICE in C, so this only matters for fold.
  2981. if (Type.isVolatileQualified()) {
  2982. Info.FFDiag(Conv);
  2983. return false;
  2984. }
  2985. APValue Lit;
  2986. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  2987. return false;
  2988. CompleteObject LitObj(&Lit, Base->getType(), false);
  2989. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  2990. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  2991. // We represent a string literal array as an lvalue pointing at the
  2992. // corresponding expression, rather than building an array of chars.
  2993. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  2994. APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  2995. CompleteObject StrObj(&Str, Base->getType(), false);
  2996. return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
  2997. }
  2998. }
  2999. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  3000. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  3001. }
  3002. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3003. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3004. QualType LValType, APValue &Val) {
  3005. if (LVal.Designator.Invalid)
  3006. return false;
  3007. if (!Info.getLangOpts().CPlusPlus14) {
  3008. Info.FFDiag(E);
  3009. return false;
  3010. }
  3011. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3012. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3013. }
  3014. namespace {
  3015. struct CompoundAssignSubobjectHandler {
  3016. EvalInfo &Info;
  3017. const Expr *E;
  3018. QualType PromotedLHSType;
  3019. BinaryOperatorKind Opcode;
  3020. const APValue &RHS;
  3021. static const AccessKinds AccessKind = AK_Assign;
  3022. typedef bool result_type;
  3023. bool checkConst(QualType QT) {
  3024. // Assigning to a const object has undefined behavior.
  3025. if (QT.isConstQualified()) {
  3026. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3027. return false;
  3028. }
  3029. return true;
  3030. }
  3031. bool failed() { return false; }
  3032. bool found(APValue &Subobj, QualType SubobjType) {
  3033. switch (Subobj.getKind()) {
  3034. case APValue::Int:
  3035. return found(Subobj.getInt(), SubobjType);
  3036. case APValue::Float:
  3037. return found(Subobj.getFloat(), SubobjType);
  3038. case APValue::ComplexInt:
  3039. case APValue::ComplexFloat:
  3040. // FIXME: Implement complex compound assignment.
  3041. Info.FFDiag(E);
  3042. return false;
  3043. case APValue::LValue:
  3044. return foundPointer(Subobj, SubobjType);
  3045. default:
  3046. // FIXME: can this happen?
  3047. Info.FFDiag(E);
  3048. return false;
  3049. }
  3050. }
  3051. bool found(APSInt &Value, QualType SubobjType) {
  3052. if (!checkConst(SubobjType))
  3053. return false;
  3054. if (!SubobjType->isIntegerType() || !RHS.isInt()) {
  3055. // We don't support compound assignment on integer-cast-to-pointer
  3056. // values.
  3057. Info.FFDiag(E);
  3058. return false;
  3059. }
  3060. APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
  3061. SubobjType, Value);
  3062. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3063. return false;
  3064. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3065. return true;
  3066. }
  3067. bool found(APFloat &Value, QualType SubobjType) {
  3068. return checkConst(SubobjType) &&
  3069. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3070. Value) &&
  3071. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3072. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3073. }
  3074. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3075. if (!checkConst(SubobjType))
  3076. return false;
  3077. QualType PointeeType;
  3078. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3079. PointeeType = PT->getPointeeType();
  3080. if (PointeeType.isNull() || !RHS.isInt() ||
  3081. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3082. Info.FFDiag(E);
  3083. return false;
  3084. }
  3085. APSInt Offset = RHS.getInt();
  3086. if (Opcode == BO_Sub)
  3087. negateAsSigned(Offset);
  3088. LValue LVal;
  3089. LVal.setFrom(Info.Ctx, Subobj);
  3090. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3091. return false;
  3092. LVal.moveInto(Subobj);
  3093. return true;
  3094. }
  3095. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3096. llvm_unreachable("shouldn't encounter string elements here");
  3097. }
  3098. };
  3099. } // end anonymous namespace
  3100. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3101. /// Perform a compound assignment of LVal <op>= RVal.
  3102. static bool handleCompoundAssignment(
  3103. EvalInfo &Info, const Expr *E,
  3104. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3105. BinaryOperatorKind Opcode, const APValue &RVal) {
  3106. if (LVal.Designator.Invalid)
  3107. return false;
  3108. if (!Info.getLangOpts().CPlusPlus14) {
  3109. Info.FFDiag(E);
  3110. return false;
  3111. }
  3112. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3113. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3114. RVal };
  3115. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3116. }
  3117. namespace {
  3118. struct IncDecSubobjectHandler {
  3119. EvalInfo &Info;
  3120. const UnaryOperator *E;
  3121. AccessKinds AccessKind;
  3122. APValue *Old;
  3123. typedef bool result_type;
  3124. bool checkConst(QualType QT) {
  3125. // Assigning to a const object has undefined behavior.
  3126. if (QT.isConstQualified()) {
  3127. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3128. return false;
  3129. }
  3130. return true;
  3131. }
  3132. bool failed() { return false; }
  3133. bool found(APValue &Subobj, QualType SubobjType) {
  3134. // Stash the old value. Also clear Old, so we don't clobber it later
  3135. // if we're post-incrementing a complex.
  3136. if (Old) {
  3137. *Old = Subobj;
  3138. Old = nullptr;
  3139. }
  3140. switch (Subobj.getKind()) {
  3141. case APValue::Int:
  3142. return found(Subobj.getInt(), SubobjType);
  3143. case APValue::Float:
  3144. return found(Subobj.getFloat(), SubobjType);
  3145. case APValue::ComplexInt:
  3146. return found(Subobj.getComplexIntReal(),
  3147. SubobjType->castAs<ComplexType>()->getElementType()
  3148. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3149. case APValue::ComplexFloat:
  3150. return found(Subobj.getComplexFloatReal(),
  3151. SubobjType->castAs<ComplexType>()->getElementType()
  3152. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3153. case APValue::LValue:
  3154. return foundPointer(Subobj, SubobjType);
  3155. default:
  3156. // FIXME: can this happen?
  3157. Info.FFDiag(E);
  3158. return false;
  3159. }
  3160. }
  3161. bool found(APSInt &Value, QualType SubobjType) {
  3162. if (!checkConst(SubobjType))
  3163. return false;
  3164. if (!SubobjType->isIntegerType()) {
  3165. // We don't support increment / decrement on integer-cast-to-pointer
  3166. // values.
  3167. Info.FFDiag(E);
  3168. return false;
  3169. }
  3170. if (Old) *Old = APValue(Value);
  3171. // bool arithmetic promotes to int, and the conversion back to bool
  3172. // doesn't reduce mod 2^n, so special-case it.
  3173. if (SubobjType->isBooleanType()) {
  3174. if (AccessKind == AK_Increment)
  3175. Value = 1;
  3176. else
  3177. Value = !Value;
  3178. return true;
  3179. }
  3180. bool WasNegative = Value.isNegative();
  3181. if (AccessKind == AK_Increment) {
  3182. ++Value;
  3183. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3184. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3185. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3186. }
  3187. } else {
  3188. --Value;
  3189. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3190. unsigned BitWidth = Value.getBitWidth();
  3191. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3192. ActualValue.setBit(BitWidth);
  3193. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3194. }
  3195. }
  3196. return true;
  3197. }
  3198. bool found(APFloat &Value, QualType SubobjType) {
  3199. if (!checkConst(SubobjType))
  3200. return false;
  3201. if (Old) *Old = APValue(Value);
  3202. APFloat One(Value.getSemantics(), 1);
  3203. if (AccessKind == AK_Increment)
  3204. Value.add(One, APFloat::rmNearestTiesToEven);
  3205. else
  3206. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3207. return true;
  3208. }
  3209. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3210. if (!checkConst(SubobjType))
  3211. return false;
  3212. QualType PointeeType;
  3213. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3214. PointeeType = PT->getPointeeType();
  3215. else {
  3216. Info.FFDiag(E);
  3217. return false;
  3218. }
  3219. LValue LVal;
  3220. LVal.setFrom(Info.Ctx, Subobj);
  3221. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3222. AccessKind == AK_Increment ? 1 : -1))
  3223. return false;
  3224. LVal.moveInto(Subobj);
  3225. return true;
  3226. }
  3227. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3228. llvm_unreachable("shouldn't encounter string elements here");
  3229. }
  3230. };
  3231. } // end anonymous namespace
  3232. /// Perform an increment or decrement on LVal.
  3233. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3234. QualType LValType, bool IsIncrement, APValue *Old) {
  3235. if (LVal.Designator.Invalid)
  3236. return false;
  3237. if (!Info.getLangOpts().CPlusPlus14) {
  3238. Info.FFDiag(E);
  3239. return false;
  3240. }
  3241. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3242. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3243. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3244. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3245. }
  3246. /// Build an lvalue for the object argument of a member function call.
  3247. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3248. LValue &This) {
  3249. if (Object->getType()->isPointerType())
  3250. return EvaluatePointer(Object, This, Info);
  3251. if (Object->isGLValue())
  3252. return EvaluateLValue(Object, This, Info);
  3253. if (Object->getType()->isLiteralType(Info.Ctx))
  3254. return EvaluateTemporary(Object, This, Info);
  3255. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3256. return false;
  3257. }
  3258. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3259. /// lvalue referring to the result.
  3260. ///
  3261. /// \param Info - Information about the ongoing evaluation.
  3262. /// \param LV - An lvalue referring to the base of the member pointer.
  3263. /// \param RHS - The member pointer expression.
  3264. /// \param IncludeMember - Specifies whether the member itself is included in
  3265. /// the resulting LValue subobject designator. This is not possible when
  3266. /// creating a bound member function.
  3267. /// \return The field or method declaration to which the member pointer refers,
  3268. /// or 0 if evaluation fails.
  3269. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3270. QualType LVType,
  3271. LValue &LV,
  3272. const Expr *RHS,
  3273. bool IncludeMember = true) {
  3274. MemberPtr MemPtr;
  3275. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3276. return nullptr;
  3277. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3278. // member value, the behavior is undefined.
  3279. if (!MemPtr.getDecl()) {
  3280. // FIXME: Specific diagnostic.
  3281. Info.FFDiag(RHS);
  3282. return nullptr;
  3283. }
  3284. if (MemPtr.isDerivedMember()) {
  3285. // This is a member of some derived class. Truncate LV appropriately.
  3286. // The end of the derived-to-base path for the base object must match the
  3287. // derived-to-base path for the member pointer.
  3288. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3289. LV.Designator.Entries.size()) {
  3290. Info.FFDiag(RHS);
  3291. return nullptr;
  3292. }
  3293. unsigned PathLengthToMember =
  3294. LV.Designator.Entries.size() - MemPtr.Path.size();
  3295. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3296. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3297. LV.Designator.Entries[PathLengthToMember + I]);
  3298. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3299. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3300. Info.FFDiag(RHS);
  3301. return nullptr;
  3302. }
  3303. }
  3304. // Truncate the lvalue to the appropriate derived class.
  3305. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3306. PathLengthToMember))
  3307. return nullptr;
  3308. } else if (!MemPtr.Path.empty()) {
  3309. // Extend the LValue path with the member pointer's path.
  3310. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3311. MemPtr.Path.size() + IncludeMember);
  3312. // Walk down to the appropriate base class.
  3313. if (const PointerType *PT = LVType->getAs<PointerType>())
  3314. LVType = PT->getPointeeType();
  3315. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3316. assert(RD && "member pointer access on non-class-type expression");
  3317. // The first class in the path is that of the lvalue.
  3318. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3319. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3320. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3321. return nullptr;
  3322. RD = Base;
  3323. }
  3324. // Finally cast to the class containing the member.
  3325. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3326. MemPtr.getContainingRecord()))
  3327. return nullptr;
  3328. }
  3329. // Add the member. Note that we cannot build bound member functions here.
  3330. if (IncludeMember) {
  3331. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3332. if (!HandleLValueMember(Info, RHS, LV, FD))
  3333. return nullptr;
  3334. } else if (const IndirectFieldDecl *IFD =
  3335. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3336. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3337. return nullptr;
  3338. } else {
  3339. llvm_unreachable("can't construct reference to bound member function");
  3340. }
  3341. }
  3342. return MemPtr.getDecl();
  3343. }
  3344. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3345. const BinaryOperator *BO,
  3346. LValue &LV,
  3347. bool IncludeMember = true) {
  3348. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3349. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3350. if (Info.noteFailure()) {
  3351. MemberPtr MemPtr;
  3352. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3353. }
  3354. return nullptr;
  3355. }
  3356. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3357. BO->getRHS(), IncludeMember);
  3358. }
  3359. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3360. /// the provided lvalue, which currently refers to the base object.
  3361. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3362. LValue &Result) {
  3363. SubobjectDesignator &D = Result.Designator;
  3364. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3365. return false;
  3366. QualType TargetQT = E->getType();
  3367. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3368. TargetQT = PT->getPointeeType();
  3369. // Check this cast lands within the final derived-to-base subobject path.
  3370. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3371. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3372. << D.MostDerivedType << TargetQT;
  3373. return false;
  3374. }
  3375. // Check the type of the final cast. We don't need to check the path,
  3376. // since a cast can only be formed if the path is unique.
  3377. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3378. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3379. const CXXRecordDecl *FinalType;
  3380. if (NewEntriesSize == D.MostDerivedPathLength)
  3381. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3382. else
  3383. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3384. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3385. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3386. << D.MostDerivedType << TargetQT;
  3387. return false;
  3388. }
  3389. // Truncate the lvalue to the appropriate derived class.
  3390. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3391. }
  3392. namespace {
  3393. enum EvalStmtResult {
  3394. /// Evaluation failed.
  3395. ESR_Failed,
  3396. /// Hit a 'return' statement.
  3397. ESR_Returned,
  3398. /// Evaluation succeeded.
  3399. ESR_Succeeded,
  3400. /// Hit a 'continue' statement.
  3401. ESR_Continue,
  3402. /// Hit a 'break' statement.
  3403. ESR_Break,
  3404. /// Still scanning for 'case' or 'default' statement.
  3405. ESR_CaseNotFound
  3406. };
  3407. }
  3408. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3409. // We don't need to evaluate the initializer for a static local.
  3410. if (!VD->hasLocalStorage())
  3411. return true;
  3412. LValue Result;
  3413. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3414. const Expr *InitE = VD->getInit();
  3415. if (!InitE) {
  3416. Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
  3417. << false << VD->getType();
  3418. Val = APValue();
  3419. return false;
  3420. }
  3421. if (InitE->isValueDependent())
  3422. return false;
  3423. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3424. // Wipe out any partially-computed value, to allow tracking that this
  3425. // evaluation failed.
  3426. Val = APValue();
  3427. return false;
  3428. }
  3429. return true;
  3430. }
  3431. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3432. bool OK = true;
  3433. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3434. OK &= EvaluateVarDecl(Info, VD);
  3435. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3436. for (auto *BD : DD->bindings())
  3437. if (auto *VD = BD->getHoldingVar())
  3438. OK &= EvaluateDecl(Info, VD);
  3439. return OK;
  3440. }
  3441. /// Evaluate a condition (either a variable declaration or an expression).
  3442. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3443. const Expr *Cond, bool &Result) {
  3444. FullExpressionRAII Scope(Info);
  3445. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3446. return false;
  3447. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3448. }
  3449. namespace {
  3450. /// A location where the result (returned value) of evaluating a
  3451. /// statement should be stored.
  3452. struct StmtResult {
  3453. /// The APValue that should be filled in with the returned value.
  3454. APValue &Value;
  3455. /// The location containing the result, if any (used to support RVO).
  3456. const LValue *Slot;
  3457. };
  3458. struct TempVersionRAII {
  3459. CallStackFrame &Frame;
  3460. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3461. Frame.pushTempVersion();
  3462. }
  3463. ~TempVersionRAII() {
  3464. Frame.popTempVersion();
  3465. }
  3466. };
  3467. }
  3468. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3469. const Stmt *S,
  3470. const SwitchCase *SC = nullptr);
  3471. /// Evaluate the body of a loop, and translate the result as appropriate.
  3472. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3473. const Stmt *Body,
  3474. const SwitchCase *Case = nullptr) {
  3475. BlockScopeRAII Scope(Info);
  3476. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3477. case ESR_Break:
  3478. return ESR_Succeeded;
  3479. case ESR_Succeeded:
  3480. case ESR_Continue:
  3481. return ESR_Continue;
  3482. case ESR_Failed:
  3483. case ESR_Returned:
  3484. case ESR_CaseNotFound:
  3485. return ESR;
  3486. }
  3487. llvm_unreachable("Invalid EvalStmtResult!");
  3488. }
  3489. /// Evaluate a switch statement.
  3490. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3491. const SwitchStmt *SS) {
  3492. BlockScopeRAII Scope(Info);
  3493. // Evaluate the switch condition.
  3494. APSInt Value;
  3495. {
  3496. FullExpressionRAII Scope(Info);
  3497. if (const Stmt *Init = SS->getInit()) {
  3498. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3499. if (ESR != ESR_Succeeded)
  3500. return ESR;
  3501. }
  3502. if (SS->getConditionVariable() &&
  3503. !EvaluateDecl(Info, SS->getConditionVariable()))
  3504. return ESR_Failed;
  3505. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3506. return ESR_Failed;
  3507. }
  3508. // Find the switch case corresponding to the value of the condition.
  3509. // FIXME: Cache this lookup.
  3510. const SwitchCase *Found = nullptr;
  3511. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3512. SC = SC->getNextSwitchCase()) {
  3513. if (isa<DefaultStmt>(SC)) {
  3514. Found = SC;
  3515. continue;
  3516. }
  3517. const CaseStmt *CS = cast<CaseStmt>(SC);
  3518. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3519. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3520. : LHS;
  3521. if (LHS <= Value && Value <= RHS) {
  3522. Found = SC;
  3523. break;
  3524. }
  3525. }
  3526. if (!Found)
  3527. return ESR_Succeeded;
  3528. // Search the switch body for the switch case and evaluate it from there.
  3529. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3530. case ESR_Break:
  3531. return ESR_Succeeded;
  3532. case ESR_Succeeded:
  3533. case ESR_Continue:
  3534. case ESR_Failed:
  3535. case ESR_Returned:
  3536. return ESR;
  3537. case ESR_CaseNotFound:
  3538. // This can only happen if the switch case is nested within a statement
  3539. // expression. We have no intention of supporting that.
  3540. Info.FFDiag(Found->getBeginLoc(),
  3541. diag::note_constexpr_stmt_expr_unsupported);
  3542. return ESR_Failed;
  3543. }
  3544. llvm_unreachable("Invalid EvalStmtResult!");
  3545. }
  3546. // Evaluate a statement.
  3547. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3548. const Stmt *S, const SwitchCase *Case) {
  3549. if (!Info.nextStep(S))
  3550. return ESR_Failed;
  3551. // If we're hunting down a 'case' or 'default' label, recurse through
  3552. // substatements until we hit the label.
  3553. if (Case) {
  3554. // FIXME: We don't start the lifetime of objects whose initialization we
  3555. // jump over. However, such objects must be of class type with a trivial
  3556. // default constructor that initialize all subobjects, so must be empty,
  3557. // so this almost never matters.
  3558. switch (S->getStmtClass()) {
  3559. case Stmt::CompoundStmtClass:
  3560. // FIXME: Precompute which substatement of a compound statement we
  3561. // would jump to, and go straight there rather than performing a
  3562. // linear scan each time.
  3563. case Stmt::LabelStmtClass:
  3564. case Stmt::AttributedStmtClass:
  3565. case Stmt::DoStmtClass:
  3566. break;
  3567. case Stmt::CaseStmtClass:
  3568. case Stmt::DefaultStmtClass:
  3569. if (Case == S)
  3570. Case = nullptr;
  3571. break;
  3572. case Stmt::IfStmtClass: {
  3573. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3574. // straight there rather than scanning both sides.
  3575. const IfStmt *IS = cast<IfStmt>(S);
  3576. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3577. // preceded by our switch label.
  3578. BlockScopeRAII Scope(Info);
  3579. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3580. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3581. return ESR;
  3582. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3583. }
  3584. case Stmt::WhileStmtClass: {
  3585. EvalStmtResult ESR =
  3586. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3587. if (ESR != ESR_Continue)
  3588. return ESR;
  3589. break;
  3590. }
  3591. case Stmt::ForStmtClass: {
  3592. const ForStmt *FS = cast<ForStmt>(S);
  3593. EvalStmtResult ESR =
  3594. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3595. if (ESR != ESR_Continue)
  3596. return ESR;
  3597. if (FS->getInc()) {
  3598. FullExpressionRAII IncScope(Info);
  3599. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3600. return ESR_Failed;
  3601. }
  3602. break;
  3603. }
  3604. case Stmt::DeclStmtClass:
  3605. // FIXME: If the variable has initialization that can't be jumped over,
  3606. // bail out of any immediately-surrounding compound-statement too.
  3607. default:
  3608. return ESR_CaseNotFound;
  3609. }
  3610. }
  3611. switch (S->getStmtClass()) {
  3612. default:
  3613. if (const Expr *E = dyn_cast<Expr>(S)) {
  3614. // Don't bother evaluating beyond an expression-statement which couldn't
  3615. // be evaluated.
  3616. FullExpressionRAII Scope(Info);
  3617. if (!EvaluateIgnoredValue(Info, E))
  3618. return ESR_Failed;
  3619. return ESR_Succeeded;
  3620. }
  3621. Info.FFDiag(S->getBeginLoc());
  3622. return ESR_Failed;
  3623. case Stmt::NullStmtClass:
  3624. return ESR_Succeeded;
  3625. case Stmt::DeclStmtClass: {
  3626. const DeclStmt *DS = cast<DeclStmt>(S);
  3627. for (const auto *DclIt : DS->decls()) {
  3628. // Each declaration initialization is its own full-expression.
  3629. // FIXME: This isn't quite right; if we're performing aggregate
  3630. // initialization, each braced subexpression is its own full-expression.
  3631. FullExpressionRAII Scope(Info);
  3632. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3633. return ESR_Failed;
  3634. }
  3635. return ESR_Succeeded;
  3636. }
  3637. case Stmt::ReturnStmtClass: {
  3638. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3639. FullExpressionRAII Scope(Info);
  3640. if (RetExpr &&
  3641. !(Result.Slot
  3642. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3643. : Evaluate(Result.Value, Info, RetExpr)))
  3644. return ESR_Failed;
  3645. return ESR_Returned;
  3646. }
  3647. case Stmt::CompoundStmtClass: {
  3648. BlockScopeRAII Scope(Info);
  3649. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3650. for (const auto *BI : CS->body()) {
  3651. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3652. if (ESR == ESR_Succeeded)
  3653. Case = nullptr;
  3654. else if (ESR != ESR_CaseNotFound)
  3655. return ESR;
  3656. }
  3657. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3658. }
  3659. case Stmt::IfStmtClass: {
  3660. const IfStmt *IS = cast<IfStmt>(S);
  3661. // Evaluate the condition, as either a var decl or as an expression.
  3662. BlockScopeRAII Scope(Info);
  3663. if (const Stmt *Init = IS->getInit()) {
  3664. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3665. if (ESR != ESR_Succeeded)
  3666. return ESR;
  3667. }
  3668. bool Cond;
  3669. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3670. return ESR_Failed;
  3671. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3672. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3673. if (ESR != ESR_Succeeded)
  3674. return ESR;
  3675. }
  3676. return ESR_Succeeded;
  3677. }
  3678. case Stmt::WhileStmtClass: {
  3679. const WhileStmt *WS = cast<WhileStmt>(S);
  3680. while (true) {
  3681. BlockScopeRAII Scope(Info);
  3682. bool Continue;
  3683. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3684. Continue))
  3685. return ESR_Failed;
  3686. if (!Continue)
  3687. break;
  3688. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3689. if (ESR != ESR_Continue)
  3690. return ESR;
  3691. }
  3692. return ESR_Succeeded;
  3693. }
  3694. case Stmt::DoStmtClass: {
  3695. const DoStmt *DS = cast<DoStmt>(S);
  3696. bool Continue;
  3697. do {
  3698. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3699. if (ESR != ESR_Continue)
  3700. return ESR;
  3701. Case = nullptr;
  3702. FullExpressionRAII CondScope(Info);
  3703. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3704. return ESR_Failed;
  3705. } while (Continue);
  3706. return ESR_Succeeded;
  3707. }
  3708. case Stmt::ForStmtClass: {
  3709. const ForStmt *FS = cast<ForStmt>(S);
  3710. BlockScopeRAII Scope(Info);
  3711. if (FS->getInit()) {
  3712. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3713. if (ESR != ESR_Succeeded)
  3714. return ESR;
  3715. }
  3716. while (true) {
  3717. BlockScopeRAII Scope(Info);
  3718. bool Continue = true;
  3719. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3720. FS->getCond(), Continue))
  3721. return ESR_Failed;
  3722. if (!Continue)
  3723. break;
  3724. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3725. if (ESR != ESR_Continue)
  3726. return ESR;
  3727. if (FS->getInc()) {
  3728. FullExpressionRAII IncScope(Info);
  3729. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3730. return ESR_Failed;
  3731. }
  3732. }
  3733. return ESR_Succeeded;
  3734. }
  3735. case Stmt::CXXForRangeStmtClass: {
  3736. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3737. BlockScopeRAII Scope(Info);
  3738. // Evaluate the init-statement if present.
  3739. if (FS->getInit()) {
  3740. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3741. if (ESR != ESR_Succeeded)
  3742. return ESR;
  3743. }
  3744. // Initialize the __range variable.
  3745. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3746. if (ESR != ESR_Succeeded)
  3747. return ESR;
  3748. // Create the __begin and __end iterators.
  3749. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3750. if (ESR != ESR_Succeeded)
  3751. return ESR;
  3752. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3753. if (ESR != ESR_Succeeded)
  3754. return ESR;
  3755. while (true) {
  3756. // Condition: __begin != __end.
  3757. {
  3758. bool Continue = true;
  3759. FullExpressionRAII CondExpr(Info);
  3760. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3761. return ESR_Failed;
  3762. if (!Continue)
  3763. break;
  3764. }
  3765. // User's variable declaration, initialized by *__begin.
  3766. BlockScopeRAII InnerScope(Info);
  3767. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3768. if (ESR != ESR_Succeeded)
  3769. return ESR;
  3770. // Loop body.
  3771. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3772. if (ESR != ESR_Continue)
  3773. return ESR;
  3774. // Increment: ++__begin
  3775. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3776. return ESR_Failed;
  3777. }
  3778. return ESR_Succeeded;
  3779. }
  3780. case Stmt::SwitchStmtClass:
  3781. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3782. case Stmt::ContinueStmtClass:
  3783. return ESR_Continue;
  3784. case Stmt::BreakStmtClass:
  3785. return ESR_Break;
  3786. case Stmt::LabelStmtClass:
  3787. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3788. case Stmt::AttributedStmtClass:
  3789. // As a general principle, C++11 attributes can be ignored without
  3790. // any semantic impact.
  3791. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3792. Case);
  3793. case Stmt::CaseStmtClass:
  3794. case Stmt::DefaultStmtClass:
  3795. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3796. }
  3797. }
  3798. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3799. /// default constructor. If so, we'll fold it whether or not it's marked as
  3800. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3801. /// so we need special handling.
  3802. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3803. const CXXConstructorDecl *CD,
  3804. bool IsValueInitialization) {
  3805. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3806. return false;
  3807. // Value-initialization does not call a trivial default constructor, so such a
  3808. // call is a core constant expression whether or not the constructor is
  3809. // constexpr.
  3810. if (!CD->isConstexpr() && !IsValueInitialization) {
  3811. if (Info.getLangOpts().CPlusPlus11) {
  3812. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3813. // we should be much more explicit about why it's not constexpr.
  3814. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3815. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3816. Info.Note(CD->getLocation(), diag::note_declared_at);
  3817. } else {
  3818. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3819. }
  3820. }
  3821. return true;
  3822. }
  3823. /// CheckConstexprFunction - Check that a function can be called in a constant
  3824. /// expression.
  3825. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3826. const FunctionDecl *Declaration,
  3827. const FunctionDecl *Definition,
  3828. const Stmt *Body) {
  3829. // Potential constant expressions can contain calls to declared, but not yet
  3830. // defined, constexpr functions.
  3831. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3832. Declaration->isConstexpr())
  3833. return false;
  3834. // Bail out if the function declaration itself is invalid. We will
  3835. // have produced a relevant diagnostic while parsing it, so just
  3836. // note the problematic sub-expression.
  3837. if (Declaration->isInvalidDecl()) {
  3838. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3839. return false;
  3840. }
  3841. // Can we evaluate this function call?
  3842. if (Definition && Definition->isConstexpr() &&
  3843. !Definition->isInvalidDecl() && Body)
  3844. return true;
  3845. if (Info.getLangOpts().CPlusPlus11) {
  3846. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3847. // If this function is not constexpr because it is an inherited
  3848. // non-constexpr constructor, diagnose that directly.
  3849. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  3850. if (CD && CD->isInheritingConstructor()) {
  3851. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  3852. if (!Inherited->isConstexpr())
  3853. DiagDecl = CD = Inherited;
  3854. }
  3855. // FIXME: If DiagDecl is an implicitly-declared special member function
  3856. // or an inheriting constructor, we should be much more explicit about why
  3857. // it's not constexpr.
  3858. if (CD && CD->isInheritingConstructor())
  3859. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  3860. << CD->getInheritedConstructor().getConstructor()->getParent();
  3861. else
  3862. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3863. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  3864. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3865. } else {
  3866. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3867. }
  3868. return false;
  3869. }
  3870. /// Determine if a class has any fields that might need to be copied by a
  3871. /// trivial copy or move operation.
  3872. static bool hasFields(const CXXRecordDecl *RD) {
  3873. if (!RD || RD->isEmpty())
  3874. return false;
  3875. for (auto *FD : RD->fields()) {
  3876. if (FD->isUnnamedBitfield())
  3877. continue;
  3878. return true;
  3879. }
  3880. for (auto &Base : RD->bases())
  3881. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  3882. return true;
  3883. return false;
  3884. }
  3885. namespace {
  3886. typedef SmallVector<APValue, 8> ArgVector;
  3887. }
  3888. /// EvaluateArgs - Evaluate the arguments to a function call.
  3889. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  3890. EvalInfo &Info) {
  3891. bool Success = true;
  3892. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  3893. I != E; ++I) {
  3894. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  3895. // If we're checking for a potential constant expression, evaluate all
  3896. // initializers even if some of them fail.
  3897. if (!Info.noteFailure())
  3898. return false;
  3899. Success = false;
  3900. }
  3901. }
  3902. return Success;
  3903. }
  3904. /// Evaluate a function call.
  3905. static bool HandleFunctionCall(SourceLocation CallLoc,
  3906. const FunctionDecl *Callee, const LValue *This,
  3907. ArrayRef<const Expr*> Args, const Stmt *Body,
  3908. EvalInfo &Info, APValue &Result,
  3909. const LValue *ResultSlot) {
  3910. ArgVector ArgValues(Args.size());
  3911. if (!EvaluateArgs(Args, ArgValues, Info))
  3912. return false;
  3913. if (!Info.CheckCallLimit(CallLoc))
  3914. return false;
  3915. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  3916. // For a trivial copy or move assignment, perform an APValue copy. This is
  3917. // essential for unions, where the operations performed by the assignment
  3918. // operator cannot be represented as statements.
  3919. //
  3920. // Skip this for non-union classes with no fields; in that case, the defaulted
  3921. // copy/move does not actually read the object.
  3922. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  3923. if (MD && MD->isDefaulted() &&
  3924. (MD->getParent()->isUnion() ||
  3925. (MD->isTrivial() && hasFields(MD->getParent())))) {
  3926. assert(This &&
  3927. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  3928. LValue RHS;
  3929. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3930. APValue RHSValue;
  3931. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3932. RHS, RHSValue))
  3933. return false;
  3934. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
  3935. RHSValue))
  3936. return false;
  3937. This->moveInto(Result);
  3938. return true;
  3939. } else if (MD && isLambdaCallOperator(MD)) {
  3940. // We're in a lambda; determine the lambda capture field maps unless we're
  3941. // just constexpr checking a lambda's call operator. constexpr checking is
  3942. // done before the captures have been added to the closure object (unless
  3943. // we're inferring constexpr-ness), so we don't have access to them in this
  3944. // case. But since we don't need the captures to constexpr check, we can
  3945. // just ignore them.
  3946. if (!Info.checkingPotentialConstantExpression())
  3947. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  3948. Frame.LambdaThisCaptureField);
  3949. }
  3950. StmtResult Ret = {Result, ResultSlot};
  3951. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  3952. if (ESR == ESR_Succeeded) {
  3953. if (Callee->getReturnType()->isVoidType())
  3954. return true;
  3955. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  3956. }
  3957. return ESR == ESR_Returned;
  3958. }
  3959. /// Evaluate a constructor call.
  3960. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  3961. APValue *ArgValues,
  3962. const CXXConstructorDecl *Definition,
  3963. EvalInfo &Info, APValue &Result) {
  3964. SourceLocation CallLoc = E->getExprLoc();
  3965. if (!Info.CheckCallLimit(CallLoc))
  3966. return false;
  3967. const CXXRecordDecl *RD = Definition->getParent();
  3968. if (RD->getNumVBases()) {
  3969. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  3970. return false;
  3971. }
  3972. EvalInfo::EvaluatingConstructorRAII EvalObj(
  3973. Info, {This.getLValueBase(),
  3974. {This.getLValueCallIndex(), This.getLValueVersion()}});
  3975. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  3976. // FIXME: Creating an APValue just to hold a nonexistent return value is
  3977. // wasteful.
  3978. APValue RetVal;
  3979. StmtResult Ret = {RetVal, nullptr};
  3980. // If it's a delegating constructor, delegate.
  3981. if (Definition->isDelegatingConstructor()) {
  3982. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  3983. {
  3984. FullExpressionRAII InitScope(Info);
  3985. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  3986. return false;
  3987. }
  3988. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  3989. }
  3990. // For a trivial copy or move constructor, perform an APValue copy. This is
  3991. // essential for unions (or classes with anonymous union members), where the
  3992. // operations performed by the constructor cannot be represented by
  3993. // ctor-initializers.
  3994. //
  3995. // Skip this for empty non-union classes; we should not perform an
  3996. // lvalue-to-rvalue conversion on them because their copy constructor does not
  3997. // actually read them.
  3998. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  3999. (Definition->getParent()->isUnion() ||
  4000. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4001. LValue RHS;
  4002. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4003. return handleLValueToRValueConversion(
  4004. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4005. RHS, Result);
  4006. }
  4007. // Reserve space for the struct members.
  4008. if (!RD->isUnion() && Result.isUninit())
  4009. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4010. std::distance(RD->field_begin(), RD->field_end()));
  4011. if (RD->isInvalidDecl()) return false;
  4012. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4013. // A scope for temporaries lifetime-extended by reference members.
  4014. BlockScopeRAII LifetimeExtendedScope(Info);
  4015. bool Success = true;
  4016. unsigned BasesSeen = 0;
  4017. #ifndef NDEBUG
  4018. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4019. #endif
  4020. for (const auto *I : Definition->inits()) {
  4021. LValue Subobject = This;
  4022. LValue SubobjectParent = This;
  4023. APValue *Value = &Result;
  4024. // Determine the subobject to initialize.
  4025. FieldDecl *FD = nullptr;
  4026. if (I->isBaseInitializer()) {
  4027. QualType BaseType(I->getBaseClass(), 0);
  4028. #ifndef NDEBUG
  4029. // Non-virtual base classes are initialized in the order in the class
  4030. // definition. We have already checked for virtual base classes.
  4031. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4032. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4033. "base class initializers not in expected order");
  4034. ++BaseIt;
  4035. #endif
  4036. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4037. BaseType->getAsCXXRecordDecl(), &Layout))
  4038. return false;
  4039. Value = &Result.getStructBase(BasesSeen++);
  4040. } else if ((FD = I->getMember())) {
  4041. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4042. return false;
  4043. if (RD->isUnion()) {
  4044. Result = APValue(FD);
  4045. Value = &Result.getUnionValue();
  4046. } else {
  4047. Value = &Result.getStructField(FD->getFieldIndex());
  4048. }
  4049. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4050. // Walk the indirect field decl's chain to find the object to initialize,
  4051. // and make sure we've initialized every step along it.
  4052. auto IndirectFieldChain = IFD->chain();
  4053. for (auto *C : IndirectFieldChain) {
  4054. FD = cast<FieldDecl>(C);
  4055. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4056. // Switch the union field if it differs. This happens if we had
  4057. // preceding zero-initialization, and we're now initializing a union
  4058. // subobject other than the first.
  4059. // FIXME: In this case, the values of the other subobjects are
  4060. // specified, since zero-initialization sets all padding bits to zero.
  4061. if (Value->isUninit() ||
  4062. (Value->isUnion() && Value->getUnionField() != FD)) {
  4063. if (CD->isUnion())
  4064. *Value = APValue(FD);
  4065. else
  4066. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4067. std::distance(CD->field_begin(), CD->field_end()));
  4068. }
  4069. // Store Subobject as its parent before updating it for the last element
  4070. // in the chain.
  4071. if (C == IndirectFieldChain.back())
  4072. SubobjectParent = Subobject;
  4073. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4074. return false;
  4075. if (CD->isUnion())
  4076. Value = &Value->getUnionValue();
  4077. else
  4078. Value = &Value->getStructField(FD->getFieldIndex());
  4079. }
  4080. } else {
  4081. llvm_unreachable("unknown base initializer kind");
  4082. }
  4083. // Need to override This for implicit field initializers as in this case
  4084. // This refers to innermost anonymous struct/union containing initializer,
  4085. // not to currently constructed class.
  4086. const Expr *Init = I->getInit();
  4087. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4088. isa<CXXDefaultInitExpr>(Init));
  4089. FullExpressionRAII InitScope(Info);
  4090. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4091. (FD && FD->isBitField() &&
  4092. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4093. // If we're checking for a potential constant expression, evaluate all
  4094. // initializers even if some of them fail.
  4095. if (!Info.noteFailure())
  4096. return false;
  4097. Success = false;
  4098. }
  4099. }
  4100. return Success &&
  4101. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4102. }
  4103. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4104. ArrayRef<const Expr*> Args,
  4105. const CXXConstructorDecl *Definition,
  4106. EvalInfo &Info, APValue &Result) {
  4107. ArgVector ArgValues(Args.size());
  4108. if (!EvaluateArgs(Args, ArgValues, Info))
  4109. return false;
  4110. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4111. Info, Result);
  4112. }
  4113. //===----------------------------------------------------------------------===//
  4114. // Generic Evaluation
  4115. //===----------------------------------------------------------------------===//
  4116. namespace {
  4117. template <class Derived>
  4118. class ExprEvaluatorBase
  4119. : public ConstStmtVisitor<Derived, bool> {
  4120. private:
  4121. Derived &getDerived() { return static_cast<Derived&>(*this); }
  4122. bool DerivedSuccess(const APValue &V, const Expr *E) {
  4123. return getDerived().Success(V, E);
  4124. }
  4125. bool DerivedZeroInitialization(const Expr *E) {
  4126. return getDerived().ZeroInitialization(E);
  4127. }
  4128. // Check whether a conditional operator with a non-constant condition is a
  4129. // potential constant expression. If neither arm is a potential constant
  4130. // expression, then the conditional operator is not either.
  4131. template<typename ConditionalOperator>
  4132. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  4133. assert(Info.checkingPotentialConstantExpression());
  4134. // Speculatively evaluate both arms.
  4135. SmallVector<PartialDiagnosticAt, 8> Diag;
  4136. {
  4137. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4138. StmtVisitorTy::Visit(E->getFalseExpr());
  4139. if (Diag.empty())
  4140. return;
  4141. }
  4142. {
  4143. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4144. Diag.clear();
  4145. StmtVisitorTy::Visit(E->getTrueExpr());
  4146. if (Diag.empty())
  4147. return;
  4148. }
  4149. Error(E, diag::note_constexpr_conditional_never_const);
  4150. }
  4151. template<typename ConditionalOperator>
  4152. bool HandleConditionalOperator(const ConditionalOperator *E) {
  4153. bool BoolResult;
  4154. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  4155. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  4156. CheckPotentialConstantConditional(E);
  4157. return false;
  4158. }
  4159. if (Info.noteFailure()) {
  4160. StmtVisitorTy::Visit(E->getTrueExpr());
  4161. StmtVisitorTy::Visit(E->getFalseExpr());
  4162. }
  4163. return false;
  4164. }
  4165. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  4166. return StmtVisitorTy::Visit(EvalExpr);
  4167. }
  4168. protected:
  4169. EvalInfo &Info;
  4170. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  4171. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  4172. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  4173. return Info.CCEDiag(E, D);
  4174. }
  4175. bool ZeroInitialization(const Expr *E) { return Error(E); }
  4176. public:
  4177. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  4178. EvalInfo &getEvalInfo() { return Info; }
  4179. /// Report an evaluation error. This should only be called when an error is
  4180. /// first discovered. When propagating an error, just return false.
  4181. bool Error(const Expr *E, diag::kind D) {
  4182. Info.FFDiag(E, D);
  4183. return false;
  4184. }
  4185. bool Error(const Expr *E) {
  4186. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  4187. }
  4188. bool VisitStmt(const Stmt *) {
  4189. llvm_unreachable("Expression evaluator should not be called on stmts");
  4190. }
  4191. bool VisitExpr(const Expr *E) {
  4192. return Error(E);
  4193. }
  4194. bool VisitParenExpr(const ParenExpr *E)
  4195. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4196. bool VisitUnaryExtension(const UnaryOperator *E)
  4197. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4198. bool VisitUnaryPlus(const UnaryOperator *E)
  4199. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4200. bool VisitChooseExpr(const ChooseExpr *E)
  4201. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  4202. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  4203. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  4204. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  4205. { return StmtVisitorTy::Visit(E->getReplacement()); }
  4206. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  4207. TempVersionRAII RAII(*Info.CurrentCall);
  4208. return StmtVisitorTy::Visit(E->getExpr());
  4209. }
  4210. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  4211. TempVersionRAII RAII(*Info.CurrentCall);
  4212. // The initializer may not have been parsed yet, or might be erroneous.
  4213. if (!E->getExpr())
  4214. return Error(E);
  4215. return StmtVisitorTy::Visit(E->getExpr());
  4216. }
  4217. // We cannot create any objects for which cleanups are required, so there is
  4218. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  4219. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  4220. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4221. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  4222. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  4223. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4224. }
  4225. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  4226. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  4227. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4228. }
  4229. bool VisitBinaryOperator(const BinaryOperator *E) {
  4230. switch (E->getOpcode()) {
  4231. default:
  4232. return Error(E);
  4233. case BO_Comma:
  4234. VisitIgnoredValue(E->getLHS());
  4235. return StmtVisitorTy::Visit(E->getRHS());
  4236. case BO_PtrMemD:
  4237. case BO_PtrMemI: {
  4238. LValue Obj;
  4239. if (!HandleMemberPointerAccess(Info, E, Obj))
  4240. return false;
  4241. APValue Result;
  4242. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  4243. return false;
  4244. return DerivedSuccess(Result, E);
  4245. }
  4246. }
  4247. }
  4248. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  4249. // Evaluate and cache the common expression. We treat it as a temporary,
  4250. // even though it's not quite the same thing.
  4251. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  4252. Info, E->getCommon()))
  4253. return false;
  4254. return HandleConditionalOperator(E);
  4255. }
  4256. bool VisitConditionalOperator(const ConditionalOperator *E) {
  4257. bool IsBcpCall = false;
  4258. // If the condition (ignoring parens) is a __builtin_constant_p call,
  4259. // the result is a constant expression if it can be folded without
  4260. // side-effects. This is an important GNU extension. See GCC PR38377
  4261. // for discussion.
  4262. if (const CallExpr *CallCE =
  4263. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  4264. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  4265. IsBcpCall = true;
  4266. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  4267. // constant expression; we can't check whether it's potentially foldable.
  4268. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  4269. return false;
  4270. FoldConstant Fold(Info, IsBcpCall);
  4271. if (!HandleConditionalOperator(E)) {
  4272. Fold.keepDiagnostics();
  4273. return false;
  4274. }
  4275. return true;
  4276. }
  4277. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  4278. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  4279. return DerivedSuccess(*Value, E);
  4280. const Expr *Source = E->getSourceExpr();
  4281. if (!Source)
  4282. return Error(E);
  4283. if (Source == E) { // sanity checking.
  4284. assert(0 && "OpaqueValueExpr recursively refers to itself");
  4285. return Error(E);
  4286. }
  4287. return StmtVisitorTy::Visit(Source);
  4288. }
  4289. bool VisitCallExpr(const CallExpr *E) {
  4290. APValue Result;
  4291. if (!handleCallExpr(E, Result, nullptr))
  4292. return false;
  4293. return DerivedSuccess(Result, E);
  4294. }
  4295. bool handleCallExpr(const CallExpr *E, APValue &Result,
  4296. const LValue *ResultSlot) {
  4297. const Expr *Callee = E->getCallee()->IgnoreParens();
  4298. QualType CalleeType = Callee->getType();
  4299. const FunctionDecl *FD = nullptr;
  4300. LValue *This = nullptr, ThisVal;
  4301. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4302. bool HasQualifier = false;
  4303. // Extract function decl and 'this' pointer from the callee.
  4304. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  4305. const ValueDecl *Member = nullptr;
  4306. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  4307. // Explicit bound member calls, such as x.f() or p->g();
  4308. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  4309. return false;
  4310. Member = ME->getMemberDecl();
  4311. This = &ThisVal;
  4312. HasQualifier = ME->hasQualifier();
  4313. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  4314. // Indirect bound member calls ('.*' or '->*').
  4315. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  4316. if (!Member) return false;
  4317. This = &ThisVal;
  4318. } else
  4319. return Error(Callee);
  4320. FD = dyn_cast<FunctionDecl>(Member);
  4321. if (!FD)
  4322. return Error(Callee);
  4323. } else if (CalleeType->isFunctionPointerType()) {
  4324. LValue Call;
  4325. if (!EvaluatePointer(Callee, Call, Info))
  4326. return false;
  4327. if (!Call.getLValueOffset().isZero())
  4328. return Error(Callee);
  4329. FD = dyn_cast_or_null<FunctionDecl>(
  4330. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  4331. if (!FD)
  4332. return Error(Callee);
  4333. // Don't call function pointers which have been cast to some other type.
  4334. // Per DR (no number yet), the caller and callee can differ in noexcept.
  4335. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  4336. CalleeType->getPointeeType(), FD->getType())) {
  4337. return Error(E);
  4338. }
  4339. // Overloaded operator calls to member functions are represented as normal
  4340. // calls with '*this' as the first argument.
  4341. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  4342. if (MD && !MD->isStatic()) {
  4343. // FIXME: When selecting an implicit conversion for an overloaded
  4344. // operator delete, we sometimes try to evaluate calls to conversion
  4345. // operators without a 'this' parameter!
  4346. if (Args.empty())
  4347. return Error(E);
  4348. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  4349. return false;
  4350. This = &ThisVal;
  4351. Args = Args.slice(1);
  4352. } else if (MD && MD->isLambdaStaticInvoker()) {
  4353. // Map the static invoker for the lambda back to the call operator.
  4354. // Conveniently, we don't have to slice out the 'this' argument (as is
  4355. // being done for the non-static case), since a static member function
  4356. // doesn't have an implicit argument passed in.
  4357. const CXXRecordDecl *ClosureClass = MD->getParent();
  4358. assert(
  4359. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  4360. "Number of captures must be zero for conversion to function-ptr");
  4361. const CXXMethodDecl *LambdaCallOp =
  4362. ClosureClass->getLambdaCallOperator();
  4363. // Set 'FD', the function that will be called below, to the call
  4364. // operator. If the closure object represents a generic lambda, find
  4365. // the corresponding specialization of the call operator.
  4366. if (ClosureClass->isGenericLambda()) {
  4367. assert(MD->isFunctionTemplateSpecialization() &&
  4368. "A generic lambda's static-invoker function must be a "
  4369. "template specialization");
  4370. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  4371. FunctionTemplateDecl *CallOpTemplate =
  4372. LambdaCallOp->getDescribedFunctionTemplate();
  4373. void *InsertPos = nullptr;
  4374. FunctionDecl *CorrespondingCallOpSpecialization =
  4375. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  4376. assert(CorrespondingCallOpSpecialization &&
  4377. "We must always have a function call operator specialization "
  4378. "that corresponds to our static invoker specialization");
  4379. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  4380. } else
  4381. FD = LambdaCallOp;
  4382. }
  4383. } else
  4384. return Error(E);
  4385. if (This && !This->checkSubobject(Info, E, CSK_This))
  4386. return false;
  4387. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  4388. // calls to such functions in constant expressions.
  4389. if (This && !HasQualifier &&
  4390. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  4391. return Error(E, diag::note_constexpr_virtual_call);
  4392. const FunctionDecl *Definition = nullptr;
  4393. Stmt *Body = FD->getBody(Definition);
  4394. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  4395. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  4396. Result, ResultSlot))
  4397. return false;
  4398. return true;
  4399. }
  4400. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4401. return StmtVisitorTy::Visit(E->getInitializer());
  4402. }
  4403. bool VisitInitListExpr(const InitListExpr *E) {
  4404. if (E->getNumInits() == 0)
  4405. return DerivedZeroInitialization(E);
  4406. if (E->getNumInits() == 1)
  4407. return StmtVisitorTy::Visit(E->getInit(0));
  4408. return Error(E);
  4409. }
  4410. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  4411. return DerivedZeroInitialization(E);
  4412. }
  4413. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  4414. return DerivedZeroInitialization(E);
  4415. }
  4416. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  4417. return DerivedZeroInitialization(E);
  4418. }
  4419. /// A member expression where the object is a prvalue is itself a prvalue.
  4420. bool VisitMemberExpr(const MemberExpr *E) {
  4421. assert(!E->isArrow() && "missing call to bound member function?");
  4422. APValue Val;
  4423. if (!Evaluate(Val, Info, E->getBase()))
  4424. return false;
  4425. QualType BaseTy = E->getBase()->getType();
  4426. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  4427. if (!FD) return Error(E);
  4428. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  4429. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4430. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4431. CompleteObject Obj(&Val, BaseTy, true);
  4432. SubobjectDesignator Designator(BaseTy);
  4433. Designator.addDeclUnchecked(FD);
  4434. APValue Result;
  4435. return extractSubobject(Info, E, Obj, Designator, Result) &&
  4436. DerivedSuccess(Result, E);
  4437. }
  4438. bool VisitCastExpr(const CastExpr *E) {
  4439. switch (E->getCastKind()) {
  4440. default:
  4441. break;
  4442. case CK_AtomicToNonAtomic: {
  4443. APValue AtomicVal;
  4444. // This does not need to be done in place even for class/array types:
  4445. // atomic-to-non-atomic conversion implies copying the object
  4446. // representation.
  4447. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  4448. return false;
  4449. return DerivedSuccess(AtomicVal, E);
  4450. }
  4451. case CK_NoOp:
  4452. case CK_UserDefinedConversion:
  4453. return StmtVisitorTy::Visit(E->getSubExpr());
  4454. case CK_LValueToRValue: {
  4455. LValue LVal;
  4456. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  4457. return false;
  4458. APValue RVal;
  4459. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  4460. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  4461. LVal, RVal))
  4462. return false;
  4463. return DerivedSuccess(RVal, E);
  4464. }
  4465. }
  4466. return Error(E);
  4467. }
  4468. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  4469. return VisitUnaryPostIncDec(UO);
  4470. }
  4471. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  4472. return VisitUnaryPostIncDec(UO);
  4473. }
  4474. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  4475. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4476. return Error(UO);
  4477. LValue LVal;
  4478. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  4479. return false;
  4480. APValue RVal;
  4481. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  4482. UO->isIncrementOp(), &RVal))
  4483. return false;
  4484. return DerivedSuccess(RVal, UO);
  4485. }
  4486. bool VisitStmtExpr(const StmtExpr *E) {
  4487. // We will have checked the full-expressions inside the statement expression
  4488. // when they were completed, and don't need to check them again now.
  4489. if (Info.checkingForOverflow())
  4490. return Error(E);
  4491. BlockScopeRAII Scope(Info);
  4492. const CompoundStmt *CS = E->getSubStmt();
  4493. if (CS->body_empty())
  4494. return true;
  4495. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  4496. BE = CS->body_end();
  4497. /**/; ++BI) {
  4498. if (BI + 1 == BE) {
  4499. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  4500. if (!FinalExpr) {
  4501. Info.FFDiag((*BI)->getBeginLoc(),
  4502. diag::note_constexpr_stmt_expr_unsupported);
  4503. return false;
  4504. }
  4505. return this->Visit(FinalExpr);
  4506. }
  4507. APValue ReturnValue;
  4508. StmtResult Result = { ReturnValue, nullptr };
  4509. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  4510. if (ESR != ESR_Succeeded) {
  4511. // FIXME: If the statement-expression terminated due to 'return',
  4512. // 'break', or 'continue', it would be nice to propagate that to
  4513. // the outer statement evaluation rather than bailing out.
  4514. if (ESR != ESR_Failed)
  4515. Info.FFDiag((*BI)->getBeginLoc(),
  4516. diag::note_constexpr_stmt_expr_unsupported);
  4517. return false;
  4518. }
  4519. }
  4520. llvm_unreachable("Return from function from the loop above.");
  4521. }
  4522. /// Visit a value which is evaluated, but whose value is ignored.
  4523. void VisitIgnoredValue(const Expr *E) {
  4524. EvaluateIgnoredValue(Info, E);
  4525. }
  4526. /// Potentially visit a MemberExpr's base expression.
  4527. void VisitIgnoredBaseExpression(const Expr *E) {
  4528. // While MSVC doesn't evaluate the base expression, it does diagnose the
  4529. // presence of side-effecting behavior.
  4530. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  4531. return;
  4532. VisitIgnoredValue(E);
  4533. }
  4534. };
  4535. } // namespace
  4536. //===----------------------------------------------------------------------===//
  4537. // Common base class for lvalue and temporary evaluation.
  4538. //===----------------------------------------------------------------------===//
  4539. namespace {
  4540. template<class Derived>
  4541. class LValueExprEvaluatorBase
  4542. : public ExprEvaluatorBase<Derived> {
  4543. protected:
  4544. LValue &Result;
  4545. bool InvalidBaseOK;
  4546. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  4547. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  4548. bool Success(APValue::LValueBase B) {
  4549. Result.set(B);
  4550. return true;
  4551. }
  4552. bool evaluatePointer(const Expr *E, LValue &Result) {
  4553. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  4554. }
  4555. public:
  4556. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  4557. : ExprEvaluatorBaseTy(Info), Result(Result),
  4558. InvalidBaseOK(InvalidBaseOK) {}
  4559. bool Success(const APValue &V, const Expr *E) {
  4560. Result.setFrom(this->Info.Ctx, V);
  4561. return true;
  4562. }
  4563. bool VisitMemberExpr(const MemberExpr *E) {
  4564. // Handle non-static data members.
  4565. QualType BaseTy;
  4566. bool EvalOK;
  4567. if (E->isArrow()) {
  4568. EvalOK = evaluatePointer(E->getBase(), Result);
  4569. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  4570. } else if (E->getBase()->isRValue()) {
  4571. assert(E->getBase()->getType()->isRecordType());
  4572. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  4573. BaseTy = E->getBase()->getType();
  4574. } else {
  4575. EvalOK = this->Visit(E->getBase());
  4576. BaseTy = E->getBase()->getType();
  4577. }
  4578. if (!EvalOK) {
  4579. if (!InvalidBaseOK)
  4580. return false;
  4581. Result.setInvalid(E);
  4582. return true;
  4583. }
  4584. const ValueDecl *MD = E->getMemberDecl();
  4585. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  4586. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4587. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4588. (void)BaseTy;
  4589. if (!HandleLValueMember(this->Info, E, Result, FD))
  4590. return false;
  4591. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  4592. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  4593. return false;
  4594. } else
  4595. return this->Error(E);
  4596. if (MD->getType()->isReferenceType()) {
  4597. APValue RefValue;
  4598. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  4599. RefValue))
  4600. return false;
  4601. return Success(RefValue, E);
  4602. }
  4603. return true;
  4604. }
  4605. bool VisitBinaryOperator(const BinaryOperator *E) {
  4606. switch (E->getOpcode()) {
  4607. default:
  4608. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4609. case BO_PtrMemD:
  4610. case BO_PtrMemI:
  4611. return HandleMemberPointerAccess(this->Info, E, Result);
  4612. }
  4613. }
  4614. bool VisitCastExpr(const CastExpr *E) {
  4615. switch (E->getCastKind()) {
  4616. default:
  4617. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4618. case CK_DerivedToBase:
  4619. case CK_UncheckedDerivedToBase:
  4620. if (!this->Visit(E->getSubExpr()))
  4621. return false;
  4622. // Now figure out the necessary offset to add to the base LV to get from
  4623. // the derived class to the base class.
  4624. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  4625. Result);
  4626. }
  4627. }
  4628. };
  4629. }
  4630. //===----------------------------------------------------------------------===//
  4631. // LValue Evaluation
  4632. //
  4633. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  4634. // function designators (in C), decl references to void objects (in C), and
  4635. // temporaries (if building with -Wno-address-of-temporary).
  4636. //
  4637. // LValue evaluation produces values comprising a base expression of one of the
  4638. // following types:
  4639. // - Declarations
  4640. // * VarDecl
  4641. // * FunctionDecl
  4642. // - Literals
  4643. // * CompoundLiteralExpr in C (and in global scope in C++)
  4644. // * StringLiteral
  4645. // * CXXTypeidExpr
  4646. // * PredefinedExpr
  4647. // * ObjCStringLiteralExpr
  4648. // * ObjCEncodeExpr
  4649. // * AddrLabelExpr
  4650. // * BlockExpr
  4651. // * CallExpr for a MakeStringConstant builtin
  4652. // - Locals and temporaries
  4653. // * MaterializeTemporaryExpr
  4654. // * Any Expr, with a CallIndex indicating the function in which the temporary
  4655. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  4656. // from the AST (FIXME).
  4657. // * A MaterializeTemporaryExpr that has static storage duration, with no
  4658. // CallIndex, for a lifetime-extended temporary.
  4659. // plus an offset in bytes.
  4660. //===----------------------------------------------------------------------===//
  4661. namespace {
  4662. class LValueExprEvaluator
  4663. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  4664. public:
  4665. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  4666. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  4667. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  4668. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  4669. bool VisitDeclRefExpr(const DeclRefExpr *E);
  4670. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  4671. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  4672. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  4673. bool VisitMemberExpr(const MemberExpr *E);
  4674. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  4675. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  4676. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  4677. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  4678. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  4679. bool VisitUnaryDeref(const UnaryOperator *E);
  4680. bool VisitUnaryReal(const UnaryOperator *E);
  4681. bool VisitUnaryImag(const UnaryOperator *E);
  4682. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  4683. return VisitUnaryPreIncDec(UO);
  4684. }
  4685. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  4686. return VisitUnaryPreIncDec(UO);
  4687. }
  4688. bool VisitBinAssign(const BinaryOperator *BO);
  4689. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  4690. bool VisitCastExpr(const CastExpr *E) {
  4691. switch (E->getCastKind()) {
  4692. default:
  4693. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4694. case CK_LValueBitCast:
  4695. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4696. if (!Visit(E->getSubExpr()))
  4697. return false;
  4698. Result.Designator.setInvalid();
  4699. return true;
  4700. case CK_BaseToDerived:
  4701. if (!Visit(E->getSubExpr()))
  4702. return false;
  4703. return HandleBaseToDerivedCast(Info, E, Result);
  4704. }
  4705. }
  4706. };
  4707. } // end anonymous namespace
  4708. /// Evaluate an expression as an lvalue. This can be legitimately called on
  4709. /// expressions which are not glvalues, in three cases:
  4710. /// * function designators in C, and
  4711. /// * "extern void" objects
  4712. /// * @selector() expressions in Objective-C
  4713. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  4714. bool InvalidBaseOK) {
  4715. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  4716. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  4717. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  4718. }
  4719. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  4720. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  4721. return Success(FD);
  4722. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  4723. return VisitVarDecl(E, VD);
  4724. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  4725. return Visit(BD->getBinding());
  4726. return Error(E);
  4727. }
  4728. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  4729. // If we are within a lambda's call operator, check whether the 'VD' referred
  4730. // to within 'E' actually represents a lambda-capture that maps to a
  4731. // data-member/field within the closure object, and if so, evaluate to the
  4732. // field or what the field refers to.
  4733. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  4734. isa<DeclRefExpr>(E) &&
  4735. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  4736. // We don't always have a complete capture-map when checking or inferring if
  4737. // the function call operator meets the requirements of a constexpr function
  4738. // - but we don't need to evaluate the captures to determine constexprness
  4739. // (dcl.constexpr C++17).
  4740. if (Info.checkingPotentialConstantExpression())
  4741. return false;
  4742. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  4743. // Start with 'Result' referring to the complete closure object...
  4744. Result = *Info.CurrentCall->This;
  4745. // ... then update it to refer to the field of the closure object
  4746. // that represents the capture.
  4747. if (!HandleLValueMember(Info, E, Result, FD))
  4748. return false;
  4749. // And if the field is of reference type, update 'Result' to refer to what
  4750. // the field refers to.
  4751. if (FD->getType()->isReferenceType()) {
  4752. APValue RVal;
  4753. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  4754. RVal))
  4755. return false;
  4756. Result.setFrom(Info.Ctx, RVal);
  4757. }
  4758. return true;
  4759. }
  4760. }
  4761. CallStackFrame *Frame = nullptr;
  4762. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  4763. // Only if a local variable was declared in the function currently being
  4764. // evaluated, do we expect to be able to find its value in the current
  4765. // frame. (Otherwise it was likely declared in an enclosing context and
  4766. // could either have a valid evaluatable value (for e.g. a constexpr
  4767. // variable) or be ill-formed (and trigger an appropriate evaluation
  4768. // diagnostic)).
  4769. if (Info.CurrentCall->Callee &&
  4770. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  4771. Frame = Info.CurrentCall;
  4772. }
  4773. }
  4774. if (!VD->getType()->isReferenceType()) {
  4775. if (Frame) {
  4776. Result.set({VD, Frame->Index,
  4777. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  4778. return true;
  4779. }
  4780. return Success(VD);
  4781. }
  4782. APValue *V;
  4783. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  4784. return false;
  4785. if (V->isUninit()) {
  4786. if (!Info.checkingPotentialConstantExpression())
  4787. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  4788. return false;
  4789. }
  4790. return Success(*V, E);
  4791. }
  4792. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  4793. const MaterializeTemporaryExpr *E) {
  4794. // Walk through the expression to find the materialized temporary itself.
  4795. SmallVector<const Expr *, 2> CommaLHSs;
  4796. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4797. const Expr *Inner = E->GetTemporaryExpr()->
  4798. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  4799. // If we passed any comma operators, evaluate their LHSs.
  4800. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  4801. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  4802. return false;
  4803. // A materialized temporary with static storage duration can appear within the
  4804. // result of a constant expression evaluation, so we need to preserve its
  4805. // value for use outside this evaluation.
  4806. APValue *Value;
  4807. if (E->getStorageDuration() == SD_Static) {
  4808. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  4809. *Value = APValue();
  4810. Result.set(E);
  4811. } else {
  4812. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  4813. *Info.CurrentCall);
  4814. }
  4815. QualType Type = Inner->getType();
  4816. // Materialize the temporary itself.
  4817. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  4818. (E->getStorageDuration() == SD_Static &&
  4819. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  4820. *Value = APValue();
  4821. return false;
  4822. }
  4823. // Adjust our lvalue to refer to the desired subobject.
  4824. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  4825. --I;
  4826. switch (Adjustments[I].Kind) {
  4827. case SubobjectAdjustment::DerivedToBaseAdjustment:
  4828. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  4829. Type, Result))
  4830. return false;
  4831. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  4832. break;
  4833. case SubobjectAdjustment::FieldAdjustment:
  4834. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  4835. return false;
  4836. Type = Adjustments[I].Field->getType();
  4837. break;
  4838. case SubobjectAdjustment::MemberPointerAdjustment:
  4839. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  4840. Adjustments[I].Ptr.RHS))
  4841. return false;
  4842. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  4843. break;
  4844. }
  4845. }
  4846. return true;
  4847. }
  4848. bool
  4849. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4850. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  4851. "lvalue compound literal in c++?");
  4852. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  4853. // only see this when folding in C, so there's no standard to follow here.
  4854. return Success(E);
  4855. }
  4856. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  4857. if (!E->isPotentiallyEvaluated())
  4858. return Success(E);
  4859. Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
  4860. << E->getExprOperand()->getType()
  4861. << E->getExprOperand()->getSourceRange();
  4862. return false;
  4863. }
  4864. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4865. return Success(E);
  4866. }
  4867. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  4868. // Handle static data members.
  4869. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  4870. VisitIgnoredBaseExpression(E->getBase());
  4871. return VisitVarDecl(E, VD);
  4872. }
  4873. // Handle static member functions.
  4874. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  4875. if (MD->isStatic()) {
  4876. VisitIgnoredBaseExpression(E->getBase());
  4877. return Success(MD);
  4878. }
  4879. }
  4880. // Handle non-static data members.
  4881. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  4882. }
  4883. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  4884. // FIXME: Deal with vectors as array subscript bases.
  4885. if (E->getBase()->getType()->isVectorType())
  4886. return Error(E);
  4887. bool Success = true;
  4888. if (!evaluatePointer(E->getBase(), Result)) {
  4889. if (!Info.noteFailure())
  4890. return false;
  4891. Success = false;
  4892. }
  4893. APSInt Index;
  4894. if (!EvaluateInteger(E->getIdx(), Index, Info))
  4895. return false;
  4896. return Success &&
  4897. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  4898. }
  4899. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  4900. return evaluatePointer(E->getSubExpr(), Result);
  4901. }
  4902. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4903. if (!Visit(E->getSubExpr()))
  4904. return false;
  4905. // __real is a no-op on scalar lvalues.
  4906. if (E->getSubExpr()->getType()->isAnyComplexType())
  4907. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  4908. return true;
  4909. }
  4910. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4911. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  4912. "lvalue __imag__ on scalar?");
  4913. if (!Visit(E->getSubExpr()))
  4914. return false;
  4915. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  4916. return true;
  4917. }
  4918. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  4919. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4920. return Error(UO);
  4921. if (!this->Visit(UO->getSubExpr()))
  4922. return false;
  4923. return handleIncDec(
  4924. this->Info, UO, Result, UO->getSubExpr()->getType(),
  4925. UO->isIncrementOp(), nullptr);
  4926. }
  4927. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  4928. const CompoundAssignOperator *CAO) {
  4929. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4930. return Error(CAO);
  4931. APValue RHS;
  4932. // The overall lvalue result is the result of evaluating the LHS.
  4933. if (!this->Visit(CAO->getLHS())) {
  4934. if (Info.noteFailure())
  4935. Evaluate(RHS, this->Info, CAO->getRHS());
  4936. return false;
  4937. }
  4938. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  4939. return false;
  4940. return handleCompoundAssignment(
  4941. this->Info, CAO,
  4942. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  4943. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  4944. }
  4945. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  4946. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4947. return Error(E);
  4948. APValue NewVal;
  4949. if (!this->Visit(E->getLHS())) {
  4950. if (Info.noteFailure())
  4951. Evaluate(NewVal, this->Info, E->getRHS());
  4952. return false;
  4953. }
  4954. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  4955. return false;
  4956. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  4957. NewVal);
  4958. }
  4959. //===----------------------------------------------------------------------===//
  4960. // Pointer Evaluation
  4961. //===----------------------------------------------------------------------===//
  4962. /// Attempts to compute the number of bytes available at the pointer
  4963. /// returned by a function with the alloc_size attribute. Returns true if we
  4964. /// were successful. Places an unsigned number into `Result`.
  4965. ///
  4966. /// This expects the given CallExpr to be a call to a function with an
  4967. /// alloc_size attribute.
  4968. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  4969. const CallExpr *Call,
  4970. llvm::APInt &Result) {
  4971. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  4972. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  4973. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  4974. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  4975. if (Call->getNumArgs() <= SizeArgNo)
  4976. return false;
  4977. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  4978. if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
  4979. return false;
  4980. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  4981. return false;
  4982. Into = Into.zextOrSelf(BitsInSizeT);
  4983. return true;
  4984. };
  4985. APSInt SizeOfElem;
  4986. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  4987. return false;
  4988. if (!AllocSize->getNumElemsParam().isValid()) {
  4989. Result = std::move(SizeOfElem);
  4990. return true;
  4991. }
  4992. APSInt NumberOfElems;
  4993. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  4994. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  4995. return false;
  4996. bool Overflow;
  4997. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  4998. if (Overflow)
  4999. return false;
  5000. Result = std::move(BytesAvailable);
  5001. return true;
  5002. }
  5003. /// Convenience function. LVal's base must be a call to an alloc_size
  5004. /// function.
  5005. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5006. const LValue &LVal,
  5007. llvm::APInt &Result) {
  5008. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  5009. "Can't get the size of a non alloc_size function");
  5010. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  5011. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  5012. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  5013. }
  5014. /// Attempts to evaluate the given LValueBase as the result of a call to
  5015. /// a function with the alloc_size attribute. If it was possible to do so, this
  5016. /// function will return true, make Result's Base point to said function call,
  5017. /// and mark Result's Base as invalid.
  5018. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  5019. LValue &Result) {
  5020. if (Base.isNull())
  5021. return false;
  5022. // Because we do no form of static analysis, we only support const variables.
  5023. //
  5024. // Additionally, we can't support parameters, nor can we support static
  5025. // variables (in the latter case, use-before-assign isn't UB; in the former,
  5026. // we have no clue what they'll be assigned to).
  5027. const auto *VD =
  5028. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  5029. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  5030. return false;
  5031. const Expr *Init = VD->getAnyInitializer();
  5032. if (!Init)
  5033. return false;
  5034. const Expr *E = Init->IgnoreParens();
  5035. if (!tryUnwrapAllocSizeCall(E))
  5036. return false;
  5037. // Store E instead of E unwrapped so that the type of the LValue's base is
  5038. // what the user wanted.
  5039. Result.setInvalid(E);
  5040. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  5041. Result.addUnsizedArray(Info, E, Pointee);
  5042. return true;
  5043. }
  5044. namespace {
  5045. class PointerExprEvaluator
  5046. : public ExprEvaluatorBase<PointerExprEvaluator> {
  5047. LValue &Result;
  5048. bool InvalidBaseOK;
  5049. bool Success(const Expr *E) {
  5050. Result.set(E);
  5051. return true;
  5052. }
  5053. bool evaluateLValue(const Expr *E, LValue &Result) {
  5054. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  5055. }
  5056. bool evaluatePointer(const Expr *E, LValue &Result) {
  5057. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  5058. }
  5059. bool visitNonBuiltinCallExpr(const CallExpr *E);
  5060. public:
  5061. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  5062. : ExprEvaluatorBaseTy(info), Result(Result),
  5063. InvalidBaseOK(InvalidBaseOK) {}
  5064. bool Success(const APValue &V, const Expr *E) {
  5065. Result.setFrom(Info.Ctx, V);
  5066. return true;
  5067. }
  5068. bool ZeroInitialization(const Expr *E) {
  5069. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  5070. Result.setNull(E->getType(), TargetVal);
  5071. return true;
  5072. }
  5073. bool VisitBinaryOperator(const BinaryOperator *E);
  5074. bool VisitCastExpr(const CastExpr* E);
  5075. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5076. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  5077. { return Success(E); }
  5078. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  5079. if (Info.noteFailure())
  5080. EvaluateIgnoredValue(Info, E->getSubExpr());
  5081. return Error(E);
  5082. }
  5083. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  5084. { return Success(E); }
  5085. bool VisitCallExpr(const CallExpr *E);
  5086. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  5087. bool VisitBlockExpr(const BlockExpr *E) {
  5088. if (!E->getBlockDecl()->hasCaptures())
  5089. return Success(E);
  5090. return Error(E);
  5091. }
  5092. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  5093. // Can't look at 'this' when checking a potential constant expression.
  5094. if (Info.checkingPotentialConstantExpression())
  5095. return false;
  5096. if (!Info.CurrentCall->This) {
  5097. if (Info.getLangOpts().CPlusPlus11)
  5098. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  5099. else
  5100. Info.FFDiag(E);
  5101. return false;
  5102. }
  5103. Result = *Info.CurrentCall->This;
  5104. // If we are inside a lambda's call operator, the 'this' expression refers
  5105. // to the enclosing '*this' object (either by value or reference) which is
  5106. // either copied into the closure object's field that represents the '*this'
  5107. // or refers to '*this'.
  5108. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  5109. // Update 'Result' to refer to the data member/field of the closure object
  5110. // that represents the '*this' capture.
  5111. if (!HandleLValueMember(Info, E, Result,
  5112. Info.CurrentCall->LambdaThisCaptureField))
  5113. return false;
  5114. // If we captured '*this' by reference, replace the field with its referent.
  5115. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  5116. ->isPointerType()) {
  5117. APValue RVal;
  5118. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  5119. RVal))
  5120. return false;
  5121. Result.setFrom(Info.Ctx, RVal);
  5122. }
  5123. }
  5124. return true;
  5125. }
  5126. // FIXME: Missing: @protocol, @selector
  5127. };
  5128. } // end anonymous namespace
  5129. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  5130. bool InvalidBaseOK) {
  5131. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  5132. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5133. }
  5134. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5135. if (E->getOpcode() != BO_Add &&
  5136. E->getOpcode() != BO_Sub)
  5137. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5138. const Expr *PExp = E->getLHS();
  5139. const Expr *IExp = E->getRHS();
  5140. if (IExp->getType()->isPointerType())
  5141. std::swap(PExp, IExp);
  5142. bool EvalPtrOK = evaluatePointer(PExp, Result);
  5143. if (!EvalPtrOK && !Info.noteFailure())
  5144. return false;
  5145. llvm::APSInt Offset;
  5146. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  5147. return false;
  5148. if (E->getOpcode() == BO_Sub)
  5149. negateAsSigned(Offset);
  5150. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  5151. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  5152. }
  5153. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5154. return evaluateLValue(E->getSubExpr(), Result);
  5155. }
  5156. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5157. const Expr *SubExpr = E->getSubExpr();
  5158. switch (E->getCastKind()) {
  5159. default:
  5160. break;
  5161. case CK_BitCast:
  5162. case CK_CPointerToObjCPointerCast:
  5163. case CK_BlockPointerToObjCPointerCast:
  5164. case CK_AnyPointerToBlockPointerCast:
  5165. case CK_AddressSpaceConversion:
  5166. if (!Visit(SubExpr))
  5167. return false;
  5168. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  5169. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  5170. // also static_casts, but we disallow them as a resolution to DR1312.
  5171. if (!E->getType()->isVoidPointerType()) {
  5172. Result.Designator.setInvalid();
  5173. if (SubExpr->getType()->isVoidPointerType())
  5174. CCEDiag(E, diag::note_constexpr_invalid_cast)
  5175. << 3 << SubExpr->getType();
  5176. else
  5177. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5178. }
  5179. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  5180. ZeroInitialization(E);
  5181. return true;
  5182. case CK_DerivedToBase:
  5183. case CK_UncheckedDerivedToBase:
  5184. if (!evaluatePointer(E->getSubExpr(), Result))
  5185. return false;
  5186. if (!Result.Base && Result.Offset.isZero())
  5187. return true;
  5188. // Now figure out the necessary offset to add to the base LV to get from
  5189. // the derived class to the base class.
  5190. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  5191. castAs<PointerType>()->getPointeeType(),
  5192. Result);
  5193. case CK_BaseToDerived:
  5194. if (!Visit(E->getSubExpr()))
  5195. return false;
  5196. if (!Result.Base && Result.Offset.isZero())
  5197. return true;
  5198. return HandleBaseToDerivedCast(Info, E, Result);
  5199. case CK_NullToPointer:
  5200. VisitIgnoredValue(E->getSubExpr());
  5201. return ZeroInitialization(E);
  5202. case CK_IntegralToPointer: {
  5203. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5204. APValue Value;
  5205. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  5206. break;
  5207. if (Value.isInt()) {
  5208. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  5209. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  5210. Result.Base = (Expr*)nullptr;
  5211. Result.InvalidBase = false;
  5212. Result.Offset = CharUnits::fromQuantity(N);
  5213. Result.Designator.setInvalid();
  5214. Result.IsNullPtr = false;
  5215. return true;
  5216. } else {
  5217. // Cast is of an lvalue, no need to change value.
  5218. Result.setFrom(Info.Ctx, Value);
  5219. return true;
  5220. }
  5221. }
  5222. case CK_ArrayToPointerDecay: {
  5223. if (SubExpr->isGLValue()) {
  5224. if (!evaluateLValue(SubExpr, Result))
  5225. return false;
  5226. } else {
  5227. APValue &Value = createTemporary(SubExpr, false, Result,
  5228. *Info.CurrentCall);
  5229. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  5230. return false;
  5231. }
  5232. // The result is a pointer to the first element of the array.
  5233. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  5234. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5235. Result.addArray(Info, E, CAT);
  5236. else
  5237. Result.addUnsizedArray(Info, E, AT->getElementType());
  5238. return true;
  5239. }
  5240. case CK_FunctionToPointerDecay:
  5241. return evaluateLValue(SubExpr, Result);
  5242. case CK_LValueToRValue: {
  5243. LValue LVal;
  5244. if (!evaluateLValue(E->getSubExpr(), LVal))
  5245. return false;
  5246. APValue RVal;
  5247. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5248. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5249. LVal, RVal))
  5250. return InvalidBaseOK &&
  5251. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  5252. return Success(RVal, E);
  5253. }
  5254. }
  5255. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5256. }
  5257. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  5258. UnaryExprOrTypeTrait ExprKind) {
  5259. // C++ [expr.alignof]p3:
  5260. // When alignof is applied to a reference type, the result is the
  5261. // alignment of the referenced type.
  5262. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  5263. T = Ref->getPointeeType();
  5264. if (T.getQualifiers().hasUnaligned())
  5265. return CharUnits::One();
  5266. const bool AlignOfReturnsPreferred =
  5267. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  5268. // __alignof is defined to return the preferred alignment.
  5269. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  5270. // as well.
  5271. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  5272. return Info.Ctx.toCharUnitsFromBits(
  5273. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  5274. // alignof and _Alignof are defined to return the ABI alignment.
  5275. else if (ExprKind == UETT_AlignOf)
  5276. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  5277. else
  5278. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  5279. }
  5280. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  5281. UnaryExprOrTypeTrait ExprKind) {
  5282. E = E->IgnoreParens();
  5283. // The kinds of expressions that we have special-case logic here for
  5284. // should be kept up to date with the special checks for those
  5285. // expressions in Sema.
  5286. // alignof decl is always accepted, even if it doesn't make sense: we default
  5287. // to 1 in those cases.
  5288. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5289. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  5290. /*RefAsPointee*/true);
  5291. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  5292. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  5293. /*RefAsPointee*/true);
  5294. return GetAlignOfType(Info, E->getType(), ExprKind);
  5295. }
  5296. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  5297. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  5298. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  5299. return true;
  5300. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  5301. return false;
  5302. Result.setInvalid(E);
  5303. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  5304. Result.addUnsizedArray(Info, E, PointeeTy);
  5305. return true;
  5306. }
  5307. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  5308. if (IsStringLiteralCall(E))
  5309. return Success(E);
  5310. if (unsigned BuiltinOp = E->getBuiltinCallee())
  5311. return VisitBuiltinCallExpr(E, BuiltinOp);
  5312. return visitNonBuiltinCallExpr(E);
  5313. }
  5314. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  5315. unsigned BuiltinOp) {
  5316. switch (BuiltinOp) {
  5317. case Builtin::BI__builtin_addressof:
  5318. return evaluateLValue(E->getArg(0), Result);
  5319. case Builtin::BI__builtin_assume_aligned: {
  5320. // We need to be very careful here because: if the pointer does not have the
  5321. // asserted alignment, then the behavior is undefined, and undefined
  5322. // behavior is non-constant.
  5323. if (!evaluatePointer(E->getArg(0), Result))
  5324. return false;
  5325. LValue OffsetResult(Result);
  5326. APSInt Alignment;
  5327. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  5328. return false;
  5329. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  5330. if (E->getNumArgs() > 2) {
  5331. APSInt Offset;
  5332. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  5333. return false;
  5334. int64_t AdditionalOffset = -Offset.getZExtValue();
  5335. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  5336. }
  5337. // If there is a base object, then it must have the correct alignment.
  5338. if (OffsetResult.Base) {
  5339. CharUnits BaseAlignment;
  5340. if (const ValueDecl *VD =
  5341. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  5342. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  5343. } else {
  5344. BaseAlignment = GetAlignOfExpr(
  5345. Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
  5346. }
  5347. if (BaseAlignment < Align) {
  5348. Result.Designator.setInvalid();
  5349. // FIXME: Add support to Diagnostic for long / long long.
  5350. CCEDiag(E->getArg(0),
  5351. diag::note_constexpr_baa_insufficient_alignment) << 0
  5352. << (unsigned)BaseAlignment.getQuantity()
  5353. << (unsigned)Align.getQuantity();
  5354. return false;
  5355. }
  5356. }
  5357. // The offset must also have the correct alignment.
  5358. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  5359. Result.Designator.setInvalid();
  5360. (OffsetResult.Base
  5361. ? CCEDiag(E->getArg(0),
  5362. diag::note_constexpr_baa_insufficient_alignment) << 1
  5363. : CCEDiag(E->getArg(0),
  5364. diag::note_constexpr_baa_value_insufficient_alignment))
  5365. << (int)OffsetResult.Offset.getQuantity()
  5366. << (unsigned)Align.getQuantity();
  5367. return false;
  5368. }
  5369. return true;
  5370. }
  5371. case Builtin::BIstrchr:
  5372. case Builtin::BIwcschr:
  5373. case Builtin::BImemchr:
  5374. case Builtin::BIwmemchr:
  5375. if (Info.getLangOpts().CPlusPlus11)
  5376. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5377. << /*isConstexpr*/0 << /*isConstructor*/0
  5378. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5379. else
  5380. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5381. LLVM_FALLTHROUGH;
  5382. case Builtin::BI__builtin_strchr:
  5383. case Builtin::BI__builtin_wcschr:
  5384. case Builtin::BI__builtin_memchr:
  5385. case Builtin::BI__builtin_char_memchr:
  5386. case Builtin::BI__builtin_wmemchr: {
  5387. if (!Visit(E->getArg(0)))
  5388. return false;
  5389. APSInt Desired;
  5390. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  5391. return false;
  5392. uint64_t MaxLength = uint64_t(-1);
  5393. if (BuiltinOp != Builtin::BIstrchr &&
  5394. BuiltinOp != Builtin::BIwcschr &&
  5395. BuiltinOp != Builtin::BI__builtin_strchr &&
  5396. BuiltinOp != Builtin::BI__builtin_wcschr) {
  5397. APSInt N;
  5398. if (!EvaluateInteger(E->getArg(2), N, Info))
  5399. return false;
  5400. MaxLength = N.getExtValue();
  5401. }
  5402. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  5403. // Figure out what value we're actually looking for (after converting to
  5404. // the corresponding unsigned type if necessary).
  5405. uint64_t DesiredVal;
  5406. bool StopAtNull = false;
  5407. switch (BuiltinOp) {
  5408. case Builtin::BIstrchr:
  5409. case Builtin::BI__builtin_strchr:
  5410. // strchr compares directly to the passed integer, and therefore
  5411. // always fails if given an int that is not a char.
  5412. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  5413. E->getArg(1)->getType(),
  5414. Desired),
  5415. Desired))
  5416. return ZeroInitialization(E);
  5417. StopAtNull = true;
  5418. LLVM_FALLTHROUGH;
  5419. case Builtin::BImemchr:
  5420. case Builtin::BI__builtin_memchr:
  5421. case Builtin::BI__builtin_char_memchr:
  5422. // memchr compares by converting both sides to unsigned char. That's also
  5423. // correct for strchr if we get this far (to cope with plain char being
  5424. // unsigned in the strchr case).
  5425. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  5426. break;
  5427. case Builtin::BIwcschr:
  5428. case Builtin::BI__builtin_wcschr:
  5429. StopAtNull = true;
  5430. LLVM_FALLTHROUGH;
  5431. case Builtin::BIwmemchr:
  5432. case Builtin::BI__builtin_wmemchr:
  5433. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  5434. DesiredVal = Desired.getZExtValue();
  5435. break;
  5436. }
  5437. for (; MaxLength; --MaxLength) {
  5438. APValue Char;
  5439. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  5440. !Char.isInt())
  5441. return false;
  5442. if (Char.getInt().getZExtValue() == DesiredVal)
  5443. return true;
  5444. if (StopAtNull && !Char.getInt())
  5445. break;
  5446. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  5447. return false;
  5448. }
  5449. // Not found: return nullptr.
  5450. return ZeroInitialization(E);
  5451. }
  5452. case Builtin::BImemcpy:
  5453. case Builtin::BImemmove:
  5454. case Builtin::BIwmemcpy:
  5455. case Builtin::BIwmemmove:
  5456. if (Info.getLangOpts().CPlusPlus11)
  5457. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5458. << /*isConstexpr*/0 << /*isConstructor*/0
  5459. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5460. else
  5461. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5462. LLVM_FALLTHROUGH;
  5463. case Builtin::BI__builtin_memcpy:
  5464. case Builtin::BI__builtin_memmove:
  5465. case Builtin::BI__builtin_wmemcpy:
  5466. case Builtin::BI__builtin_wmemmove: {
  5467. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  5468. BuiltinOp == Builtin::BIwmemmove ||
  5469. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  5470. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5471. bool Move = BuiltinOp == Builtin::BImemmove ||
  5472. BuiltinOp == Builtin::BIwmemmove ||
  5473. BuiltinOp == Builtin::BI__builtin_memmove ||
  5474. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5475. // The result of mem* is the first argument.
  5476. if (!Visit(E->getArg(0)))
  5477. return false;
  5478. LValue Dest = Result;
  5479. LValue Src;
  5480. if (!EvaluatePointer(E->getArg(1), Src, Info))
  5481. return false;
  5482. APSInt N;
  5483. if (!EvaluateInteger(E->getArg(2), N, Info))
  5484. return false;
  5485. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  5486. // If the size is zero, we treat this as always being a valid no-op.
  5487. // (Even if one of the src and dest pointers is null.)
  5488. if (!N)
  5489. return true;
  5490. // Otherwise, if either of the operands is null, we can't proceed. Don't
  5491. // try to determine the type of the copied objects, because there aren't
  5492. // any.
  5493. if (!Src.Base || !Dest.Base) {
  5494. APValue Val;
  5495. (!Src.Base ? Src : Dest).moveInto(Val);
  5496. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  5497. << Move << WChar << !!Src.Base
  5498. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  5499. return false;
  5500. }
  5501. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  5502. return false;
  5503. // We require that Src and Dest are both pointers to arrays of
  5504. // trivially-copyable type. (For the wide version, the designator will be
  5505. // invalid if the designated object is not a wchar_t.)
  5506. QualType T = Dest.Designator.getType(Info.Ctx);
  5507. QualType SrcT = Src.Designator.getType(Info.Ctx);
  5508. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  5509. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  5510. return false;
  5511. }
  5512. if (T->isIncompleteType()) {
  5513. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  5514. return false;
  5515. }
  5516. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  5517. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  5518. return false;
  5519. }
  5520. // Figure out how many T's we're copying.
  5521. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  5522. if (!WChar) {
  5523. uint64_t Remainder;
  5524. llvm::APInt OrigN = N;
  5525. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  5526. if (Remainder) {
  5527. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  5528. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  5529. << (unsigned)TSize;
  5530. return false;
  5531. }
  5532. }
  5533. // Check that the copying will remain within the arrays, just so that we
  5534. // can give a more meaningful diagnostic. This implicitly also checks that
  5535. // N fits into 64 bits.
  5536. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  5537. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  5538. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  5539. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  5540. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  5541. << N.toString(10, /*Signed*/false);
  5542. return false;
  5543. }
  5544. uint64_t NElems = N.getZExtValue();
  5545. uint64_t NBytes = NElems * TSize;
  5546. // Check for overlap.
  5547. int Direction = 1;
  5548. if (HasSameBase(Src, Dest)) {
  5549. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  5550. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  5551. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  5552. // Dest is inside the source region.
  5553. if (!Move) {
  5554. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  5555. return false;
  5556. }
  5557. // For memmove and friends, copy backwards.
  5558. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  5559. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  5560. return false;
  5561. Direction = -1;
  5562. } else if (!Move && SrcOffset >= DestOffset &&
  5563. SrcOffset - DestOffset < NBytes) {
  5564. // Src is inside the destination region for memcpy: invalid.
  5565. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  5566. return false;
  5567. }
  5568. }
  5569. while (true) {
  5570. APValue Val;
  5571. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  5572. !handleAssignment(Info, E, Dest, T, Val))
  5573. return false;
  5574. // Do not iterate past the last element; if we're copying backwards, that
  5575. // might take us off the start of the array.
  5576. if (--NElems == 0)
  5577. return true;
  5578. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  5579. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  5580. return false;
  5581. }
  5582. }
  5583. default:
  5584. return visitNonBuiltinCallExpr(E);
  5585. }
  5586. }
  5587. //===----------------------------------------------------------------------===//
  5588. // Member Pointer Evaluation
  5589. //===----------------------------------------------------------------------===//
  5590. namespace {
  5591. class MemberPointerExprEvaluator
  5592. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  5593. MemberPtr &Result;
  5594. bool Success(const ValueDecl *D) {
  5595. Result = MemberPtr(D);
  5596. return true;
  5597. }
  5598. public:
  5599. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  5600. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  5601. bool Success(const APValue &V, const Expr *E) {
  5602. Result.setFrom(V);
  5603. return true;
  5604. }
  5605. bool ZeroInitialization(const Expr *E) {
  5606. return Success((const ValueDecl*)nullptr);
  5607. }
  5608. bool VisitCastExpr(const CastExpr *E);
  5609. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5610. };
  5611. } // end anonymous namespace
  5612. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  5613. EvalInfo &Info) {
  5614. assert(E->isRValue() && E->getType()->isMemberPointerType());
  5615. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  5616. }
  5617. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5618. switch (E->getCastKind()) {
  5619. default:
  5620. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5621. case CK_NullToMemberPointer:
  5622. VisitIgnoredValue(E->getSubExpr());
  5623. return ZeroInitialization(E);
  5624. case CK_BaseToDerivedMemberPointer: {
  5625. if (!Visit(E->getSubExpr()))
  5626. return false;
  5627. if (E->path_empty())
  5628. return true;
  5629. // Base-to-derived member pointer casts store the path in derived-to-base
  5630. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  5631. // the wrong end of the derived->base arc, so stagger the path by one class.
  5632. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  5633. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  5634. PathI != PathE; ++PathI) {
  5635. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5636. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  5637. if (!Result.castToDerived(Derived))
  5638. return Error(E);
  5639. }
  5640. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  5641. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  5642. return Error(E);
  5643. return true;
  5644. }
  5645. case CK_DerivedToBaseMemberPointer:
  5646. if (!Visit(E->getSubExpr()))
  5647. return false;
  5648. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5649. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5650. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5651. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5652. if (!Result.castToBase(Base))
  5653. return Error(E);
  5654. }
  5655. return true;
  5656. }
  5657. }
  5658. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5659. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  5660. // member can be formed.
  5661. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  5662. }
  5663. //===----------------------------------------------------------------------===//
  5664. // Record Evaluation
  5665. //===----------------------------------------------------------------------===//
  5666. namespace {
  5667. class RecordExprEvaluator
  5668. : public ExprEvaluatorBase<RecordExprEvaluator> {
  5669. const LValue &This;
  5670. APValue &Result;
  5671. public:
  5672. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  5673. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  5674. bool Success(const APValue &V, const Expr *E) {
  5675. Result = V;
  5676. return true;
  5677. }
  5678. bool ZeroInitialization(const Expr *E) {
  5679. return ZeroInitialization(E, E->getType());
  5680. }
  5681. bool ZeroInitialization(const Expr *E, QualType T);
  5682. bool VisitCallExpr(const CallExpr *E) {
  5683. return handleCallExpr(E, Result, &This);
  5684. }
  5685. bool VisitCastExpr(const CastExpr *E);
  5686. bool VisitInitListExpr(const InitListExpr *E);
  5687. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5688. return VisitCXXConstructExpr(E, E->getType());
  5689. }
  5690. bool VisitLambdaExpr(const LambdaExpr *E);
  5691. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  5692. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  5693. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  5694. bool VisitBinCmp(const BinaryOperator *E);
  5695. };
  5696. }
  5697. /// Perform zero-initialization on an object of non-union class type.
  5698. /// C++11 [dcl.init]p5:
  5699. /// To zero-initialize an object or reference of type T means:
  5700. /// [...]
  5701. /// -- if T is a (possibly cv-qualified) non-union class type,
  5702. /// each non-static data member and each base-class subobject is
  5703. /// zero-initialized
  5704. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  5705. const RecordDecl *RD,
  5706. const LValue &This, APValue &Result) {
  5707. assert(!RD->isUnion() && "Expected non-union class type");
  5708. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  5709. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  5710. std::distance(RD->field_begin(), RD->field_end()));
  5711. if (RD->isInvalidDecl()) return false;
  5712. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5713. if (CD) {
  5714. unsigned Index = 0;
  5715. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  5716. End = CD->bases_end(); I != End; ++I, ++Index) {
  5717. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  5718. LValue Subobject = This;
  5719. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  5720. return false;
  5721. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  5722. Result.getStructBase(Index)))
  5723. return false;
  5724. }
  5725. }
  5726. for (const auto *I : RD->fields()) {
  5727. // -- if T is a reference type, no initialization is performed.
  5728. if (I->getType()->isReferenceType())
  5729. continue;
  5730. LValue Subobject = This;
  5731. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  5732. return false;
  5733. ImplicitValueInitExpr VIE(I->getType());
  5734. if (!EvaluateInPlace(
  5735. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  5736. return false;
  5737. }
  5738. return true;
  5739. }
  5740. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  5741. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  5742. if (RD->isInvalidDecl()) return false;
  5743. if (RD->isUnion()) {
  5744. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  5745. // object's first non-static named data member is zero-initialized
  5746. RecordDecl::field_iterator I = RD->field_begin();
  5747. if (I == RD->field_end()) {
  5748. Result = APValue((const FieldDecl*)nullptr);
  5749. return true;
  5750. }
  5751. LValue Subobject = This;
  5752. if (!HandleLValueMember(Info, E, Subobject, *I))
  5753. return false;
  5754. Result = APValue(*I);
  5755. ImplicitValueInitExpr VIE(I->getType());
  5756. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  5757. }
  5758. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  5759. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  5760. return false;
  5761. }
  5762. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  5763. }
  5764. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5765. switch (E->getCastKind()) {
  5766. default:
  5767. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5768. case CK_ConstructorConversion:
  5769. return Visit(E->getSubExpr());
  5770. case CK_DerivedToBase:
  5771. case CK_UncheckedDerivedToBase: {
  5772. APValue DerivedObject;
  5773. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  5774. return false;
  5775. if (!DerivedObject.isStruct())
  5776. return Error(E->getSubExpr());
  5777. // Derived-to-base rvalue conversion: just slice off the derived part.
  5778. APValue *Value = &DerivedObject;
  5779. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  5780. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5781. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5782. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  5783. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5784. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  5785. RD = Base;
  5786. }
  5787. Result = *Value;
  5788. return true;
  5789. }
  5790. }
  5791. }
  5792. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5793. if (E->isTransparent())
  5794. return Visit(E->getInit(0));
  5795. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  5796. if (RD->isInvalidDecl()) return false;
  5797. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5798. if (RD->isUnion()) {
  5799. const FieldDecl *Field = E->getInitializedFieldInUnion();
  5800. Result = APValue(Field);
  5801. if (!Field)
  5802. return true;
  5803. // If the initializer list for a union does not contain any elements, the
  5804. // first element of the union is value-initialized.
  5805. // FIXME: The element should be initialized from an initializer list.
  5806. // Is this difference ever observable for initializer lists which
  5807. // we don't build?
  5808. ImplicitValueInitExpr VIE(Field->getType());
  5809. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  5810. LValue Subobject = This;
  5811. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  5812. return false;
  5813. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5814. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5815. isa<CXXDefaultInitExpr>(InitExpr));
  5816. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  5817. }
  5818. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  5819. if (Result.isUninit())
  5820. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  5821. std::distance(RD->field_begin(), RD->field_end()));
  5822. unsigned ElementNo = 0;
  5823. bool Success = true;
  5824. // Initialize base classes.
  5825. if (CXXRD) {
  5826. for (const auto &Base : CXXRD->bases()) {
  5827. assert(ElementNo < E->getNumInits() && "missing init for base class");
  5828. const Expr *Init = E->getInit(ElementNo);
  5829. LValue Subobject = This;
  5830. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  5831. return false;
  5832. APValue &FieldVal = Result.getStructBase(ElementNo);
  5833. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  5834. if (!Info.noteFailure())
  5835. return false;
  5836. Success = false;
  5837. }
  5838. ++ElementNo;
  5839. }
  5840. }
  5841. // Initialize members.
  5842. for (const auto *Field : RD->fields()) {
  5843. // Anonymous bit-fields are not considered members of the class for
  5844. // purposes of aggregate initialization.
  5845. if (Field->isUnnamedBitfield())
  5846. continue;
  5847. LValue Subobject = This;
  5848. bool HaveInit = ElementNo < E->getNumInits();
  5849. // FIXME: Diagnostics here should point to the end of the initializer
  5850. // list, not the start.
  5851. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  5852. Subobject, Field, &Layout))
  5853. return false;
  5854. // Perform an implicit value-initialization for members beyond the end of
  5855. // the initializer list.
  5856. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  5857. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  5858. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5859. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5860. isa<CXXDefaultInitExpr>(Init));
  5861. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5862. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  5863. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  5864. FieldVal, Field))) {
  5865. if (!Info.noteFailure())
  5866. return false;
  5867. Success = false;
  5868. }
  5869. }
  5870. return Success;
  5871. }
  5872. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5873. QualType T) {
  5874. // Note that E's type is not necessarily the type of our class here; we might
  5875. // be initializing an array element instead.
  5876. const CXXConstructorDecl *FD = E->getConstructor();
  5877. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  5878. bool ZeroInit = E->requiresZeroInitialization();
  5879. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  5880. // If we've already performed zero-initialization, we're already done.
  5881. if (!Result.isUninit())
  5882. return true;
  5883. // We can get here in two different ways:
  5884. // 1) We're performing value-initialization, and should zero-initialize
  5885. // the object, or
  5886. // 2) We're performing default-initialization of an object with a trivial
  5887. // constexpr default constructor, in which case we should start the
  5888. // lifetimes of all the base subobjects (there can be no data member
  5889. // subobjects in this case) per [basic.life]p1.
  5890. // Either way, ZeroInitialization is appropriate.
  5891. return ZeroInitialization(E, T);
  5892. }
  5893. const FunctionDecl *Definition = nullptr;
  5894. auto Body = FD->getBody(Definition);
  5895. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5896. return false;
  5897. // Avoid materializing a temporary for an elidable copy/move constructor.
  5898. if (E->isElidable() && !ZeroInit)
  5899. if (const MaterializeTemporaryExpr *ME
  5900. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  5901. return Visit(ME->GetTemporaryExpr());
  5902. if (ZeroInit && !ZeroInitialization(E, T))
  5903. return false;
  5904. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5905. return HandleConstructorCall(E, This, Args,
  5906. cast<CXXConstructorDecl>(Definition), Info,
  5907. Result);
  5908. }
  5909. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  5910. const CXXInheritedCtorInitExpr *E) {
  5911. if (!Info.CurrentCall) {
  5912. assert(Info.checkingPotentialConstantExpression());
  5913. return false;
  5914. }
  5915. const CXXConstructorDecl *FD = E->getConstructor();
  5916. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  5917. return false;
  5918. const FunctionDecl *Definition = nullptr;
  5919. auto Body = FD->getBody(Definition);
  5920. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5921. return false;
  5922. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  5923. cast<CXXConstructorDecl>(Definition), Info,
  5924. Result);
  5925. }
  5926. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  5927. const CXXStdInitializerListExpr *E) {
  5928. const ConstantArrayType *ArrayType =
  5929. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  5930. LValue Array;
  5931. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  5932. return false;
  5933. // Get a pointer to the first element of the array.
  5934. Array.addArray(Info, E, ArrayType);
  5935. // FIXME: Perform the checks on the field types in SemaInit.
  5936. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  5937. RecordDecl::field_iterator Field = Record->field_begin();
  5938. if (Field == Record->field_end())
  5939. return Error(E);
  5940. // Start pointer.
  5941. if (!Field->getType()->isPointerType() ||
  5942. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5943. ArrayType->getElementType()))
  5944. return Error(E);
  5945. // FIXME: What if the initializer_list type has base classes, etc?
  5946. Result = APValue(APValue::UninitStruct(), 0, 2);
  5947. Array.moveInto(Result.getStructField(0));
  5948. if (++Field == Record->field_end())
  5949. return Error(E);
  5950. if (Field->getType()->isPointerType() &&
  5951. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5952. ArrayType->getElementType())) {
  5953. // End pointer.
  5954. if (!HandleLValueArrayAdjustment(Info, E, Array,
  5955. ArrayType->getElementType(),
  5956. ArrayType->getSize().getZExtValue()))
  5957. return false;
  5958. Array.moveInto(Result.getStructField(1));
  5959. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  5960. // Length.
  5961. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  5962. else
  5963. return Error(E);
  5964. if (++Field != Record->field_end())
  5965. return Error(E);
  5966. return true;
  5967. }
  5968. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  5969. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  5970. if (ClosureClass->isInvalidDecl()) return false;
  5971. if (Info.checkingPotentialConstantExpression()) return true;
  5972. const size_t NumFields =
  5973. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  5974. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  5975. E->capture_init_end()) &&
  5976. "The number of lambda capture initializers should equal the number of "
  5977. "fields within the closure type");
  5978. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  5979. // Iterate through all the lambda's closure object's fields and initialize
  5980. // them.
  5981. auto *CaptureInitIt = E->capture_init_begin();
  5982. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  5983. bool Success = true;
  5984. for (const auto *Field : ClosureClass->fields()) {
  5985. assert(CaptureInitIt != E->capture_init_end());
  5986. // Get the initializer for this field
  5987. Expr *const CurFieldInit = *CaptureInitIt++;
  5988. // If there is no initializer, either this is a VLA or an error has
  5989. // occurred.
  5990. if (!CurFieldInit)
  5991. return Error(E);
  5992. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5993. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  5994. if (!Info.keepEvaluatingAfterFailure())
  5995. return false;
  5996. Success = false;
  5997. }
  5998. ++CaptureIt;
  5999. }
  6000. return Success;
  6001. }
  6002. static bool EvaluateRecord(const Expr *E, const LValue &This,
  6003. APValue &Result, EvalInfo &Info) {
  6004. assert(E->isRValue() && E->getType()->isRecordType() &&
  6005. "can't evaluate expression as a record rvalue");
  6006. return RecordExprEvaluator(Info, This, Result).Visit(E);
  6007. }
  6008. //===----------------------------------------------------------------------===//
  6009. // Temporary Evaluation
  6010. //
  6011. // Temporaries are represented in the AST as rvalues, but generally behave like
  6012. // lvalues. The full-object of which the temporary is a subobject is implicitly
  6013. // materialized so that a reference can bind to it.
  6014. //===----------------------------------------------------------------------===//
  6015. namespace {
  6016. class TemporaryExprEvaluator
  6017. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  6018. public:
  6019. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  6020. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  6021. /// Visit an expression which constructs the value of this temporary.
  6022. bool VisitConstructExpr(const Expr *E) {
  6023. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  6024. return EvaluateInPlace(Value, Info, Result, E);
  6025. }
  6026. bool VisitCastExpr(const CastExpr *E) {
  6027. switch (E->getCastKind()) {
  6028. default:
  6029. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6030. case CK_ConstructorConversion:
  6031. return VisitConstructExpr(E->getSubExpr());
  6032. }
  6033. }
  6034. bool VisitInitListExpr(const InitListExpr *E) {
  6035. return VisitConstructExpr(E);
  6036. }
  6037. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6038. return VisitConstructExpr(E);
  6039. }
  6040. bool VisitCallExpr(const CallExpr *E) {
  6041. return VisitConstructExpr(E);
  6042. }
  6043. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  6044. return VisitConstructExpr(E);
  6045. }
  6046. bool VisitLambdaExpr(const LambdaExpr *E) {
  6047. return VisitConstructExpr(E);
  6048. }
  6049. };
  6050. } // end anonymous namespace
  6051. /// Evaluate an expression of record type as a temporary.
  6052. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  6053. assert(E->isRValue() && E->getType()->isRecordType());
  6054. return TemporaryExprEvaluator(Info, Result).Visit(E);
  6055. }
  6056. //===----------------------------------------------------------------------===//
  6057. // Vector Evaluation
  6058. //===----------------------------------------------------------------------===//
  6059. namespace {
  6060. class VectorExprEvaluator
  6061. : public ExprEvaluatorBase<VectorExprEvaluator> {
  6062. APValue &Result;
  6063. public:
  6064. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  6065. : ExprEvaluatorBaseTy(info), Result(Result) {}
  6066. bool Success(ArrayRef<APValue> V, const Expr *E) {
  6067. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  6068. // FIXME: remove this APValue copy.
  6069. Result = APValue(V.data(), V.size());
  6070. return true;
  6071. }
  6072. bool Success(const APValue &V, const Expr *E) {
  6073. assert(V.isVector());
  6074. Result = V;
  6075. return true;
  6076. }
  6077. bool ZeroInitialization(const Expr *E);
  6078. bool VisitUnaryReal(const UnaryOperator *E)
  6079. { return Visit(E->getSubExpr()); }
  6080. bool VisitCastExpr(const CastExpr* E);
  6081. bool VisitInitListExpr(const InitListExpr *E);
  6082. bool VisitUnaryImag(const UnaryOperator *E);
  6083. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  6084. // binary comparisons, binary and/or/xor,
  6085. // shufflevector, ExtVectorElementExpr
  6086. };
  6087. } // end anonymous namespace
  6088. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  6089. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  6090. return VectorExprEvaluator(Info, Result).Visit(E);
  6091. }
  6092. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6093. const VectorType *VTy = E->getType()->castAs<VectorType>();
  6094. unsigned NElts = VTy->getNumElements();
  6095. const Expr *SE = E->getSubExpr();
  6096. QualType SETy = SE->getType();
  6097. switch (E->getCastKind()) {
  6098. case CK_VectorSplat: {
  6099. APValue Val = APValue();
  6100. if (SETy->isIntegerType()) {
  6101. APSInt IntResult;
  6102. if (!EvaluateInteger(SE, IntResult, Info))
  6103. return false;
  6104. Val = APValue(std::move(IntResult));
  6105. } else if (SETy->isRealFloatingType()) {
  6106. APFloat FloatResult(0.0);
  6107. if (!EvaluateFloat(SE, FloatResult, Info))
  6108. return false;
  6109. Val = APValue(std::move(FloatResult));
  6110. } else {
  6111. return Error(E);
  6112. }
  6113. // Splat and create vector APValue.
  6114. SmallVector<APValue, 4> Elts(NElts, Val);
  6115. return Success(Elts, E);
  6116. }
  6117. case CK_BitCast: {
  6118. // Evaluate the operand into an APInt we can extract from.
  6119. llvm::APInt SValInt;
  6120. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  6121. return false;
  6122. // Extract the elements
  6123. QualType EltTy = VTy->getElementType();
  6124. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  6125. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  6126. SmallVector<APValue, 4> Elts;
  6127. if (EltTy->isRealFloatingType()) {
  6128. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  6129. unsigned FloatEltSize = EltSize;
  6130. if (&Sem == &APFloat::x87DoubleExtended())
  6131. FloatEltSize = 80;
  6132. for (unsigned i = 0; i < NElts; i++) {
  6133. llvm::APInt Elt;
  6134. if (BigEndian)
  6135. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  6136. else
  6137. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  6138. Elts.push_back(APValue(APFloat(Sem, Elt)));
  6139. }
  6140. } else if (EltTy->isIntegerType()) {
  6141. for (unsigned i = 0; i < NElts; i++) {
  6142. llvm::APInt Elt;
  6143. if (BigEndian)
  6144. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  6145. else
  6146. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  6147. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  6148. }
  6149. } else {
  6150. return Error(E);
  6151. }
  6152. return Success(Elts, E);
  6153. }
  6154. default:
  6155. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6156. }
  6157. }
  6158. bool
  6159. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6160. const VectorType *VT = E->getType()->castAs<VectorType>();
  6161. unsigned NumInits = E->getNumInits();
  6162. unsigned NumElements = VT->getNumElements();
  6163. QualType EltTy = VT->getElementType();
  6164. SmallVector<APValue, 4> Elements;
  6165. // The number of initializers can be less than the number of
  6166. // vector elements. For OpenCL, this can be due to nested vector
  6167. // initialization. For GCC compatibility, missing trailing elements
  6168. // should be initialized with zeroes.
  6169. unsigned CountInits = 0, CountElts = 0;
  6170. while (CountElts < NumElements) {
  6171. // Handle nested vector initialization.
  6172. if (CountInits < NumInits
  6173. && E->getInit(CountInits)->getType()->isVectorType()) {
  6174. APValue v;
  6175. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  6176. return Error(E);
  6177. unsigned vlen = v.getVectorLength();
  6178. for (unsigned j = 0; j < vlen; j++)
  6179. Elements.push_back(v.getVectorElt(j));
  6180. CountElts += vlen;
  6181. } else if (EltTy->isIntegerType()) {
  6182. llvm::APSInt sInt(32);
  6183. if (CountInits < NumInits) {
  6184. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  6185. return false;
  6186. } else // trailing integer zero.
  6187. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  6188. Elements.push_back(APValue(sInt));
  6189. CountElts++;
  6190. } else {
  6191. llvm::APFloat f(0.0);
  6192. if (CountInits < NumInits) {
  6193. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  6194. return false;
  6195. } else // trailing float zero.
  6196. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  6197. Elements.push_back(APValue(f));
  6198. CountElts++;
  6199. }
  6200. CountInits++;
  6201. }
  6202. return Success(Elements, E);
  6203. }
  6204. bool
  6205. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  6206. const VectorType *VT = E->getType()->getAs<VectorType>();
  6207. QualType EltTy = VT->getElementType();
  6208. APValue ZeroElement;
  6209. if (EltTy->isIntegerType())
  6210. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  6211. else
  6212. ZeroElement =
  6213. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  6214. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  6215. return Success(Elements, E);
  6216. }
  6217. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6218. VisitIgnoredValue(E->getSubExpr());
  6219. return ZeroInitialization(E);
  6220. }
  6221. //===----------------------------------------------------------------------===//
  6222. // Array Evaluation
  6223. //===----------------------------------------------------------------------===//
  6224. namespace {
  6225. class ArrayExprEvaluator
  6226. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  6227. const LValue &This;
  6228. APValue &Result;
  6229. public:
  6230. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  6231. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  6232. bool Success(const APValue &V, const Expr *E) {
  6233. assert((V.isArray() || V.isLValue()) &&
  6234. "expected array or string literal");
  6235. Result = V;
  6236. return true;
  6237. }
  6238. bool ZeroInitialization(const Expr *E) {
  6239. const ConstantArrayType *CAT =
  6240. Info.Ctx.getAsConstantArrayType(E->getType());
  6241. if (!CAT)
  6242. return Error(E);
  6243. Result = APValue(APValue::UninitArray(), 0,
  6244. CAT->getSize().getZExtValue());
  6245. if (!Result.hasArrayFiller()) return true;
  6246. // Zero-initialize all elements.
  6247. LValue Subobject = This;
  6248. Subobject.addArray(Info, E, CAT);
  6249. ImplicitValueInitExpr VIE(CAT->getElementType());
  6250. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  6251. }
  6252. bool VisitCallExpr(const CallExpr *E) {
  6253. return handleCallExpr(E, Result, &This);
  6254. }
  6255. bool VisitInitListExpr(const InitListExpr *E);
  6256. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  6257. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  6258. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  6259. const LValue &Subobject,
  6260. APValue *Value, QualType Type);
  6261. };
  6262. } // end anonymous namespace
  6263. static bool EvaluateArray(const Expr *E, const LValue &This,
  6264. APValue &Result, EvalInfo &Info) {
  6265. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  6266. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  6267. }
  6268. // Return true iff the given array filler may depend on the element index.
  6269. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  6270. // For now, just whitelist non-class value-initialization and initialization
  6271. // lists comprised of them.
  6272. if (isa<ImplicitValueInitExpr>(FillerExpr))
  6273. return false;
  6274. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  6275. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  6276. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  6277. return true;
  6278. }
  6279. return false;
  6280. }
  6281. return true;
  6282. }
  6283. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6284. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  6285. if (!CAT)
  6286. return Error(E);
  6287. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  6288. // an appropriately-typed string literal enclosed in braces.
  6289. if (E->isStringLiteralInit()) {
  6290. LValue LV;
  6291. if (!EvaluateLValue(E->getInit(0), LV, Info))
  6292. return false;
  6293. APValue Val;
  6294. LV.moveInto(Val);
  6295. return Success(Val, E);
  6296. }
  6297. bool Success = true;
  6298. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  6299. "zero-initialized array shouldn't have any initialized elts");
  6300. APValue Filler;
  6301. if (Result.isArray() && Result.hasArrayFiller())
  6302. Filler = Result.getArrayFiller();
  6303. unsigned NumEltsToInit = E->getNumInits();
  6304. unsigned NumElts = CAT->getSize().getZExtValue();
  6305. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  6306. // If the initializer might depend on the array index, run it for each
  6307. // array element.
  6308. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  6309. NumEltsToInit = NumElts;
  6310. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  6311. << NumEltsToInit << ".\n");
  6312. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  6313. // If the array was previously zero-initialized, preserve the
  6314. // zero-initialized values.
  6315. if (!Filler.isUninit()) {
  6316. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  6317. Result.getArrayInitializedElt(I) = Filler;
  6318. if (Result.hasArrayFiller())
  6319. Result.getArrayFiller() = Filler;
  6320. }
  6321. LValue Subobject = This;
  6322. Subobject.addArray(Info, E, CAT);
  6323. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  6324. const Expr *Init =
  6325. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  6326. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6327. Info, Subobject, Init) ||
  6328. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  6329. CAT->getElementType(), 1)) {
  6330. if (!Info.noteFailure())
  6331. return false;
  6332. Success = false;
  6333. }
  6334. }
  6335. if (!Result.hasArrayFiller())
  6336. return Success;
  6337. // If we get here, we have a trivial filler, which we can just evaluate
  6338. // once and splat over the rest of the array elements.
  6339. assert(FillerExpr && "no array filler for incomplete init list");
  6340. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  6341. FillerExpr) && Success;
  6342. }
  6343. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  6344. if (E->getCommonExpr() &&
  6345. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  6346. Info, E->getCommonExpr()->getSourceExpr()))
  6347. return false;
  6348. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  6349. uint64_t Elements = CAT->getSize().getZExtValue();
  6350. Result = APValue(APValue::UninitArray(), Elements, Elements);
  6351. LValue Subobject = This;
  6352. Subobject.addArray(Info, E, CAT);
  6353. bool Success = true;
  6354. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  6355. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6356. Info, Subobject, E->getSubExpr()) ||
  6357. !HandleLValueArrayAdjustment(Info, E, Subobject,
  6358. CAT->getElementType(), 1)) {
  6359. if (!Info.noteFailure())
  6360. return false;
  6361. Success = false;
  6362. }
  6363. }
  6364. return Success;
  6365. }
  6366. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6367. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  6368. }
  6369. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6370. const LValue &Subobject,
  6371. APValue *Value,
  6372. QualType Type) {
  6373. bool HadZeroInit = !Value->isUninit();
  6374. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  6375. unsigned N = CAT->getSize().getZExtValue();
  6376. // Preserve the array filler if we had prior zero-initialization.
  6377. APValue Filler =
  6378. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  6379. : APValue();
  6380. *Value = APValue(APValue::UninitArray(), N, N);
  6381. if (HadZeroInit)
  6382. for (unsigned I = 0; I != N; ++I)
  6383. Value->getArrayInitializedElt(I) = Filler;
  6384. // Initialize the elements.
  6385. LValue ArrayElt = Subobject;
  6386. ArrayElt.addArray(Info, E, CAT);
  6387. for (unsigned I = 0; I != N; ++I)
  6388. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  6389. CAT->getElementType()) ||
  6390. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  6391. CAT->getElementType(), 1))
  6392. return false;
  6393. return true;
  6394. }
  6395. if (!Type->isRecordType())
  6396. return Error(E);
  6397. return RecordExprEvaluator(Info, Subobject, *Value)
  6398. .VisitCXXConstructExpr(E, Type);
  6399. }
  6400. //===----------------------------------------------------------------------===//
  6401. // Integer Evaluation
  6402. //
  6403. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  6404. // types and back in constant folding. Integer values are thus represented
  6405. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  6406. //===----------------------------------------------------------------------===//
  6407. namespace {
  6408. class IntExprEvaluator
  6409. : public ExprEvaluatorBase<IntExprEvaluator> {
  6410. APValue &Result;
  6411. public:
  6412. IntExprEvaluator(EvalInfo &info, APValue &result)
  6413. : ExprEvaluatorBaseTy(info), Result(result) {}
  6414. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6415. assert(E->getType()->isIntegralOrEnumerationType() &&
  6416. "Invalid evaluation result.");
  6417. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  6418. "Invalid evaluation result.");
  6419. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6420. "Invalid evaluation result.");
  6421. Result = APValue(SI);
  6422. return true;
  6423. }
  6424. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6425. return Success(SI, E, Result);
  6426. }
  6427. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6428. assert(E->getType()->isIntegralOrEnumerationType() &&
  6429. "Invalid evaluation result.");
  6430. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6431. "Invalid evaluation result.");
  6432. Result = APValue(APSInt(I));
  6433. Result.getInt().setIsUnsigned(
  6434. E->getType()->isUnsignedIntegerOrEnumerationType());
  6435. return true;
  6436. }
  6437. bool Success(const llvm::APInt &I, const Expr *E) {
  6438. return Success(I, E, Result);
  6439. }
  6440. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6441. assert(E->getType()->isIntegralOrEnumerationType() &&
  6442. "Invalid evaluation result.");
  6443. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6444. return true;
  6445. }
  6446. bool Success(uint64_t Value, const Expr *E) {
  6447. return Success(Value, E, Result);
  6448. }
  6449. bool Success(CharUnits Size, const Expr *E) {
  6450. return Success(Size.getQuantity(), E);
  6451. }
  6452. bool Success(const APValue &V, const Expr *E) {
  6453. if (V.isLValue() || V.isAddrLabelDiff()) {
  6454. Result = V;
  6455. return true;
  6456. }
  6457. return Success(V.getInt(), E);
  6458. }
  6459. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6460. //===--------------------------------------------------------------------===//
  6461. // Visitor Methods
  6462. //===--------------------------------------------------------------------===//
  6463. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  6464. return Success(E->getValue(), E);
  6465. }
  6466. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  6467. return Success(E->getValue(), E);
  6468. }
  6469. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  6470. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  6471. if (CheckReferencedDecl(E, E->getDecl()))
  6472. return true;
  6473. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  6474. }
  6475. bool VisitMemberExpr(const MemberExpr *E) {
  6476. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  6477. VisitIgnoredBaseExpression(E->getBase());
  6478. return true;
  6479. }
  6480. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  6481. }
  6482. bool VisitCallExpr(const CallExpr *E);
  6483. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6484. bool VisitBinaryOperator(const BinaryOperator *E);
  6485. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  6486. bool VisitUnaryOperator(const UnaryOperator *E);
  6487. bool VisitCastExpr(const CastExpr* E);
  6488. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  6489. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  6490. return Success(E->getValue(), E);
  6491. }
  6492. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  6493. return Success(E->getValue(), E);
  6494. }
  6495. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  6496. if (Info.ArrayInitIndex == uint64_t(-1)) {
  6497. // We were asked to evaluate this subexpression independent of the
  6498. // enclosing ArrayInitLoopExpr. We can't do that.
  6499. Info.FFDiag(E);
  6500. return false;
  6501. }
  6502. return Success(Info.ArrayInitIndex, E);
  6503. }
  6504. // Note, GNU defines __null as an integer, not a pointer.
  6505. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  6506. return ZeroInitialization(E);
  6507. }
  6508. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  6509. return Success(E->getValue(), E);
  6510. }
  6511. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  6512. return Success(E->getValue(), E);
  6513. }
  6514. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  6515. return Success(E->getValue(), E);
  6516. }
  6517. bool VisitUnaryReal(const UnaryOperator *E);
  6518. bool VisitUnaryImag(const UnaryOperator *E);
  6519. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  6520. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  6521. // FIXME: Missing: array subscript of vector, member of vector
  6522. };
  6523. class FixedPointExprEvaluator
  6524. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  6525. APValue &Result;
  6526. public:
  6527. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  6528. : ExprEvaluatorBaseTy(info), Result(result) {}
  6529. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6530. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6531. assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
  6532. "Invalid evaluation result.");
  6533. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6534. "Invalid evaluation result.");
  6535. Result = APValue(SI);
  6536. return true;
  6537. }
  6538. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6539. return Success(SI, E, Result);
  6540. }
  6541. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6542. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6543. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6544. "Invalid evaluation result.");
  6545. Result = APValue(APSInt(I));
  6546. Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
  6547. return true;
  6548. }
  6549. bool Success(const llvm::APInt &I, const Expr *E) {
  6550. return Success(I, E, Result);
  6551. }
  6552. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6553. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6554. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6555. return true;
  6556. }
  6557. bool Success(uint64_t Value, const Expr *E) {
  6558. return Success(Value, E, Result);
  6559. }
  6560. bool Success(CharUnits Size, const Expr *E) {
  6561. return Success(Size.getQuantity(), E);
  6562. }
  6563. bool Success(const APValue &V, const Expr *E) {
  6564. if (V.isLValue() || V.isAddrLabelDiff()) {
  6565. Result = V;
  6566. return true;
  6567. }
  6568. return Success(V.getInt(), E);
  6569. }
  6570. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6571. //===--------------------------------------------------------------------===//
  6572. // Visitor Methods
  6573. //===--------------------------------------------------------------------===//
  6574. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  6575. return Success(E->getValue(), E);
  6576. }
  6577. bool VisitUnaryOperator(const UnaryOperator *E);
  6578. };
  6579. } // end anonymous namespace
  6580. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  6581. /// produce either the integer value or a pointer.
  6582. ///
  6583. /// GCC has a heinous extension which folds casts between pointer types and
  6584. /// pointer-sized integral types. We support this by allowing the evaluation of
  6585. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  6586. /// Some simple arithmetic on such values is supported (they are treated much
  6587. /// like char*).
  6588. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  6589. EvalInfo &Info) {
  6590. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  6591. return IntExprEvaluator(Info, Result).Visit(E);
  6592. }
  6593. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  6594. APValue Val;
  6595. if (!EvaluateIntegerOrLValue(E, Val, Info))
  6596. return false;
  6597. if (!Val.isInt()) {
  6598. // FIXME: It would be better to produce the diagnostic for casting
  6599. // a pointer to an integer.
  6600. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6601. return false;
  6602. }
  6603. Result = Val.getInt();
  6604. return true;
  6605. }
  6606. /// Check whether the given declaration can be directly converted to an integral
  6607. /// rvalue. If not, no diagnostic is produced; there are other things we can
  6608. /// try.
  6609. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  6610. // Enums are integer constant exprs.
  6611. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  6612. // Check for signedness/width mismatches between E type and ECD value.
  6613. bool SameSign = (ECD->getInitVal().isSigned()
  6614. == E->getType()->isSignedIntegerOrEnumerationType());
  6615. bool SameWidth = (ECD->getInitVal().getBitWidth()
  6616. == Info.Ctx.getIntWidth(E->getType()));
  6617. if (SameSign && SameWidth)
  6618. return Success(ECD->getInitVal(), E);
  6619. else {
  6620. // Get rid of mismatch (otherwise Success assertions will fail)
  6621. // by computing a new value matching the type of E.
  6622. llvm::APSInt Val = ECD->getInitVal();
  6623. if (!SameSign)
  6624. Val.setIsSigned(!ECD->getInitVal().isSigned());
  6625. if (!SameWidth)
  6626. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  6627. return Success(Val, E);
  6628. }
  6629. }
  6630. return false;
  6631. }
  6632. /// Values returned by __builtin_classify_type, chosen to match the values
  6633. /// produced by GCC's builtin.
  6634. enum class GCCTypeClass {
  6635. None = -1,
  6636. Void = 0,
  6637. Integer = 1,
  6638. // GCC reserves 2 for character types, but instead classifies them as
  6639. // integers.
  6640. Enum = 3,
  6641. Bool = 4,
  6642. Pointer = 5,
  6643. // GCC reserves 6 for references, but appears to never use it (because
  6644. // expressions never have reference type, presumably).
  6645. PointerToDataMember = 7,
  6646. RealFloat = 8,
  6647. Complex = 9,
  6648. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  6649. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6650. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  6651. // uses 12 for that purpose, same as for a class or struct. Maybe it
  6652. // internally implements a pointer to member as a struct? Who knows.
  6653. PointerToMemberFunction = 12, // Not a bug, see above.
  6654. ClassOrStruct = 12,
  6655. Union = 13,
  6656. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  6657. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6658. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  6659. // literals.
  6660. };
  6661. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6662. /// as GCC.
  6663. static GCCTypeClass
  6664. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  6665. assert(!T->isDependentType() && "unexpected dependent type");
  6666. QualType CanTy = T.getCanonicalType();
  6667. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  6668. switch (CanTy->getTypeClass()) {
  6669. #define TYPE(ID, BASE)
  6670. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6671. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  6672. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6673. #include "clang/AST/TypeNodes.def"
  6674. case Type::Auto:
  6675. case Type::DeducedTemplateSpecialization:
  6676. llvm_unreachable("unexpected non-canonical or dependent type");
  6677. case Type::Builtin:
  6678. switch (BT->getKind()) {
  6679. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  6680. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  6681. case BuiltinType::ID: return GCCTypeClass::Integer;
  6682. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  6683. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  6684. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  6685. case BuiltinType::ID: break;
  6686. #include "clang/AST/BuiltinTypes.def"
  6687. case BuiltinType::Void:
  6688. return GCCTypeClass::Void;
  6689. case BuiltinType::Bool:
  6690. return GCCTypeClass::Bool;
  6691. case BuiltinType::Char_U:
  6692. case BuiltinType::UChar:
  6693. case BuiltinType::WChar_U:
  6694. case BuiltinType::Char8:
  6695. case BuiltinType::Char16:
  6696. case BuiltinType::Char32:
  6697. case BuiltinType::UShort:
  6698. case BuiltinType::UInt:
  6699. case BuiltinType::ULong:
  6700. case BuiltinType::ULongLong:
  6701. case BuiltinType::UInt128:
  6702. return GCCTypeClass::Integer;
  6703. case BuiltinType::UShortAccum:
  6704. case BuiltinType::UAccum:
  6705. case BuiltinType::ULongAccum:
  6706. case BuiltinType::UShortFract:
  6707. case BuiltinType::UFract:
  6708. case BuiltinType::ULongFract:
  6709. case BuiltinType::SatUShortAccum:
  6710. case BuiltinType::SatUAccum:
  6711. case BuiltinType::SatULongAccum:
  6712. case BuiltinType::SatUShortFract:
  6713. case BuiltinType::SatUFract:
  6714. case BuiltinType::SatULongFract:
  6715. return GCCTypeClass::None;
  6716. case BuiltinType::NullPtr:
  6717. case BuiltinType::ObjCId:
  6718. case BuiltinType::ObjCClass:
  6719. case BuiltinType::ObjCSel:
  6720. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6721. case BuiltinType::Id:
  6722. #include "clang/Basic/OpenCLImageTypes.def"
  6723. case BuiltinType::OCLSampler:
  6724. case BuiltinType::OCLEvent:
  6725. case BuiltinType::OCLClkEvent:
  6726. case BuiltinType::OCLQueue:
  6727. case BuiltinType::OCLReserveID:
  6728. return GCCTypeClass::None;
  6729. case BuiltinType::Dependent:
  6730. llvm_unreachable("unexpected dependent type");
  6731. };
  6732. llvm_unreachable("unexpected placeholder type");
  6733. case Type::Enum:
  6734. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  6735. case Type::Pointer:
  6736. case Type::ConstantArray:
  6737. case Type::VariableArray:
  6738. case Type::IncompleteArray:
  6739. case Type::FunctionNoProto:
  6740. case Type::FunctionProto:
  6741. return GCCTypeClass::Pointer;
  6742. case Type::MemberPointer:
  6743. return CanTy->isMemberDataPointerType()
  6744. ? GCCTypeClass::PointerToDataMember
  6745. : GCCTypeClass::PointerToMemberFunction;
  6746. case Type::Complex:
  6747. return GCCTypeClass::Complex;
  6748. case Type::Record:
  6749. return CanTy->isUnionType() ? GCCTypeClass::Union
  6750. : GCCTypeClass::ClassOrStruct;
  6751. case Type::Atomic:
  6752. // GCC classifies _Atomic T the same as T.
  6753. return EvaluateBuiltinClassifyType(
  6754. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  6755. case Type::BlockPointer:
  6756. case Type::Vector:
  6757. case Type::ExtVector:
  6758. case Type::ObjCObject:
  6759. case Type::ObjCInterface:
  6760. case Type::ObjCObjectPointer:
  6761. case Type::Pipe:
  6762. // GCC classifies vectors as None. We follow its lead and classify all
  6763. // other types that don't fit into the regular classification the same way.
  6764. return GCCTypeClass::None;
  6765. case Type::LValueReference:
  6766. case Type::RValueReference:
  6767. llvm_unreachable("invalid type for expression");
  6768. }
  6769. llvm_unreachable("unexpected type class");
  6770. }
  6771. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6772. /// as GCC.
  6773. static GCCTypeClass
  6774. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  6775. // If no argument was supplied, default to None. This isn't
  6776. // ideal, however it is what gcc does.
  6777. if (E->getNumArgs() == 0)
  6778. return GCCTypeClass::None;
  6779. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  6780. // being an ICE, but still folds it to a constant using the type of the first
  6781. // argument.
  6782. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  6783. }
  6784. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  6785. /// __builtin_constant_p when applied to the given lvalue.
  6786. ///
  6787. /// An lvalue is only "constant" if it is a pointer or reference to the first
  6788. /// character of a string literal.
  6789. template<typename LValue>
  6790. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  6791. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  6792. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  6793. }
  6794. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  6795. /// GCC as we can manage.
  6796. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  6797. QualType ArgType = Arg->getType();
  6798. // __builtin_constant_p always has one operand. The rules which gcc follows
  6799. // are not precisely documented, but are as follows:
  6800. //
  6801. // - If the operand is of integral, floating, complex or enumeration type,
  6802. // and can be folded to a known value of that type, it returns 1.
  6803. // - If the operand and can be folded to a pointer to the first character
  6804. // of a string literal (or such a pointer cast to an integral type), it
  6805. // returns 1.
  6806. //
  6807. // Otherwise, it returns 0.
  6808. //
  6809. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  6810. // its support for this does not currently work.
  6811. if (ArgType->isIntegralOrEnumerationType()) {
  6812. Expr::EvalResult Result;
  6813. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  6814. return false;
  6815. APValue &V = Result.Val;
  6816. if (V.getKind() == APValue::Int)
  6817. return true;
  6818. if (V.getKind() == APValue::LValue)
  6819. return EvaluateBuiltinConstantPForLValue(V);
  6820. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  6821. return Arg->isEvaluatable(Ctx);
  6822. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  6823. LValue LV;
  6824. Expr::EvalStatus Status;
  6825. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  6826. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  6827. : EvaluatePointer(Arg, LV, Info)) &&
  6828. !Status.HasSideEffects)
  6829. return EvaluateBuiltinConstantPForLValue(LV);
  6830. }
  6831. // Anything else isn't considered to be sufficiently constant.
  6832. return false;
  6833. }
  6834. /// Retrieves the "underlying object type" of the given expression,
  6835. /// as used by __builtin_object_size.
  6836. static QualType getObjectType(APValue::LValueBase B) {
  6837. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  6838. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  6839. return VD->getType();
  6840. } else if (const Expr *E = B.get<const Expr*>()) {
  6841. if (isa<CompoundLiteralExpr>(E))
  6842. return E->getType();
  6843. }
  6844. return QualType();
  6845. }
  6846. /// A more selective version of E->IgnoreParenCasts for
  6847. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  6848. /// to change the type of E.
  6849. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  6850. ///
  6851. /// Always returns an RValue with a pointer representation.
  6852. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  6853. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6854. auto *NoParens = E->IgnoreParens();
  6855. auto *Cast = dyn_cast<CastExpr>(NoParens);
  6856. if (Cast == nullptr)
  6857. return NoParens;
  6858. // We only conservatively allow a few kinds of casts, because this code is
  6859. // inherently a simple solution that seeks to support the common case.
  6860. auto CastKind = Cast->getCastKind();
  6861. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  6862. CastKind != CK_AddressSpaceConversion)
  6863. return NoParens;
  6864. auto *SubExpr = Cast->getSubExpr();
  6865. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  6866. return NoParens;
  6867. return ignorePointerCastsAndParens(SubExpr);
  6868. }
  6869. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  6870. /// record layout. e.g.
  6871. /// struct { struct { int a, b; } fst, snd; } obj;
  6872. /// obj.fst // no
  6873. /// obj.snd // yes
  6874. /// obj.fst.a // no
  6875. /// obj.fst.b // no
  6876. /// obj.snd.a // no
  6877. /// obj.snd.b // yes
  6878. ///
  6879. /// Please note: this function is specialized for how __builtin_object_size
  6880. /// views "objects".
  6881. ///
  6882. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  6883. /// correct result, it will always return true.
  6884. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  6885. assert(!LVal.Designator.Invalid);
  6886. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  6887. const RecordDecl *Parent = FD->getParent();
  6888. Invalid = Parent->isInvalidDecl();
  6889. if (Invalid || Parent->isUnion())
  6890. return true;
  6891. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  6892. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  6893. };
  6894. auto &Base = LVal.getLValueBase();
  6895. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  6896. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  6897. bool Invalid;
  6898. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6899. return Invalid;
  6900. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  6901. for (auto *FD : IFD->chain()) {
  6902. bool Invalid;
  6903. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  6904. return Invalid;
  6905. }
  6906. }
  6907. }
  6908. unsigned I = 0;
  6909. QualType BaseType = getType(Base);
  6910. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  6911. // If we don't know the array bound, conservatively assume we're looking at
  6912. // the final array element.
  6913. ++I;
  6914. if (BaseType->isIncompleteArrayType())
  6915. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  6916. else
  6917. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  6918. }
  6919. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  6920. const auto &Entry = LVal.Designator.Entries[I];
  6921. if (BaseType->isArrayType()) {
  6922. // Because __builtin_object_size treats arrays as objects, we can ignore
  6923. // the index iff this is the last array in the Designator.
  6924. if (I + 1 == E)
  6925. return true;
  6926. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  6927. uint64_t Index = Entry.ArrayIndex;
  6928. if (Index + 1 != CAT->getSize())
  6929. return false;
  6930. BaseType = CAT->getElementType();
  6931. } else if (BaseType->isAnyComplexType()) {
  6932. const auto *CT = BaseType->castAs<ComplexType>();
  6933. uint64_t Index = Entry.ArrayIndex;
  6934. if (Index != 1)
  6935. return false;
  6936. BaseType = CT->getElementType();
  6937. } else if (auto *FD = getAsField(Entry)) {
  6938. bool Invalid;
  6939. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6940. return Invalid;
  6941. BaseType = FD->getType();
  6942. } else {
  6943. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  6944. return false;
  6945. }
  6946. }
  6947. return true;
  6948. }
  6949. /// Tests to see if the LValue has a user-specified designator (that isn't
  6950. /// necessarily valid). Note that this always returns 'true' if the LValue has
  6951. /// an unsized array as its first designator entry, because there's currently no
  6952. /// way to tell if the user typed *foo or foo[0].
  6953. static bool refersToCompleteObject(const LValue &LVal) {
  6954. if (LVal.Designator.Invalid)
  6955. return false;
  6956. if (!LVal.Designator.Entries.empty())
  6957. return LVal.Designator.isMostDerivedAnUnsizedArray();
  6958. if (!LVal.InvalidBase)
  6959. return true;
  6960. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  6961. // the LValueBase.
  6962. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  6963. return !E || !isa<MemberExpr>(E);
  6964. }
  6965. /// Attempts to detect a user writing into a piece of memory that's impossible
  6966. /// to figure out the size of by just using types.
  6967. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  6968. const SubobjectDesignator &Designator = LVal.Designator;
  6969. // Notes:
  6970. // - Users can only write off of the end when we have an invalid base. Invalid
  6971. // bases imply we don't know where the memory came from.
  6972. // - We used to be a bit more aggressive here; we'd only be conservative if
  6973. // the array at the end was flexible, or if it had 0 or 1 elements. This
  6974. // broke some common standard library extensions (PR30346), but was
  6975. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  6976. // with some sort of whitelist. OTOH, it seems that GCC is always
  6977. // conservative with the last element in structs (if it's an array), so our
  6978. // current behavior is more compatible than a whitelisting approach would
  6979. // be.
  6980. return LVal.InvalidBase &&
  6981. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  6982. Designator.MostDerivedIsArrayElement &&
  6983. isDesignatorAtObjectEnd(Ctx, LVal);
  6984. }
  6985. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  6986. /// Fails if the conversion would cause loss of precision.
  6987. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  6988. CharUnits &Result) {
  6989. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  6990. if (Int.ugt(CharUnitsMax))
  6991. return false;
  6992. Result = CharUnits::fromQuantity(Int.getZExtValue());
  6993. return true;
  6994. }
  6995. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  6996. /// determine how many bytes exist from the beginning of the object to either
  6997. /// the end of the current subobject, or the end of the object itself, depending
  6998. /// on what the LValue looks like + the value of Type.
  6999. ///
  7000. /// If this returns false, the value of Result is undefined.
  7001. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  7002. unsigned Type, const LValue &LVal,
  7003. CharUnits &EndOffset) {
  7004. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  7005. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  7006. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  7007. return false;
  7008. return HandleSizeof(Info, ExprLoc, Ty, Result);
  7009. };
  7010. // We want to evaluate the size of the entire object. This is a valid fallback
  7011. // for when Type=1 and the designator is invalid, because we're asked for an
  7012. // upper-bound.
  7013. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  7014. // Type=3 wants a lower bound, so we can't fall back to this.
  7015. if (Type == 3 && !DetermineForCompleteObject)
  7016. return false;
  7017. llvm::APInt APEndOffset;
  7018. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7019. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7020. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7021. if (LVal.InvalidBase)
  7022. return false;
  7023. QualType BaseTy = getObjectType(LVal.getLValueBase());
  7024. return CheckedHandleSizeof(BaseTy, EndOffset);
  7025. }
  7026. // We want to evaluate the size of a subobject.
  7027. const SubobjectDesignator &Designator = LVal.Designator;
  7028. // The following is a moderately common idiom in C:
  7029. //
  7030. // struct Foo { int a; char c[1]; };
  7031. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  7032. // strcpy(&F->c[0], Bar);
  7033. //
  7034. // In order to not break too much legacy code, we need to support it.
  7035. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  7036. // If we can resolve this to an alloc_size call, we can hand that back,
  7037. // because we know for certain how many bytes there are to write to.
  7038. llvm::APInt APEndOffset;
  7039. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7040. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7041. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7042. // If we cannot determine the size of the initial allocation, then we can't
  7043. // given an accurate upper-bound. However, we are still able to give
  7044. // conservative lower-bounds for Type=3.
  7045. if (Type == 1)
  7046. return false;
  7047. }
  7048. CharUnits BytesPerElem;
  7049. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  7050. return false;
  7051. // According to the GCC documentation, we want the size of the subobject
  7052. // denoted by the pointer. But that's not quite right -- what we actually
  7053. // want is the size of the immediately-enclosing array, if there is one.
  7054. int64_t ElemsRemaining;
  7055. if (Designator.MostDerivedIsArrayElement &&
  7056. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  7057. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  7058. uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
  7059. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  7060. } else {
  7061. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  7062. }
  7063. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  7064. return true;
  7065. }
  7066. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  7067. /// returns true and stores the result in @p Size.
  7068. ///
  7069. /// If @p WasError is non-null, this will report whether the failure to evaluate
  7070. /// is to be treated as an Error in IntExprEvaluator.
  7071. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  7072. EvalInfo &Info, uint64_t &Size) {
  7073. // Determine the denoted object.
  7074. LValue LVal;
  7075. {
  7076. // The operand of __builtin_object_size is never evaluated for side-effects.
  7077. // If there are any, but we can determine the pointed-to object anyway, then
  7078. // ignore the side-effects.
  7079. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7080. IgnoreSideEffectsRAII Fold(Info);
  7081. if (E->isGLValue()) {
  7082. // It's possible for us to be given GLValues if we're called via
  7083. // Expr::tryEvaluateObjectSize.
  7084. APValue RVal;
  7085. if (!EvaluateAsRValue(Info, E, RVal))
  7086. return false;
  7087. LVal.setFrom(Info.Ctx, RVal);
  7088. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  7089. /*InvalidBaseOK=*/true))
  7090. return false;
  7091. }
  7092. // If we point to before the start of the object, there are no accessible
  7093. // bytes.
  7094. if (LVal.getLValueOffset().isNegative()) {
  7095. Size = 0;
  7096. return true;
  7097. }
  7098. CharUnits EndOffset;
  7099. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  7100. return false;
  7101. // If we've fallen outside of the end offset, just pretend there's nothing to
  7102. // write to/read from.
  7103. if (EndOffset <= LVal.getLValueOffset())
  7104. Size = 0;
  7105. else
  7106. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  7107. return true;
  7108. }
  7109. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7110. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7111. return VisitBuiltinCallExpr(E, BuiltinOp);
  7112. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7113. }
  7114. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7115. unsigned BuiltinOp) {
  7116. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  7117. default:
  7118. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7119. case Builtin::BI__builtin_object_size: {
  7120. // The type was checked when we built the expression.
  7121. unsigned Type =
  7122. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7123. assert(Type <= 3 && "unexpected type");
  7124. uint64_t Size;
  7125. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  7126. return Success(Size, E);
  7127. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  7128. return Success((Type & 2) ? 0 : -1, E);
  7129. // Expression had no side effects, but we couldn't statically determine the
  7130. // size of the referenced object.
  7131. switch (Info.EvalMode) {
  7132. case EvalInfo::EM_ConstantExpression:
  7133. case EvalInfo::EM_PotentialConstantExpression:
  7134. case EvalInfo::EM_ConstantFold:
  7135. case EvalInfo::EM_EvaluateForOverflow:
  7136. case EvalInfo::EM_IgnoreSideEffects:
  7137. // Leave it to IR generation.
  7138. return Error(E);
  7139. case EvalInfo::EM_ConstantExpressionUnevaluated:
  7140. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  7141. // Reduce it to a constant now.
  7142. return Success((Type & 2) ? 0 : -1, E);
  7143. }
  7144. llvm_unreachable("unexpected EvalMode");
  7145. }
  7146. case Builtin::BI__builtin_bswap16:
  7147. case Builtin::BI__builtin_bswap32:
  7148. case Builtin::BI__builtin_bswap64: {
  7149. APSInt Val;
  7150. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7151. return false;
  7152. return Success(Val.byteSwap(), E);
  7153. }
  7154. case Builtin::BI__builtin_classify_type:
  7155. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  7156. case Builtin::BI__builtin_clrsb:
  7157. case Builtin::BI__builtin_clrsbl:
  7158. case Builtin::BI__builtin_clrsbll: {
  7159. APSInt Val;
  7160. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7161. return false;
  7162. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  7163. }
  7164. case Builtin::BI__builtin_clz:
  7165. case Builtin::BI__builtin_clzl:
  7166. case Builtin::BI__builtin_clzll:
  7167. case Builtin::BI__builtin_clzs: {
  7168. APSInt Val;
  7169. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7170. return false;
  7171. if (!Val)
  7172. return Error(E);
  7173. return Success(Val.countLeadingZeros(), E);
  7174. }
  7175. case Builtin::BI__builtin_constant_p:
  7176. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  7177. case Builtin::BI__builtin_ctz:
  7178. case Builtin::BI__builtin_ctzl:
  7179. case Builtin::BI__builtin_ctzll:
  7180. case Builtin::BI__builtin_ctzs: {
  7181. APSInt Val;
  7182. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7183. return false;
  7184. if (!Val)
  7185. return Error(E);
  7186. return Success(Val.countTrailingZeros(), E);
  7187. }
  7188. case Builtin::BI__builtin_eh_return_data_regno: {
  7189. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7190. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  7191. return Success(Operand, E);
  7192. }
  7193. case Builtin::BI__builtin_expect:
  7194. return Visit(E->getArg(0));
  7195. case Builtin::BI__builtin_ffs:
  7196. case Builtin::BI__builtin_ffsl:
  7197. case Builtin::BI__builtin_ffsll: {
  7198. APSInt Val;
  7199. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7200. return false;
  7201. unsigned N = Val.countTrailingZeros();
  7202. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  7203. }
  7204. case Builtin::BI__builtin_fpclassify: {
  7205. APFloat Val(0.0);
  7206. if (!EvaluateFloat(E->getArg(5), Val, Info))
  7207. return false;
  7208. unsigned Arg;
  7209. switch (Val.getCategory()) {
  7210. case APFloat::fcNaN: Arg = 0; break;
  7211. case APFloat::fcInfinity: Arg = 1; break;
  7212. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  7213. case APFloat::fcZero: Arg = 4; break;
  7214. }
  7215. return Visit(E->getArg(Arg));
  7216. }
  7217. case Builtin::BI__builtin_isinf_sign: {
  7218. APFloat Val(0.0);
  7219. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7220. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  7221. }
  7222. case Builtin::BI__builtin_isinf: {
  7223. APFloat Val(0.0);
  7224. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7225. Success(Val.isInfinity() ? 1 : 0, E);
  7226. }
  7227. case Builtin::BI__builtin_isfinite: {
  7228. APFloat Val(0.0);
  7229. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7230. Success(Val.isFinite() ? 1 : 0, E);
  7231. }
  7232. case Builtin::BI__builtin_isnan: {
  7233. APFloat Val(0.0);
  7234. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7235. Success(Val.isNaN() ? 1 : 0, E);
  7236. }
  7237. case Builtin::BI__builtin_isnormal: {
  7238. APFloat Val(0.0);
  7239. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7240. Success(Val.isNormal() ? 1 : 0, E);
  7241. }
  7242. case Builtin::BI__builtin_parity:
  7243. case Builtin::BI__builtin_parityl:
  7244. case Builtin::BI__builtin_parityll: {
  7245. APSInt Val;
  7246. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7247. return false;
  7248. return Success(Val.countPopulation() % 2, E);
  7249. }
  7250. case Builtin::BI__builtin_popcount:
  7251. case Builtin::BI__builtin_popcountl:
  7252. case Builtin::BI__builtin_popcountll: {
  7253. APSInt Val;
  7254. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7255. return false;
  7256. return Success(Val.countPopulation(), E);
  7257. }
  7258. case Builtin::BIstrlen:
  7259. case Builtin::BIwcslen:
  7260. // A call to strlen is not a constant expression.
  7261. if (Info.getLangOpts().CPlusPlus11)
  7262. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7263. << /*isConstexpr*/0 << /*isConstructor*/0
  7264. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7265. else
  7266. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7267. LLVM_FALLTHROUGH;
  7268. case Builtin::BI__builtin_strlen:
  7269. case Builtin::BI__builtin_wcslen: {
  7270. // As an extension, we support __builtin_strlen() as a constant expression,
  7271. // and support folding strlen() to a constant.
  7272. LValue String;
  7273. if (!EvaluatePointer(E->getArg(0), String, Info))
  7274. return false;
  7275. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7276. // Fast path: if it's a string literal, search the string value.
  7277. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  7278. String.getLValueBase().dyn_cast<const Expr *>())) {
  7279. // The string literal may have embedded null characters. Find the first
  7280. // one and truncate there.
  7281. StringRef Str = S->getBytes();
  7282. int64_t Off = String.Offset.getQuantity();
  7283. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  7284. S->getCharByteWidth() == 1 &&
  7285. // FIXME: Add fast-path for wchar_t too.
  7286. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  7287. Str = Str.substr(Off);
  7288. StringRef::size_type Pos = Str.find(0);
  7289. if (Pos != StringRef::npos)
  7290. Str = Str.substr(0, Pos);
  7291. return Success(Str.size(), E);
  7292. }
  7293. // Fall through to slow path to issue appropriate diagnostic.
  7294. }
  7295. // Slow path: scan the bytes of the string looking for the terminating 0.
  7296. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  7297. APValue Char;
  7298. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  7299. !Char.isInt())
  7300. return false;
  7301. if (!Char.getInt())
  7302. return Success(Strlen, E);
  7303. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  7304. return false;
  7305. }
  7306. }
  7307. case Builtin::BIstrcmp:
  7308. case Builtin::BIwcscmp:
  7309. case Builtin::BIstrncmp:
  7310. case Builtin::BIwcsncmp:
  7311. case Builtin::BImemcmp:
  7312. case Builtin::BIwmemcmp:
  7313. // A call to strlen is not a constant expression.
  7314. if (Info.getLangOpts().CPlusPlus11)
  7315. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7316. << /*isConstexpr*/0 << /*isConstructor*/0
  7317. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7318. else
  7319. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7320. LLVM_FALLTHROUGH;
  7321. case Builtin::BI__builtin_strcmp:
  7322. case Builtin::BI__builtin_wcscmp:
  7323. case Builtin::BI__builtin_strncmp:
  7324. case Builtin::BI__builtin_wcsncmp:
  7325. case Builtin::BI__builtin_memcmp:
  7326. case Builtin::BI__builtin_wmemcmp: {
  7327. LValue String1, String2;
  7328. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  7329. !EvaluatePointer(E->getArg(1), String2, Info))
  7330. return false;
  7331. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7332. uint64_t MaxLength = uint64_t(-1);
  7333. if (BuiltinOp != Builtin::BIstrcmp &&
  7334. BuiltinOp != Builtin::BIwcscmp &&
  7335. BuiltinOp != Builtin::BI__builtin_strcmp &&
  7336. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  7337. APSInt N;
  7338. if (!EvaluateInteger(E->getArg(2), N, Info))
  7339. return false;
  7340. MaxLength = N.getExtValue();
  7341. }
  7342. bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
  7343. BuiltinOp != Builtin::BIwmemcmp &&
  7344. BuiltinOp != Builtin::BI__builtin_memcmp &&
  7345. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  7346. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  7347. BuiltinOp == Builtin::BIwcsncmp ||
  7348. BuiltinOp == Builtin::BIwmemcmp ||
  7349. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  7350. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  7351. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  7352. for (; MaxLength; --MaxLength) {
  7353. APValue Char1, Char2;
  7354. if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
  7355. !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
  7356. !Char1.isInt() || !Char2.isInt())
  7357. return false;
  7358. if (Char1.getInt() != Char2.getInt()) {
  7359. if (IsWide) // wmemcmp compares with wchar_t signedness.
  7360. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  7361. // memcmp always compares unsigned chars.
  7362. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  7363. }
  7364. if (StopAtNull && !Char1.getInt())
  7365. return Success(0, E);
  7366. assert(!(StopAtNull && !Char2.getInt()));
  7367. if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
  7368. !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
  7369. return false;
  7370. }
  7371. // We hit the strncmp / memcmp limit.
  7372. return Success(0, E);
  7373. }
  7374. case Builtin::BI__atomic_always_lock_free:
  7375. case Builtin::BI__atomic_is_lock_free:
  7376. case Builtin::BI__c11_atomic_is_lock_free: {
  7377. APSInt SizeVal;
  7378. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  7379. return false;
  7380. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  7381. // of two less than the maximum inline atomic width, we know it is
  7382. // lock-free. If the size isn't a power of two, or greater than the
  7383. // maximum alignment where we promote atomics, we know it is not lock-free
  7384. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  7385. // the answer can only be determined at runtime; for example, 16-byte
  7386. // atomics have lock-free implementations on some, but not all,
  7387. // x86-64 processors.
  7388. // Check power-of-two.
  7389. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  7390. if (Size.isPowerOfTwo()) {
  7391. // Check against inlining width.
  7392. unsigned InlineWidthBits =
  7393. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  7394. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  7395. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  7396. Size == CharUnits::One() ||
  7397. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  7398. Expr::NPC_NeverValueDependent))
  7399. // OK, we will inline appropriately-aligned operations of this size,
  7400. // and _Atomic(T) is appropriately-aligned.
  7401. return Success(1, E);
  7402. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  7403. castAs<PointerType>()->getPointeeType();
  7404. if (!PointeeType->isIncompleteType() &&
  7405. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  7406. // OK, we will inline operations on this object.
  7407. return Success(1, E);
  7408. }
  7409. }
  7410. }
  7411. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  7412. Success(0, E) : Error(E);
  7413. }
  7414. case Builtin::BIomp_is_initial_device:
  7415. // We can decide statically which value the runtime would return if called.
  7416. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  7417. case Builtin::BI__builtin_add_overflow:
  7418. case Builtin::BI__builtin_sub_overflow:
  7419. case Builtin::BI__builtin_mul_overflow:
  7420. case Builtin::BI__builtin_sadd_overflow:
  7421. case Builtin::BI__builtin_uadd_overflow:
  7422. case Builtin::BI__builtin_uaddl_overflow:
  7423. case Builtin::BI__builtin_uaddll_overflow:
  7424. case Builtin::BI__builtin_usub_overflow:
  7425. case Builtin::BI__builtin_usubl_overflow:
  7426. case Builtin::BI__builtin_usubll_overflow:
  7427. case Builtin::BI__builtin_umul_overflow:
  7428. case Builtin::BI__builtin_umull_overflow:
  7429. case Builtin::BI__builtin_umulll_overflow:
  7430. case Builtin::BI__builtin_saddl_overflow:
  7431. case Builtin::BI__builtin_saddll_overflow:
  7432. case Builtin::BI__builtin_ssub_overflow:
  7433. case Builtin::BI__builtin_ssubl_overflow:
  7434. case Builtin::BI__builtin_ssubll_overflow:
  7435. case Builtin::BI__builtin_smul_overflow:
  7436. case Builtin::BI__builtin_smull_overflow:
  7437. case Builtin::BI__builtin_smulll_overflow: {
  7438. LValue ResultLValue;
  7439. APSInt LHS, RHS;
  7440. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  7441. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  7442. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  7443. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  7444. return false;
  7445. APSInt Result;
  7446. bool DidOverflow = false;
  7447. // If the types don't have to match, enlarge all 3 to the largest of them.
  7448. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7449. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7450. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7451. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  7452. ResultType->isSignedIntegerOrEnumerationType();
  7453. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  7454. ResultType->isSignedIntegerOrEnumerationType();
  7455. uint64_t LHSSize = LHS.getBitWidth();
  7456. uint64_t RHSSize = RHS.getBitWidth();
  7457. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  7458. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  7459. // Add an additional bit if the signedness isn't uniformly agreed to. We
  7460. // could do this ONLY if there is a signed and an unsigned that both have
  7461. // MaxBits, but the code to check that is pretty nasty. The issue will be
  7462. // caught in the shrink-to-result later anyway.
  7463. if (IsSigned && !AllSigned)
  7464. ++MaxBits;
  7465. LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
  7466. !IsSigned);
  7467. RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
  7468. !IsSigned);
  7469. Result = APSInt(MaxBits, !IsSigned);
  7470. }
  7471. // Find largest int.
  7472. switch (BuiltinOp) {
  7473. default:
  7474. llvm_unreachable("Invalid value for BuiltinOp");
  7475. case Builtin::BI__builtin_add_overflow:
  7476. case Builtin::BI__builtin_sadd_overflow:
  7477. case Builtin::BI__builtin_saddl_overflow:
  7478. case Builtin::BI__builtin_saddll_overflow:
  7479. case Builtin::BI__builtin_uadd_overflow:
  7480. case Builtin::BI__builtin_uaddl_overflow:
  7481. case Builtin::BI__builtin_uaddll_overflow:
  7482. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  7483. : LHS.uadd_ov(RHS, DidOverflow);
  7484. break;
  7485. case Builtin::BI__builtin_sub_overflow:
  7486. case Builtin::BI__builtin_ssub_overflow:
  7487. case Builtin::BI__builtin_ssubl_overflow:
  7488. case Builtin::BI__builtin_ssubll_overflow:
  7489. case Builtin::BI__builtin_usub_overflow:
  7490. case Builtin::BI__builtin_usubl_overflow:
  7491. case Builtin::BI__builtin_usubll_overflow:
  7492. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  7493. : LHS.usub_ov(RHS, DidOverflow);
  7494. break;
  7495. case Builtin::BI__builtin_mul_overflow:
  7496. case Builtin::BI__builtin_smul_overflow:
  7497. case Builtin::BI__builtin_smull_overflow:
  7498. case Builtin::BI__builtin_smulll_overflow:
  7499. case Builtin::BI__builtin_umul_overflow:
  7500. case Builtin::BI__builtin_umull_overflow:
  7501. case Builtin::BI__builtin_umulll_overflow:
  7502. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  7503. : LHS.umul_ov(RHS, DidOverflow);
  7504. break;
  7505. }
  7506. // In the case where multiple sizes are allowed, truncate and see if
  7507. // the values are the same.
  7508. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7509. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7510. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7511. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  7512. // since it will give us the behavior of a TruncOrSelf in the case where
  7513. // its parameter <= its size. We previously set Result to be at least the
  7514. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  7515. // will work exactly like TruncOrSelf.
  7516. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  7517. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  7518. if (!APSInt::isSameValue(Temp, Result))
  7519. DidOverflow = true;
  7520. Result = Temp;
  7521. }
  7522. APValue APV{Result};
  7523. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  7524. return false;
  7525. return Success(DidOverflow, E);
  7526. }
  7527. }
  7528. }
  7529. /// Determine whether this is a pointer past the end of the complete
  7530. /// object referred to by the lvalue.
  7531. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  7532. const LValue &LV) {
  7533. // A null pointer can be viewed as being "past the end" but we don't
  7534. // choose to look at it that way here.
  7535. if (!LV.getLValueBase())
  7536. return false;
  7537. // If the designator is valid and refers to a subobject, we're not pointing
  7538. // past the end.
  7539. if (!LV.getLValueDesignator().Invalid &&
  7540. !LV.getLValueDesignator().isOnePastTheEnd())
  7541. return false;
  7542. // A pointer to an incomplete type might be past-the-end if the type's size is
  7543. // zero. We cannot tell because the type is incomplete.
  7544. QualType Ty = getType(LV.getLValueBase());
  7545. if (Ty->isIncompleteType())
  7546. return true;
  7547. // We're a past-the-end pointer if we point to the byte after the object,
  7548. // no matter what our type or path is.
  7549. auto Size = Ctx.getTypeSizeInChars(Ty);
  7550. return LV.getLValueOffset() == Size;
  7551. }
  7552. namespace {
  7553. /// Data recursive integer evaluator of certain binary operators.
  7554. ///
  7555. /// We use a data recursive algorithm for binary operators so that we are able
  7556. /// to handle extreme cases of chained binary operators without causing stack
  7557. /// overflow.
  7558. class DataRecursiveIntBinOpEvaluator {
  7559. struct EvalResult {
  7560. APValue Val;
  7561. bool Failed;
  7562. EvalResult() : Failed(false) { }
  7563. void swap(EvalResult &RHS) {
  7564. Val.swap(RHS.Val);
  7565. Failed = RHS.Failed;
  7566. RHS.Failed = false;
  7567. }
  7568. };
  7569. struct Job {
  7570. const Expr *E;
  7571. EvalResult LHSResult; // meaningful only for binary operator expression.
  7572. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  7573. Job() = default;
  7574. Job(Job &&) = default;
  7575. void startSpeculativeEval(EvalInfo &Info) {
  7576. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  7577. }
  7578. private:
  7579. SpeculativeEvaluationRAII SpecEvalRAII;
  7580. };
  7581. SmallVector<Job, 16> Queue;
  7582. IntExprEvaluator &IntEval;
  7583. EvalInfo &Info;
  7584. APValue &FinalResult;
  7585. public:
  7586. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  7587. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  7588. /// True if \param E is a binary operator that we are going to handle
  7589. /// data recursively.
  7590. /// We handle binary operators that are comma, logical, or that have operands
  7591. /// with integral or enumeration type.
  7592. static bool shouldEnqueue(const BinaryOperator *E) {
  7593. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  7594. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  7595. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7596. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7597. }
  7598. bool Traverse(const BinaryOperator *E) {
  7599. enqueue(E);
  7600. EvalResult PrevResult;
  7601. while (!Queue.empty())
  7602. process(PrevResult);
  7603. if (PrevResult.Failed) return false;
  7604. FinalResult.swap(PrevResult.Val);
  7605. return true;
  7606. }
  7607. private:
  7608. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  7609. return IntEval.Success(Value, E, Result);
  7610. }
  7611. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  7612. return IntEval.Success(Value, E, Result);
  7613. }
  7614. bool Error(const Expr *E) {
  7615. return IntEval.Error(E);
  7616. }
  7617. bool Error(const Expr *E, diag::kind D) {
  7618. return IntEval.Error(E, D);
  7619. }
  7620. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  7621. return Info.CCEDiag(E, D);
  7622. }
  7623. // Returns true if visiting the RHS is necessary, false otherwise.
  7624. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7625. bool &SuppressRHSDiags);
  7626. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7627. const BinaryOperator *E, APValue &Result);
  7628. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  7629. Result.Failed = !Evaluate(Result.Val, Info, E);
  7630. if (Result.Failed)
  7631. Result.Val = APValue();
  7632. }
  7633. void process(EvalResult &Result);
  7634. void enqueue(const Expr *E) {
  7635. E = E->IgnoreParens();
  7636. Queue.resize(Queue.size()+1);
  7637. Queue.back().E = E;
  7638. Queue.back().Kind = Job::AnyExprKind;
  7639. }
  7640. };
  7641. }
  7642. bool DataRecursiveIntBinOpEvaluator::
  7643. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7644. bool &SuppressRHSDiags) {
  7645. if (E->getOpcode() == BO_Comma) {
  7646. // Ignore LHS but note if we could not evaluate it.
  7647. if (LHSResult.Failed)
  7648. return Info.noteSideEffect();
  7649. return true;
  7650. }
  7651. if (E->isLogicalOp()) {
  7652. bool LHSAsBool;
  7653. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  7654. // We were able to evaluate the LHS, see if we can get away with not
  7655. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  7656. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  7657. Success(LHSAsBool, E, LHSResult.Val);
  7658. return false; // Ignore RHS
  7659. }
  7660. } else {
  7661. LHSResult.Failed = true;
  7662. // Since we weren't able to evaluate the left hand side, it
  7663. // might have had side effects.
  7664. if (!Info.noteSideEffect())
  7665. return false;
  7666. // We can't evaluate the LHS; however, sometimes the result
  7667. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7668. // Don't ignore RHS and suppress diagnostics from this arm.
  7669. SuppressRHSDiags = true;
  7670. }
  7671. return true;
  7672. }
  7673. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7674. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7675. if (LHSResult.Failed && !Info.noteFailure())
  7676. return false; // Ignore RHS;
  7677. return true;
  7678. }
  7679. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  7680. bool IsSub) {
  7681. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  7682. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  7683. // offsets.
  7684. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  7685. CharUnits &Offset = LVal.getLValueOffset();
  7686. uint64_t Offset64 = Offset.getQuantity();
  7687. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  7688. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  7689. : Offset64 + Index64);
  7690. }
  7691. bool DataRecursiveIntBinOpEvaluator::
  7692. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7693. const BinaryOperator *E, APValue &Result) {
  7694. if (E->getOpcode() == BO_Comma) {
  7695. if (RHSResult.Failed)
  7696. return false;
  7697. Result = RHSResult.Val;
  7698. return true;
  7699. }
  7700. if (E->isLogicalOp()) {
  7701. bool lhsResult, rhsResult;
  7702. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  7703. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  7704. if (LHSIsOK) {
  7705. if (RHSIsOK) {
  7706. if (E->getOpcode() == BO_LOr)
  7707. return Success(lhsResult || rhsResult, E, Result);
  7708. else
  7709. return Success(lhsResult && rhsResult, E, Result);
  7710. }
  7711. } else {
  7712. if (RHSIsOK) {
  7713. // We can't evaluate the LHS; however, sometimes the result
  7714. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7715. if (rhsResult == (E->getOpcode() == BO_LOr))
  7716. return Success(rhsResult, E, Result);
  7717. }
  7718. }
  7719. return false;
  7720. }
  7721. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7722. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7723. if (LHSResult.Failed || RHSResult.Failed)
  7724. return false;
  7725. const APValue &LHSVal = LHSResult.Val;
  7726. const APValue &RHSVal = RHSResult.Val;
  7727. // Handle cases like (unsigned long)&a + 4.
  7728. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  7729. Result = LHSVal;
  7730. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  7731. return true;
  7732. }
  7733. // Handle cases like 4 + (unsigned long)&a
  7734. if (E->getOpcode() == BO_Add &&
  7735. RHSVal.isLValue() && LHSVal.isInt()) {
  7736. Result = RHSVal;
  7737. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  7738. return true;
  7739. }
  7740. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  7741. // Handle (intptr_t)&&A - (intptr_t)&&B.
  7742. if (!LHSVal.getLValueOffset().isZero() ||
  7743. !RHSVal.getLValueOffset().isZero())
  7744. return false;
  7745. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  7746. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  7747. if (!LHSExpr || !RHSExpr)
  7748. return false;
  7749. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  7750. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  7751. if (!LHSAddrExpr || !RHSAddrExpr)
  7752. return false;
  7753. // Make sure both labels come from the same function.
  7754. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  7755. RHSAddrExpr->getLabel()->getDeclContext())
  7756. return false;
  7757. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  7758. return true;
  7759. }
  7760. // All the remaining cases expect both operands to be an integer
  7761. if (!LHSVal.isInt() || !RHSVal.isInt())
  7762. return Error(E);
  7763. // Set up the width and signedness manually, in case it can't be deduced
  7764. // from the operation we're performing.
  7765. // FIXME: Don't do this in the cases where we can deduce it.
  7766. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  7767. E->getType()->isUnsignedIntegerOrEnumerationType());
  7768. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  7769. RHSVal.getInt(), Value))
  7770. return false;
  7771. return Success(Value, E, Result);
  7772. }
  7773. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  7774. Job &job = Queue.back();
  7775. switch (job.Kind) {
  7776. case Job::AnyExprKind: {
  7777. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  7778. if (shouldEnqueue(Bop)) {
  7779. job.Kind = Job::BinOpKind;
  7780. enqueue(Bop->getLHS());
  7781. return;
  7782. }
  7783. }
  7784. EvaluateExpr(job.E, Result);
  7785. Queue.pop_back();
  7786. return;
  7787. }
  7788. case Job::BinOpKind: {
  7789. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7790. bool SuppressRHSDiags = false;
  7791. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  7792. Queue.pop_back();
  7793. return;
  7794. }
  7795. if (SuppressRHSDiags)
  7796. job.startSpeculativeEval(Info);
  7797. job.LHSResult.swap(Result);
  7798. job.Kind = Job::BinOpVisitedLHSKind;
  7799. enqueue(Bop->getRHS());
  7800. return;
  7801. }
  7802. case Job::BinOpVisitedLHSKind: {
  7803. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7804. EvalResult RHS;
  7805. RHS.swap(Result);
  7806. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  7807. Queue.pop_back();
  7808. return;
  7809. }
  7810. }
  7811. llvm_unreachable("Invalid Job::Kind!");
  7812. }
  7813. namespace {
  7814. /// Used when we determine that we should fail, but can keep evaluating prior to
  7815. /// noting that we had a failure.
  7816. class DelayedNoteFailureRAII {
  7817. EvalInfo &Info;
  7818. bool NoteFailure;
  7819. public:
  7820. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  7821. : Info(Info), NoteFailure(NoteFailure) {}
  7822. ~DelayedNoteFailureRAII() {
  7823. if (NoteFailure) {
  7824. bool ContinueAfterFailure = Info.noteFailure();
  7825. (void)ContinueAfterFailure;
  7826. assert(ContinueAfterFailure &&
  7827. "Shouldn't have kept evaluating on failure.");
  7828. }
  7829. }
  7830. };
  7831. }
  7832. template <class SuccessCB, class AfterCB>
  7833. static bool
  7834. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  7835. SuccessCB &&Success, AfterCB &&DoAfter) {
  7836. assert(E->isComparisonOp() && "expected comparison operator");
  7837. assert((E->getOpcode() == BO_Cmp ||
  7838. E->getType()->isIntegralOrEnumerationType()) &&
  7839. "unsupported binary expression evaluation");
  7840. auto Error = [&](const Expr *E) {
  7841. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7842. return false;
  7843. };
  7844. using CCR = ComparisonCategoryResult;
  7845. bool IsRelational = E->isRelationalOp();
  7846. bool IsEquality = E->isEqualityOp();
  7847. if (E->getOpcode() == BO_Cmp) {
  7848. const ComparisonCategoryInfo &CmpInfo =
  7849. Info.Ctx.CompCategories.getInfoForType(E->getType());
  7850. IsRelational = CmpInfo.isOrdered();
  7851. IsEquality = CmpInfo.isEquality();
  7852. }
  7853. QualType LHSTy = E->getLHS()->getType();
  7854. QualType RHSTy = E->getRHS()->getType();
  7855. if (LHSTy->isIntegralOrEnumerationType() &&
  7856. RHSTy->isIntegralOrEnumerationType()) {
  7857. APSInt LHS, RHS;
  7858. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  7859. if (!LHSOK && !Info.noteFailure())
  7860. return false;
  7861. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  7862. return false;
  7863. if (LHS < RHS)
  7864. return Success(CCR::Less, E);
  7865. if (LHS > RHS)
  7866. return Success(CCR::Greater, E);
  7867. return Success(CCR::Equal, E);
  7868. }
  7869. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  7870. ComplexValue LHS, RHS;
  7871. bool LHSOK;
  7872. if (E->isAssignmentOp()) {
  7873. LValue LV;
  7874. EvaluateLValue(E->getLHS(), LV, Info);
  7875. LHSOK = false;
  7876. } else if (LHSTy->isRealFloatingType()) {
  7877. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  7878. if (LHSOK) {
  7879. LHS.makeComplexFloat();
  7880. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  7881. }
  7882. } else {
  7883. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  7884. }
  7885. if (!LHSOK && !Info.noteFailure())
  7886. return false;
  7887. if (E->getRHS()->getType()->isRealFloatingType()) {
  7888. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  7889. return false;
  7890. RHS.makeComplexFloat();
  7891. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  7892. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  7893. return false;
  7894. if (LHS.isComplexFloat()) {
  7895. APFloat::cmpResult CR_r =
  7896. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  7897. APFloat::cmpResult CR_i =
  7898. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  7899. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  7900. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7901. } else {
  7902. assert(IsEquality && "invalid complex comparison");
  7903. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  7904. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  7905. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7906. }
  7907. }
  7908. if (LHSTy->isRealFloatingType() &&
  7909. RHSTy->isRealFloatingType()) {
  7910. APFloat RHS(0.0), LHS(0.0);
  7911. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  7912. if (!LHSOK && !Info.noteFailure())
  7913. return false;
  7914. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  7915. return false;
  7916. assert(E->isComparisonOp() && "Invalid binary operator!");
  7917. auto GetCmpRes = [&]() {
  7918. switch (LHS.compare(RHS)) {
  7919. case APFloat::cmpEqual:
  7920. return CCR::Equal;
  7921. case APFloat::cmpLessThan:
  7922. return CCR::Less;
  7923. case APFloat::cmpGreaterThan:
  7924. return CCR::Greater;
  7925. case APFloat::cmpUnordered:
  7926. return CCR::Unordered;
  7927. }
  7928. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  7929. };
  7930. return Success(GetCmpRes(), E);
  7931. }
  7932. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  7933. LValue LHSValue, RHSValue;
  7934. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  7935. if (!LHSOK && !Info.noteFailure())
  7936. return false;
  7937. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  7938. return false;
  7939. // Reject differing bases from the normal codepath; we special-case
  7940. // comparisons to null.
  7941. if (!HasSameBase(LHSValue, RHSValue)) {
  7942. // Inequalities and subtractions between unrelated pointers have
  7943. // unspecified or undefined behavior.
  7944. if (!IsEquality)
  7945. return Error(E);
  7946. // A constant address may compare equal to the address of a symbol.
  7947. // The one exception is that address of an object cannot compare equal
  7948. // to a null pointer constant.
  7949. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  7950. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  7951. return Error(E);
  7952. // It's implementation-defined whether distinct literals will have
  7953. // distinct addresses. In clang, the result of such a comparison is
  7954. // unspecified, so it is not a constant expression. However, we do know
  7955. // that the address of a literal will be non-null.
  7956. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  7957. LHSValue.Base && RHSValue.Base)
  7958. return Error(E);
  7959. // We can't tell whether weak symbols will end up pointing to the same
  7960. // object.
  7961. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  7962. return Error(E);
  7963. // We can't compare the address of the start of one object with the
  7964. // past-the-end address of another object, per C++ DR1652.
  7965. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  7966. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  7967. (RHSValue.Base && RHSValue.Offset.isZero() &&
  7968. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  7969. return Error(E);
  7970. // We can't tell whether an object is at the same address as another
  7971. // zero sized object.
  7972. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  7973. (LHSValue.Base && isZeroSized(RHSValue)))
  7974. return Error(E);
  7975. return Success(CCR::Nonequal, E);
  7976. }
  7977. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  7978. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  7979. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  7980. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  7981. // C++11 [expr.rel]p3:
  7982. // Pointers to void (after pointer conversions) can be compared, with a
  7983. // result defined as follows: If both pointers represent the same
  7984. // address or are both the null pointer value, the result is true if the
  7985. // operator is <= or >= and false otherwise; otherwise the result is
  7986. // unspecified.
  7987. // We interpret this as applying to pointers to *cv* void.
  7988. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  7989. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  7990. // C++11 [expr.rel]p2:
  7991. // - If two pointers point to non-static data members of the same object,
  7992. // or to subobjects or array elements fo such members, recursively, the
  7993. // pointer to the later declared member compares greater provided the
  7994. // two members have the same access control and provided their class is
  7995. // not a union.
  7996. // [...]
  7997. // - Otherwise pointer comparisons are unspecified.
  7998. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  7999. bool WasArrayIndex;
  8000. unsigned Mismatch = FindDesignatorMismatch(
  8001. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  8002. // At the point where the designators diverge, the comparison has a
  8003. // specified value if:
  8004. // - we are comparing array indices
  8005. // - we are comparing fields of a union, or fields with the same access
  8006. // Otherwise, the result is unspecified and thus the comparison is not a
  8007. // constant expression.
  8008. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  8009. Mismatch < RHSDesignator.Entries.size()) {
  8010. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  8011. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  8012. if (!LF && !RF)
  8013. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  8014. else if (!LF)
  8015. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8016. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  8017. << RF->getParent() << RF;
  8018. else if (!RF)
  8019. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8020. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  8021. << LF->getParent() << LF;
  8022. else if (!LF->getParent()->isUnion() &&
  8023. LF->getAccess() != RF->getAccess())
  8024. Info.CCEDiag(E,
  8025. diag::note_constexpr_pointer_comparison_differing_access)
  8026. << LF << LF->getAccess() << RF << RF->getAccess()
  8027. << LF->getParent();
  8028. }
  8029. }
  8030. // The comparison here must be unsigned, and performed with the same
  8031. // width as the pointer.
  8032. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  8033. uint64_t CompareLHS = LHSOffset.getQuantity();
  8034. uint64_t CompareRHS = RHSOffset.getQuantity();
  8035. assert(PtrSize <= 64 && "Unexpected pointer width");
  8036. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  8037. CompareLHS &= Mask;
  8038. CompareRHS &= Mask;
  8039. // If there is a base and this is a relational operator, we can only
  8040. // compare pointers within the object in question; otherwise, the result
  8041. // depends on where the object is located in memory.
  8042. if (!LHSValue.Base.isNull() && IsRelational) {
  8043. QualType BaseTy = getType(LHSValue.Base);
  8044. if (BaseTy->isIncompleteType())
  8045. return Error(E);
  8046. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  8047. uint64_t OffsetLimit = Size.getQuantity();
  8048. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  8049. return Error(E);
  8050. }
  8051. if (CompareLHS < CompareRHS)
  8052. return Success(CCR::Less, E);
  8053. if (CompareLHS > CompareRHS)
  8054. return Success(CCR::Greater, E);
  8055. return Success(CCR::Equal, E);
  8056. }
  8057. if (LHSTy->isMemberPointerType()) {
  8058. assert(IsEquality && "unexpected member pointer operation");
  8059. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  8060. MemberPtr LHSValue, RHSValue;
  8061. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  8062. if (!LHSOK && !Info.noteFailure())
  8063. return false;
  8064. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8065. return false;
  8066. // C++11 [expr.eq]p2:
  8067. // If both operands are null, they compare equal. Otherwise if only one is
  8068. // null, they compare unequal.
  8069. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  8070. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  8071. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8072. }
  8073. // Otherwise if either is a pointer to a virtual member function, the
  8074. // result is unspecified.
  8075. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  8076. if (MD->isVirtual())
  8077. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8078. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  8079. if (MD->isVirtual())
  8080. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8081. // Otherwise they compare equal if and only if they would refer to the
  8082. // same member of the same most derived object or the same subobject if
  8083. // they were dereferenced with a hypothetical object of the associated
  8084. // class type.
  8085. bool Equal = LHSValue == RHSValue;
  8086. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8087. }
  8088. if (LHSTy->isNullPtrType()) {
  8089. assert(E->isComparisonOp() && "unexpected nullptr operation");
  8090. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  8091. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  8092. // are compared, the result is true of the operator is <=, >= or ==, and
  8093. // false otherwise.
  8094. return Success(CCR::Equal, E);
  8095. }
  8096. return DoAfter();
  8097. }
  8098. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  8099. if (!CheckLiteralType(Info, E))
  8100. return false;
  8101. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8102. const BinaryOperator *E) {
  8103. // Evaluation succeeded. Lookup the information for the comparison category
  8104. // type and fetch the VarDecl for the result.
  8105. const ComparisonCategoryInfo &CmpInfo =
  8106. Info.Ctx.CompCategories.getInfoForType(E->getType());
  8107. const VarDecl *VD =
  8108. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  8109. // Check and evaluate the result as a constant expression.
  8110. LValue LV;
  8111. LV.set(VD);
  8112. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  8113. return false;
  8114. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  8115. };
  8116. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8117. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  8118. });
  8119. }
  8120. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8121. // We don't call noteFailure immediately because the assignment happens after
  8122. // we evaluate LHS and RHS.
  8123. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  8124. return Error(E);
  8125. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  8126. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  8127. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  8128. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  8129. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  8130. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  8131. if (E->isComparisonOp()) {
  8132. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  8133. // comparisons and then translating the result.
  8134. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8135. const BinaryOperator *E) {
  8136. using CCR = ComparisonCategoryResult;
  8137. bool IsEqual = ResKind == CCR::Equal,
  8138. IsLess = ResKind == CCR::Less,
  8139. IsGreater = ResKind == CCR::Greater;
  8140. auto Op = E->getOpcode();
  8141. switch (Op) {
  8142. default:
  8143. llvm_unreachable("unsupported binary operator");
  8144. case BO_EQ:
  8145. case BO_NE:
  8146. return Success(IsEqual == (Op == BO_EQ), E);
  8147. case BO_LT: return Success(IsLess, E);
  8148. case BO_GT: return Success(IsGreater, E);
  8149. case BO_LE: return Success(IsEqual || IsLess, E);
  8150. case BO_GE: return Success(IsEqual || IsGreater, E);
  8151. }
  8152. };
  8153. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8154. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8155. });
  8156. }
  8157. QualType LHSTy = E->getLHS()->getType();
  8158. QualType RHSTy = E->getRHS()->getType();
  8159. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  8160. E->getOpcode() == BO_Sub) {
  8161. LValue LHSValue, RHSValue;
  8162. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  8163. if (!LHSOK && !Info.noteFailure())
  8164. return false;
  8165. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8166. return false;
  8167. // Reject differing bases from the normal codepath; we special-case
  8168. // comparisons to null.
  8169. if (!HasSameBase(LHSValue, RHSValue)) {
  8170. // Handle &&A - &&B.
  8171. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  8172. return Error(E);
  8173. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  8174. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  8175. if (!LHSExpr || !RHSExpr)
  8176. return Error(E);
  8177. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8178. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8179. if (!LHSAddrExpr || !RHSAddrExpr)
  8180. return Error(E);
  8181. // Make sure both labels come from the same function.
  8182. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8183. RHSAddrExpr->getLabel()->getDeclContext())
  8184. return Error(E);
  8185. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  8186. }
  8187. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  8188. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  8189. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  8190. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  8191. // C++11 [expr.add]p6:
  8192. // Unless both pointers point to elements of the same array object, or
  8193. // one past the last element of the array object, the behavior is
  8194. // undefined.
  8195. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  8196. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  8197. RHSDesignator))
  8198. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  8199. QualType Type = E->getLHS()->getType();
  8200. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  8201. CharUnits ElementSize;
  8202. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  8203. return false;
  8204. // As an extension, a type may have zero size (empty struct or union in
  8205. // C, array of zero length). Pointer subtraction in such cases has
  8206. // undefined behavior, so is not constant.
  8207. if (ElementSize.isZero()) {
  8208. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  8209. << ElementType;
  8210. return false;
  8211. }
  8212. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  8213. // and produce incorrect results when it overflows. Such behavior
  8214. // appears to be non-conforming, but is common, so perhaps we should
  8215. // assume the standard intended for such cases to be undefined behavior
  8216. // and check for them.
  8217. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  8218. // overflow in the final conversion to ptrdiff_t.
  8219. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  8220. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  8221. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  8222. false);
  8223. APSInt TrueResult = (LHS - RHS) / ElemSize;
  8224. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  8225. if (Result.extend(65) != TrueResult &&
  8226. !HandleOverflow(Info, E, TrueResult, E->getType()))
  8227. return false;
  8228. return Success(Result, E);
  8229. }
  8230. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8231. }
  8232. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  8233. /// a result as the expression's type.
  8234. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  8235. const UnaryExprOrTypeTraitExpr *E) {
  8236. switch(E->getKind()) {
  8237. case UETT_PreferredAlignOf:
  8238. case UETT_AlignOf: {
  8239. if (E->isArgumentType())
  8240. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  8241. E);
  8242. else
  8243. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  8244. E);
  8245. }
  8246. case UETT_VecStep: {
  8247. QualType Ty = E->getTypeOfArgument();
  8248. if (Ty->isVectorType()) {
  8249. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  8250. // The vec_step built-in functions that take a 3-component
  8251. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  8252. if (n == 3)
  8253. n = 4;
  8254. return Success(n, E);
  8255. } else
  8256. return Success(1, E);
  8257. }
  8258. case UETT_SizeOf: {
  8259. QualType SrcTy = E->getTypeOfArgument();
  8260. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  8261. // the result is the size of the referenced type."
  8262. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  8263. SrcTy = Ref->getPointeeType();
  8264. CharUnits Sizeof;
  8265. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  8266. return false;
  8267. return Success(Sizeof, E);
  8268. }
  8269. case UETT_OpenMPRequiredSimdAlign:
  8270. assert(E->isArgumentType());
  8271. return Success(
  8272. Info.Ctx.toCharUnitsFromBits(
  8273. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  8274. .getQuantity(),
  8275. E);
  8276. }
  8277. llvm_unreachable("unknown expr/type trait");
  8278. }
  8279. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  8280. CharUnits Result;
  8281. unsigned n = OOE->getNumComponents();
  8282. if (n == 0)
  8283. return Error(OOE);
  8284. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  8285. for (unsigned i = 0; i != n; ++i) {
  8286. OffsetOfNode ON = OOE->getComponent(i);
  8287. switch (ON.getKind()) {
  8288. case OffsetOfNode::Array: {
  8289. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  8290. APSInt IdxResult;
  8291. if (!EvaluateInteger(Idx, IdxResult, Info))
  8292. return false;
  8293. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  8294. if (!AT)
  8295. return Error(OOE);
  8296. CurrentType = AT->getElementType();
  8297. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  8298. Result += IdxResult.getSExtValue() * ElementSize;
  8299. break;
  8300. }
  8301. case OffsetOfNode::Field: {
  8302. FieldDecl *MemberDecl = ON.getField();
  8303. const RecordType *RT = CurrentType->getAs<RecordType>();
  8304. if (!RT)
  8305. return Error(OOE);
  8306. RecordDecl *RD = RT->getDecl();
  8307. if (RD->isInvalidDecl()) return false;
  8308. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8309. unsigned i = MemberDecl->getFieldIndex();
  8310. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  8311. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  8312. CurrentType = MemberDecl->getType().getNonReferenceType();
  8313. break;
  8314. }
  8315. case OffsetOfNode::Identifier:
  8316. llvm_unreachable("dependent __builtin_offsetof");
  8317. case OffsetOfNode::Base: {
  8318. CXXBaseSpecifier *BaseSpec = ON.getBase();
  8319. if (BaseSpec->isVirtual())
  8320. return Error(OOE);
  8321. // Find the layout of the class whose base we are looking into.
  8322. const RecordType *RT = CurrentType->getAs<RecordType>();
  8323. if (!RT)
  8324. return Error(OOE);
  8325. RecordDecl *RD = RT->getDecl();
  8326. if (RD->isInvalidDecl()) return false;
  8327. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8328. // Find the base class itself.
  8329. CurrentType = BaseSpec->getType();
  8330. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  8331. if (!BaseRT)
  8332. return Error(OOE);
  8333. // Add the offset to the base.
  8334. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  8335. break;
  8336. }
  8337. }
  8338. }
  8339. return Success(Result, OOE);
  8340. }
  8341. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8342. switch (E->getOpcode()) {
  8343. default:
  8344. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  8345. // See C99 6.6p3.
  8346. return Error(E);
  8347. case UO_Extension:
  8348. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  8349. // If so, we could clear the diagnostic ID.
  8350. return Visit(E->getSubExpr());
  8351. case UO_Plus:
  8352. // The result is just the value.
  8353. return Visit(E->getSubExpr());
  8354. case UO_Minus: {
  8355. if (!Visit(E->getSubExpr()))
  8356. return false;
  8357. if (!Result.isInt()) return Error(E);
  8358. const APSInt &Value = Result.getInt();
  8359. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  8360. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  8361. E->getType()))
  8362. return false;
  8363. return Success(-Value, E);
  8364. }
  8365. case UO_Not: {
  8366. if (!Visit(E->getSubExpr()))
  8367. return false;
  8368. if (!Result.isInt()) return Error(E);
  8369. return Success(~Result.getInt(), E);
  8370. }
  8371. case UO_LNot: {
  8372. bool bres;
  8373. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8374. return false;
  8375. return Success(!bres, E);
  8376. }
  8377. }
  8378. }
  8379. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  8380. /// result type is integer.
  8381. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8382. const Expr *SubExpr = E->getSubExpr();
  8383. QualType DestType = E->getType();
  8384. QualType SrcType = SubExpr->getType();
  8385. switch (E->getCastKind()) {
  8386. case CK_BaseToDerived:
  8387. case CK_DerivedToBase:
  8388. case CK_UncheckedDerivedToBase:
  8389. case CK_Dynamic:
  8390. case CK_ToUnion:
  8391. case CK_ArrayToPointerDecay:
  8392. case CK_FunctionToPointerDecay:
  8393. case CK_NullToPointer:
  8394. case CK_NullToMemberPointer:
  8395. case CK_BaseToDerivedMemberPointer:
  8396. case CK_DerivedToBaseMemberPointer:
  8397. case CK_ReinterpretMemberPointer:
  8398. case CK_ConstructorConversion:
  8399. case CK_IntegralToPointer:
  8400. case CK_ToVoid:
  8401. case CK_VectorSplat:
  8402. case CK_IntegralToFloating:
  8403. case CK_FloatingCast:
  8404. case CK_CPointerToObjCPointerCast:
  8405. case CK_BlockPointerToObjCPointerCast:
  8406. case CK_AnyPointerToBlockPointerCast:
  8407. case CK_ObjCObjectLValueCast:
  8408. case CK_FloatingRealToComplex:
  8409. case CK_FloatingComplexToReal:
  8410. case CK_FloatingComplexCast:
  8411. case CK_FloatingComplexToIntegralComplex:
  8412. case CK_IntegralRealToComplex:
  8413. case CK_IntegralComplexCast:
  8414. case CK_IntegralComplexToFloatingComplex:
  8415. case CK_BuiltinFnToFnPtr:
  8416. case CK_ZeroToOCLOpaqueType:
  8417. case CK_NonAtomicToAtomic:
  8418. case CK_AddressSpaceConversion:
  8419. case CK_IntToOCLSampler:
  8420. case CK_FixedPointCast:
  8421. llvm_unreachable("invalid cast kind for integral value");
  8422. case CK_BitCast:
  8423. case CK_Dependent:
  8424. case CK_LValueBitCast:
  8425. case CK_ARCProduceObject:
  8426. case CK_ARCConsumeObject:
  8427. case CK_ARCReclaimReturnedObject:
  8428. case CK_ARCExtendBlockObject:
  8429. case CK_CopyAndAutoreleaseBlockObject:
  8430. return Error(E);
  8431. case CK_UserDefinedConversion:
  8432. case CK_LValueToRValue:
  8433. case CK_AtomicToNonAtomic:
  8434. case CK_NoOp:
  8435. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8436. case CK_MemberPointerToBoolean:
  8437. case CK_PointerToBoolean:
  8438. case CK_IntegralToBoolean:
  8439. case CK_FloatingToBoolean:
  8440. case CK_BooleanToSignedIntegral:
  8441. case CK_FloatingComplexToBoolean:
  8442. case CK_IntegralComplexToBoolean: {
  8443. bool BoolResult;
  8444. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  8445. return false;
  8446. uint64_t IntResult = BoolResult;
  8447. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  8448. IntResult = (uint64_t)-1;
  8449. return Success(IntResult, E);
  8450. }
  8451. case CK_FixedPointToBoolean: {
  8452. // Unsigned padding does not affect this.
  8453. APValue Val;
  8454. if (!Evaluate(Val, Info, SubExpr))
  8455. return false;
  8456. return Success(Val.getInt().getBoolValue(), E);
  8457. }
  8458. case CK_IntegralCast: {
  8459. if (!Visit(SubExpr))
  8460. return false;
  8461. if (!Result.isInt()) {
  8462. // Allow casts of address-of-label differences if they are no-ops
  8463. // or narrowing. (The narrowing case isn't actually guaranteed to
  8464. // be constant-evaluatable except in some narrow cases which are hard
  8465. // to detect here. We let it through on the assumption the user knows
  8466. // what they are doing.)
  8467. if (Result.isAddrLabelDiff())
  8468. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  8469. // Only allow casts of lvalues if they are lossless.
  8470. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  8471. }
  8472. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  8473. Result.getInt()), E);
  8474. }
  8475. case CK_PointerToIntegral: {
  8476. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  8477. LValue LV;
  8478. if (!EvaluatePointer(SubExpr, LV, Info))
  8479. return false;
  8480. if (LV.getLValueBase()) {
  8481. // Only allow based lvalue casts if they are lossless.
  8482. // FIXME: Allow a larger integer size than the pointer size, and allow
  8483. // narrowing back down to pointer width in subsequent integral casts.
  8484. // FIXME: Check integer type's active bits, not its type size.
  8485. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  8486. return Error(E);
  8487. LV.Designator.setInvalid();
  8488. LV.moveInto(Result);
  8489. return true;
  8490. }
  8491. uint64_t V;
  8492. if (LV.isNullPointer())
  8493. V = Info.Ctx.getTargetNullPointerValue(SrcType);
  8494. else
  8495. V = LV.getLValueOffset().getQuantity();
  8496. APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
  8497. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  8498. }
  8499. case CK_IntegralComplexToReal: {
  8500. ComplexValue C;
  8501. if (!EvaluateComplex(SubExpr, C, Info))
  8502. return false;
  8503. return Success(C.getComplexIntReal(), E);
  8504. }
  8505. case CK_FloatingToIntegral: {
  8506. APFloat F(0.0);
  8507. if (!EvaluateFloat(SubExpr, F, Info))
  8508. return false;
  8509. APSInt Value;
  8510. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  8511. return false;
  8512. return Success(Value, E);
  8513. }
  8514. }
  8515. llvm_unreachable("unknown cast resulting in integral value");
  8516. }
  8517. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8518. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8519. ComplexValue LV;
  8520. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8521. return false;
  8522. if (!LV.isComplexInt())
  8523. return Error(E);
  8524. return Success(LV.getComplexIntReal(), E);
  8525. }
  8526. return Visit(E->getSubExpr());
  8527. }
  8528. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8529. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  8530. ComplexValue LV;
  8531. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8532. return false;
  8533. if (!LV.isComplexInt())
  8534. return Error(E);
  8535. return Success(LV.getComplexIntImag(), E);
  8536. }
  8537. VisitIgnoredValue(E->getSubExpr());
  8538. return Success(0, E);
  8539. }
  8540. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  8541. return Success(E->getPackLength(), E);
  8542. }
  8543. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  8544. return Success(E->getValue(), E);
  8545. }
  8546. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8547. switch (E->getOpcode()) {
  8548. default:
  8549. // Invalid unary operators
  8550. return Error(E);
  8551. case UO_Plus:
  8552. // The result is just the value.
  8553. return Visit(E->getSubExpr());
  8554. case UO_Minus: {
  8555. if (!Visit(E->getSubExpr())) return false;
  8556. if (!Result.isInt()) return Error(E);
  8557. const APSInt &Value = Result.getInt();
  8558. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
  8559. SmallString<64> S;
  8560. FixedPointValueToString(S, Value,
  8561. Info.Ctx.getTypeInfo(E->getType()).Width);
  8562. Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
  8563. if (Info.noteUndefinedBehavior()) return false;
  8564. }
  8565. return Success(-Value, E);
  8566. }
  8567. case UO_LNot: {
  8568. bool bres;
  8569. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8570. return false;
  8571. return Success(!bres, E);
  8572. }
  8573. }
  8574. }
  8575. //===----------------------------------------------------------------------===//
  8576. // Float Evaluation
  8577. //===----------------------------------------------------------------------===//
  8578. namespace {
  8579. class FloatExprEvaluator
  8580. : public ExprEvaluatorBase<FloatExprEvaluator> {
  8581. APFloat &Result;
  8582. public:
  8583. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  8584. : ExprEvaluatorBaseTy(info), Result(result) {}
  8585. bool Success(const APValue &V, const Expr *e) {
  8586. Result = V.getFloat();
  8587. return true;
  8588. }
  8589. bool ZeroInitialization(const Expr *E) {
  8590. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  8591. return true;
  8592. }
  8593. bool VisitCallExpr(const CallExpr *E);
  8594. bool VisitUnaryOperator(const UnaryOperator *E);
  8595. bool VisitBinaryOperator(const BinaryOperator *E);
  8596. bool VisitFloatingLiteral(const FloatingLiteral *E);
  8597. bool VisitCastExpr(const CastExpr *E);
  8598. bool VisitUnaryReal(const UnaryOperator *E);
  8599. bool VisitUnaryImag(const UnaryOperator *E);
  8600. // FIXME: Missing: array subscript of vector, member of vector
  8601. };
  8602. } // end anonymous namespace
  8603. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  8604. assert(E->isRValue() && E->getType()->isRealFloatingType());
  8605. return FloatExprEvaluator(Info, Result).Visit(E);
  8606. }
  8607. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  8608. QualType ResultTy,
  8609. const Expr *Arg,
  8610. bool SNaN,
  8611. llvm::APFloat &Result) {
  8612. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  8613. if (!S) return false;
  8614. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  8615. llvm::APInt fill;
  8616. // Treat empty strings as if they were zero.
  8617. if (S->getString().empty())
  8618. fill = llvm::APInt(32, 0);
  8619. else if (S->getString().getAsInteger(0, fill))
  8620. return false;
  8621. if (Context.getTargetInfo().isNan2008()) {
  8622. if (SNaN)
  8623. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8624. else
  8625. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8626. } else {
  8627. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  8628. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  8629. // a different encoding to what became a standard in 2008, and for pre-
  8630. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  8631. // sNaN. This is now known as "legacy NaN" encoding.
  8632. if (SNaN)
  8633. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8634. else
  8635. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8636. }
  8637. return true;
  8638. }
  8639. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8640. switch (E->getBuiltinCallee()) {
  8641. default:
  8642. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8643. case Builtin::BI__builtin_huge_val:
  8644. case Builtin::BI__builtin_huge_valf:
  8645. case Builtin::BI__builtin_huge_vall:
  8646. case Builtin::BI__builtin_huge_valf128:
  8647. case Builtin::BI__builtin_inf:
  8648. case Builtin::BI__builtin_inff:
  8649. case Builtin::BI__builtin_infl:
  8650. case Builtin::BI__builtin_inff128: {
  8651. const llvm::fltSemantics &Sem =
  8652. Info.Ctx.getFloatTypeSemantics(E->getType());
  8653. Result = llvm::APFloat::getInf(Sem);
  8654. return true;
  8655. }
  8656. case Builtin::BI__builtin_nans:
  8657. case Builtin::BI__builtin_nansf:
  8658. case Builtin::BI__builtin_nansl:
  8659. case Builtin::BI__builtin_nansf128:
  8660. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8661. true, Result))
  8662. return Error(E);
  8663. return true;
  8664. case Builtin::BI__builtin_nan:
  8665. case Builtin::BI__builtin_nanf:
  8666. case Builtin::BI__builtin_nanl:
  8667. case Builtin::BI__builtin_nanf128:
  8668. // If this is __builtin_nan() turn this into a nan, otherwise we
  8669. // can't constant fold it.
  8670. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8671. false, Result))
  8672. return Error(E);
  8673. return true;
  8674. case Builtin::BI__builtin_fabs:
  8675. case Builtin::BI__builtin_fabsf:
  8676. case Builtin::BI__builtin_fabsl:
  8677. case Builtin::BI__builtin_fabsf128:
  8678. if (!EvaluateFloat(E->getArg(0), Result, Info))
  8679. return false;
  8680. if (Result.isNegative())
  8681. Result.changeSign();
  8682. return true;
  8683. // FIXME: Builtin::BI__builtin_powi
  8684. // FIXME: Builtin::BI__builtin_powif
  8685. // FIXME: Builtin::BI__builtin_powil
  8686. case Builtin::BI__builtin_copysign:
  8687. case Builtin::BI__builtin_copysignf:
  8688. case Builtin::BI__builtin_copysignl:
  8689. case Builtin::BI__builtin_copysignf128: {
  8690. APFloat RHS(0.);
  8691. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  8692. !EvaluateFloat(E->getArg(1), RHS, Info))
  8693. return false;
  8694. Result.copySign(RHS);
  8695. return true;
  8696. }
  8697. }
  8698. }
  8699. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8700. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8701. ComplexValue CV;
  8702. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8703. return false;
  8704. Result = CV.FloatReal;
  8705. return true;
  8706. }
  8707. return Visit(E->getSubExpr());
  8708. }
  8709. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8710. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8711. ComplexValue CV;
  8712. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8713. return false;
  8714. Result = CV.FloatImag;
  8715. return true;
  8716. }
  8717. VisitIgnoredValue(E->getSubExpr());
  8718. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  8719. Result = llvm::APFloat::getZero(Sem);
  8720. return true;
  8721. }
  8722. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8723. switch (E->getOpcode()) {
  8724. default: return Error(E);
  8725. case UO_Plus:
  8726. return EvaluateFloat(E->getSubExpr(), Result, Info);
  8727. case UO_Minus:
  8728. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  8729. return false;
  8730. Result.changeSign();
  8731. return true;
  8732. }
  8733. }
  8734. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8735. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8736. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8737. APFloat RHS(0.0);
  8738. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  8739. if (!LHSOK && !Info.noteFailure())
  8740. return false;
  8741. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  8742. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  8743. }
  8744. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  8745. Result = E->getValue();
  8746. return true;
  8747. }
  8748. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8749. const Expr* SubExpr = E->getSubExpr();
  8750. switch (E->getCastKind()) {
  8751. default:
  8752. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8753. case CK_IntegralToFloating: {
  8754. APSInt IntResult;
  8755. return EvaluateInteger(SubExpr, IntResult, Info) &&
  8756. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  8757. E->getType(), Result);
  8758. }
  8759. case CK_FloatingCast: {
  8760. if (!Visit(SubExpr))
  8761. return false;
  8762. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  8763. Result);
  8764. }
  8765. case CK_FloatingComplexToReal: {
  8766. ComplexValue V;
  8767. if (!EvaluateComplex(SubExpr, V, Info))
  8768. return false;
  8769. Result = V.getComplexFloatReal();
  8770. return true;
  8771. }
  8772. }
  8773. }
  8774. //===----------------------------------------------------------------------===//
  8775. // Complex Evaluation (for float and integer)
  8776. //===----------------------------------------------------------------------===//
  8777. namespace {
  8778. class ComplexExprEvaluator
  8779. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  8780. ComplexValue &Result;
  8781. public:
  8782. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  8783. : ExprEvaluatorBaseTy(info), Result(Result) {}
  8784. bool Success(const APValue &V, const Expr *e) {
  8785. Result.setFrom(V);
  8786. return true;
  8787. }
  8788. bool ZeroInitialization(const Expr *E);
  8789. //===--------------------------------------------------------------------===//
  8790. // Visitor Methods
  8791. //===--------------------------------------------------------------------===//
  8792. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  8793. bool VisitCastExpr(const CastExpr *E);
  8794. bool VisitBinaryOperator(const BinaryOperator *E);
  8795. bool VisitUnaryOperator(const UnaryOperator *E);
  8796. bool VisitInitListExpr(const InitListExpr *E);
  8797. };
  8798. } // end anonymous namespace
  8799. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  8800. EvalInfo &Info) {
  8801. assert(E->isRValue() && E->getType()->isAnyComplexType());
  8802. return ComplexExprEvaluator(Info, Result).Visit(E);
  8803. }
  8804. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  8805. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  8806. if (ElemTy->isRealFloatingType()) {
  8807. Result.makeComplexFloat();
  8808. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  8809. Result.FloatReal = Zero;
  8810. Result.FloatImag = Zero;
  8811. } else {
  8812. Result.makeComplexInt();
  8813. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  8814. Result.IntReal = Zero;
  8815. Result.IntImag = Zero;
  8816. }
  8817. return true;
  8818. }
  8819. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  8820. const Expr* SubExpr = E->getSubExpr();
  8821. if (SubExpr->getType()->isRealFloatingType()) {
  8822. Result.makeComplexFloat();
  8823. APFloat &Imag = Result.FloatImag;
  8824. if (!EvaluateFloat(SubExpr, Imag, Info))
  8825. return false;
  8826. Result.FloatReal = APFloat(Imag.getSemantics());
  8827. return true;
  8828. } else {
  8829. assert(SubExpr->getType()->isIntegerType() &&
  8830. "Unexpected imaginary literal.");
  8831. Result.makeComplexInt();
  8832. APSInt &Imag = Result.IntImag;
  8833. if (!EvaluateInteger(SubExpr, Imag, Info))
  8834. return false;
  8835. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  8836. return true;
  8837. }
  8838. }
  8839. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8840. switch (E->getCastKind()) {
  8841. case CK_BitCast:
  8842. case CK_BaseToDerived:
  8843. case CK_DerivedToBase:
  8844. case CK_UncheckedDerivedToBase:
  8845. case CK_Dynamic:
  8846. case CK_ToUnion:
  8847. case CK_ArrayToPointerDecay:
  8848. case CK_FunctionToPointerDecay:
  8849. case CK_NullToPointer:
  8850. case CK_NullToMemberPointer:
  8851. case CK_BaseToDerivedMemberPointer:
  8852. case CK_DerivedToBaseMemberPointer:
  8853. case CK_MemberPointerToBoolean:
  8854. case CK_ReinterpretMemberPointer:
  8855. case CK_ConstructorConversion:
  8856. case CK_IntegralToPointer:
  8857. case CK_PointerToIntegral:
  8858. case CK_PointerToBoolean:
  8859. case CK_ToVoid:
  8860. case CK_VectorSplat:
  8861. case CK_IntegralCast:
  8862. case CK_BooleanToSignedIntegral:
  8863. case CK_IntegralToBoolean:
  8864. case CK_IntegralToFloating:
  8865. case CK_FloatingToIntegral:
  8866. case CK_FloatingToBoolean:
  8867. case CK_FloatingCast:
  8868. case CK_CPointerToObjCPointerCast:
  8869. case CK_BlockPointerToObjCPointerCast:
  8870. case CK_AnyPointerToBlockPointerCast:
  8871. case CK_ObjCObjectLValueCast:
  8872. case CK_FloatingComplexToReal:
  8873. case CK_FloatingComplexToBoolean:
  8874. case CK_IntegralComplexToReal:
  8875. case CK_IntegralComplexToBoolean:
  8876. case CK_ARCProduceObject:
  8877. case CK_ARCConsumeObject:
  8878. case CK_ARCReclaimReturnedObject:
  8879. case CK_ARCExtendBlockObject:
  8880. case CK_CopyAndAutoreleaseBlockObject:
  8881. case CK_BuiltinFnToFnPtr:
  8882. case CK_ZeroToOCLOpaqueType:
  8883. case CK_NonAtomicToAtomic:
  8884. case CK_AddressSpaceConversion:
  8885. case CK_IntToOCLSampler:
  8886. case CK_FixedPointCast:
  8887. case CK_FixedPointToBoolean:
  8888. llvm_unreachable("invalid cast kind for complex value");
  8889. case CK_LValueToRValue:
  8890. case CK_AtomicToNonAtomic:
  8891. case CK_NoOp:
  8892. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8893. case CK_Dependent:
  8894. case CK_LValueBitCast:
  8895. case CK_UserDefinedConversion:
  8896. return Error(E);
  8897. case CK_FloatingRealToComplex: {
  8898. APFloat &Real = Result.FloatReal;
  8899. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  8900. return false;
  8901. Result.makeComplexFloat();
  8902. Result.FloatImag = APFloat(Real.getSemantics());
  8903. return true;
  8904. }
  8905. case CK_FloatingComplexCast: {
  8906. if (!Visit(E->getSubExpr()))
  8907. return false;
  8908. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8909. QualType From
  8910. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8911. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  8912. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  8913. }
  8914. case CK_FloatingComplexToIntegralComplex: {
  8915. if (!Visit(E->getSubExpr()))
  8916. return false;
  8917. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8918. QualType From
  8919. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8920. Result.makeComplexInt();
  8921. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  8922. To, Result.IntReal) &&
  8923. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  8924. To, Result.IntImag);
  8925. }
  8926. case CK_IntegralRealToComplex: {
  8927. APSInt &Real = Result.IntReal;
  8928. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  8929. return false;
  8930. Result.makeComplexInt();
  8931. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  8932. return true;
  8933. }
  8934. case CK_IntegralComplexCast: {
  8935. if (!Visit(E->getSubExpr()))
  8936. return false;
  8937. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8938. QualType From
  8939. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8940. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  8941. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  8942. return true;
  8943. }
  8944. case CK_IntegralComplexToFloatingComplex: {
  8945. if (!Visit(E->getSubExpr()))
  8946. return false;
  8947. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  8948. QualType From
  8949. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  8950. Result.makeComplexFloat();
  8951. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  8952. To, Result.FloatReal) &&
  8953. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  8954. To, Result.FloatImag);
  8955. }
  8956. }
  8957. llvm_unreachable("unknown cast resulting in complex value");
  8958. }
  8959. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8960. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8961. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8962. // Track whether the LHS or RHS is real at the type system level. When this is
  8963. // the case we can simplify our evaluation strategy.
  8964. bool LHSReal = false, RHSReal = false;
  8965. bool LHSOK;
  8966. if (E->getLHS()->getType()->isRealFloatingType()) {
  8967. LHSReal = true;
  8968. APFloat &Real = Result.FloatReal;
  8969. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  8970. if (LHSOK) {
  8971. Result.makeComplexFloat();
  8972. Result.FloatImag = APFloat(Real.getSemantics());
  8973. }
  8974. } else {
  8975. LHSOK = Visit(E->getLHS());
  8976. }
  8977. if (!LHSOK && !Info.noteFailure())
  8978. return false;
  8979. ComplexValue RHS;
  8980. if (E->getRHS()->getType()->isRealFloatingType()) {
  8981. RHSReal = true;
  8982. APFloat &Real = RHS.FloatReal;
  8983. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  8984. return false;
  8985. RHS.makeComplexFloat();
  8986. RHS.FloatImag = APFloat(Real.getSemantics());
  8987. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  8988. return false;
  8989. assert(!(LHSReal && RHSReal) &&
  8990. "Cannot have both operands of a complex operation be real.");
  8991. switch (E->getOpcode()) {
  8992. default: return Error(E);
  8993. case BO_Add:
  8994. if (Result.isComplexFloat()) {
  8995. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  8996. APFloat::rmNearestTiesToEven);
  8997. if (LHSReal)
  8998. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  8999. else if (!RHSReal)
  9000. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  9001. APFloat::rmNearestTiesToEven);
  9002. } else {
  9003. Result.getComplexIntReal() += RHS.getComplexIntReal();
  9004. Result.getComplexIntImag() += RHS.getComplexIntImag();
  9005. }
  9006. break;
  9007. case BO_Sub:
  9008. if (Result.isComplexFloat()) {
  9009. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  9010. APFloat::rmNearestTiesToEven);
  9011. if (LHSReal) {
  9012. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9013. Result.getComplexFloatImag().changeSign();
  9014. } else if (!RHSReal) {
  9015. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  9016. APFloat::rmNearestTiesToEven);
  9017. }
  9018. } else {
  9019. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  9020. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  9021. }
  9022. break;
  9023. case BO_Mul:
  9024. if (Result.isComplexFloat()) {
  9025. // This is an implementation of complex multiplication according to the
  9026. // constraints laid out in C11 Annex G. The implemention uses the
  9027. // following naming scheme:
  9028. // (a + ib) * (c + id)
  9029. ComplexValue LHS = Result;
  9030. APFloat &A = LHS.getComplexFloatReal();
  9031. APFloat &B = LHS.getComplexFloatImag();
  9032. APFloat &C = RHS.getComplexFloatReal();
  9033. APFloat &D = RHS.getComplexFloatImag();
  9034. APFloat &ResR = Result.getComplexFloatReal();
  9035. APFloat &ResI = Result.getComplexFloatImag();
  9036. if (LHSReal) {
  9037. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  9038. ResR = A * C;
  9039. ResI = A * D;
  9040. } else if (RHSReal) {
  9041. ResR = C * A;
  9042. ResI = C * B;
  9043. } else {
  9044. // In the fully general case, we need to handle NaNs and infinities
  9045. // robustly.
  9046. APFloat AC = A * C;
  9047. APFloat BD = B * D;
  9048. APFloat AD = A * D;
  9049. APFloat BC = B * C;
  9050. ResR = AC - BD;
  9051. ResI = AD + BC;
  9052. if (ResR.isNaN() && ResI.isNaN()) {
  9053. bool Recalc = false;
  9054. if (A.isInfinity() || B.isInfinity()) {
  9055. A = APFloat::copySign(
  9056. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9057. B = APFloat::copySign(
  9058. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9059. if (C.isNaN())
  9060. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9061. if (D.isNaN())
  9062. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9063. Recalc = true;
  9064. }
  9065. if (C.isInfinity() || D.isInfinity()) {
  9066. C = APFloat::copySign(
  9067. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9068. D = APFloat::copySign(
  9069. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9070. if (A.isNaN())
  9071. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9072. if (B.isNaN())
  9073. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9074. Recalc = true;
  9075. }
  9076. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  9077. AD.isInfinity() || BC.isInfinity())) {
  9078. if (A.isNaN())
  9079. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9080. if (B.isNaN())
  9081. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9082. if (C.isNaN())
  9083. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9084. if (D.isNaN())
  9085. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9086. Recalc = true;
  9087. }
  9088. if (Recalc) {
  9089. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  9090. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  9091. }
  9092. }
  9093. }
  9094. } else {
  9095. ComplexValue LHS = Result;
  9096. Result.getComplexIntReal() =
  9097. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  9098. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  9099. Result.getComplexIntImag() =
  9100. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  9101. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  9102. }
  9103. break;
  9104. case BO_Div:
  9105. if (Result.isComplexFloat()) {
  9106. // This is an implementation of complex division according to the
  9107. // constraints laid out in C11 Annex G. The implemention uses the
  9108. // following naming scheme:
  9109. // (a + ib) / (c + id)
  9110. ComplexValue LHS = Result;
  9111. APFloat &A = LHS.getComplexFloatReal();
  9112. APFloat &B = LHS.getComplexFloatImag();
  9113. APFloat &C = RHS.getComplexFloatReal();
  9114. APFloat &D = RHS.getComplexFloatImag();
  9115. APFloat &ResR = Result.getComplexFloatReal();
  9116. APFloat &ResI = Result.getComplexFloatImag();
  9117. if (RHSReal) {
  9118. ResR = A / C;
  9119. ResI = B / C;
  9120. } else {
  9121. if (LHSReal) {
  9122. // No real optimizations we can do here, stub out with zero.
  9123. B = APFloat::getZero(A.getSemantics());
  9124. }
  9125. int DenomLogB = 0;
  9126. APFloat MaxCD = maxnum(abs(C), abs(D));
  9127. if (MaxCD.isFinite()) {
  9128. DenomLogB = ilogb(MaxCD);
  9129. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  9130. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  9131. }
  9132. APFloat Denom = C * C + D * D;
  9133. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  9134. APFloat::rmNearestTiesToEven);
  9135. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  9136. APFloat::rmNearestTiesToEven);
  9137. if (ResR.isNaN() && ResI.isNaN()) {
  9138. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  9139. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  9140. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  9141. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  9142. D.isFinite()) {
  9143. A = APFloat::copySign(
  9144. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9145. B = APFloat::copySign(
  9146. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9147. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  9148. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  9149. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  9150. C = APFloat::copySign(
  9151. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9152. D = APFloat::copySign(
  9153. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9154. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  9155. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  9156. }
  9157. }
  9158. }
  9159. } else {
  9160. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  9161. return Error(E, diag::note_expr_divide_by_zero);
  9162. ComplexValue LHS = Result;
  9163. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9164. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  9165. Result.getComplexIntReal() =
  9166. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9167. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  9168. Result.getComplexIntImag() =
  9169. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  9170. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  9171. }
  9172. break;
  9173. }
  9174. return true;
  9175. }
  9176. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9177. // Get the operand value into 'Result'.
  9178. if (!Visit(E->getSubExpr()))
  9179. return false;
  9180. switch (E->getOpcode()) {
  9181. default:
  9182. return Error(E);
  9183. case UO_Extension:
  9184. return true;
  9185. case UO_Plus:
  9186. // The result is always just the subexpr.
  9187. return true;
  9188. case UO_Minus:
  9189. if (Result.isComplexFloat()) {
  9190. Result.getComplexFloatReal().changeSign();
  9191. Result.getComplexFloatImag().changeSign();
  9192. }
  9193. else {
  9194. Result.getComplexIntReal() = -Result.getComplexIntReal();
  9195. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9196. }
  9197. return true;
  9198. case UO_Not:
  9199. if (Result.isComplexFloat())
  9200. Result.getComplexFloatImag().changeSign();
  9201. else
  9202. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9203. return true;
  9204. }
  9205. }
  9206. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  9207. if (E->getNumInits() == 2) {
  9208. if (E->getType()->isComplexType()) {
  9209. Result.makeComplexFloat();
  9210. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  9211. return false;
  9212. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  9213. return false;
  9214. } else {
  9215. Result.makeComplexInt();
  9216. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  9217. return false;
  9218. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  9219. return false;
  9220. }
  9221. return true;
  9222. }
  9223. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  9224. }
  9225. //===----------------------------------------------------------------------===//
  9226. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  9227. // implicit conversion.
  9228. //===----------------------------------------------------------------------===//
  9229. namespace {
  9230. class AtomicExprEvaluator :
  9231. public ExprEvaluatorBase<AtomicExprEvaluator> {
  9232. const LValue *This;
  9233. APValue &Result;
  9234. public:
  9235. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  9236. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  9237. bool Success(const APValue &V, const Expr *E) {
  9238. Result = V;
  9239. return true;
  9240. }
  9241. bool ZeroInitialization(const Expr *E) {
  9242. ImplicitValueInitExpr VIE(
  9243. E->getType()->castAs<AtomicType>()->getValueType());
  9244. // For atomic-qualified class (and array) types in C++, initialize the
  9245. // _Atomic-wrapped subobject directly, in-place.
  9246. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  9247. : Evaluate(Result, Info, &VIE);
  9248. }
  9249. bool VisitCastExpr(const CastExpr *E) {
  9250. switch (E->getCastKind()) {
  9251. default:
  9252. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9253. case CK_NonAtomicToAtomic:
  9254. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  9255. : Evaluate(Result, Info, E->getSubExpr());
  9256. }
  9257. }
  9258. };
  9259. } // end anonymous namespace
  9260. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  9261. EvalInfo &Info) {
  9262. assert(E->isRValue() && E->getType()->isAtomicType());
  9263. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  9264. }
  9265. //===----------------------------------------------------------------------===//
  9266. // Void expression evaluation, primarily for a cast to void on the LHS of a
  9267. // comma operator
  9268. //===----------------------------------------------------------------------===//
  9269. namespace {
  9270. class VoidExprEvaluator
  9271. : public ExprEvaluatorBase<VoidExprEvaluator> {
  9272. public:
  9273. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  9274. bool Success(const APValue &V, const Expr *e) { return true; }
  9275. bool ZeroInitialization(const Expr *E) { return true; }
  9276. bool VisitCastExpr(const CastExpr *E) {
  9277. switch (E->getCastKind()) {
  9278. default:
  9279. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9280. case CK_ToVoid:
  9281. VisitIgnoredValue(E->getSubExpr());
  9282. return true;
  9283. }
  9284. }
  9285. bool VisitCallExpr(const CallExpr *E) {
  9286. switch (E->getBuiltinCallee()) {
  9287. default:
  9288. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9289. case Builtin::BI__assume:
  9290. case Builtin::BI__builtin_assume:
  9291. // The argument is not evaluated!
  9292. return true;
  9293. }
  9294. }
  9295. };
  9296. } // end anonymous namespace
  9297. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  9298. assert(E->isRValue() && E->getType()->isVoidType());
  9299. return VoidExprEvaluator(Info).Visit(E);
  9300. }
  9301. //===----------------------------------------------------------------------===//
  9302. // Top level Expr::EvaluateAsRValue method.
  9303. //===----------------------------------------------------------------------===//
  9304. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  9305. // In C, function designators are not lvalues, but we evaluate them as if they
  9306. // are.
  9307. QualType T = E->getType();
  9308. if (E->isGLValue() || T->isFunctionType()) {
  9309. LValue LV;
  9310. if (!EvaluateLValue(E, LV, Info))
  9311. return false;
  9312. LV.moveInto(Result);
  9313. } else if (T->isVectorType()) {
  9314. if (!EvaluateVector(E, Result, Info))
  9315. return false;
  9316. } else if (T->isIntegralOrEnumerationType()) {
  9317. if (!IntExprEvaluator(Info, Result).Visit(E))
  9318. return false;
  9319. } else if (T->hasPointerRepresentation()) {
  9320. LValue LV;
  9321. if (!EvaluatePointer(E, LV, Info))
  9322. return false;
  9323. LV.moveInto(Result);
  9324. } else if (T->isRealFloatingType()) {
  9325. llvm::APFloat F(0.0);
  9326. if (!EvaluateFloat(E, F, Info))
  9327. return false;
  9328. Result = APValue(F);
  9329. } else if (T->isAnyComplexType()) {
  9330. ComplexValue C;
  9331. if (!EvaluateComplex(E, C, Info))
  9332. return false;
  9333. C.moveInto(Result);
  9334. } else if (T->isFixedPointType()) {
  9335. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  9336. } else if (T->isMemberPointerType()) {
  9337. MemberPtr P;
  9338. if (!EvaluateMemberPointer(E, P, Info))
  9339. return false;
  9340. P.moveInto(Result);
  9341. return true;
  9342. } else if (T->isArrayType()) {
  9343. LValue LV;
  9344. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9345. if (!EvaluateArray(E, LV, Value, Info))
  9346. return false;
  9347. Result = Value;
  9348. } else if (T->isRecordType()) {
  9349. LValue LV;
  9350. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9351. if (!EvaluateRecord(E, LV, Value, Info))
  9352. return false;
  9353. Result = Value;
  9354. } else if (T->isVoidType()) {
  9355. if (!Info.getLangOpts().CPlusPlus11)
  9356. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  9357. << E->getType();
  9358. if (!EvaluateVoid(E, Info))
  9359. return false;
  9360. } else if (T->isAtomicType()) {
  9361. QualType Unqual = T.getAtomicUnqualifiedType();
  9362. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  9363. LValue LV;
  9364. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9365. if (!EvaluateAtomic(E, &LV, Value, Info))
  9366. return false;
  9367. } else {
  9368. if (!EvaluateAtomic(E, nullptr, Result, Info))
  9369. return false;
  9370. }
  9371. } else if (Info.getLangOpts().CPlusPlus11) {
  9372. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  9373. return false;
  9374. } else {
  9375. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9376. return false;
  9377. }
  9378. return true;
  9379. }
  9380. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  9381. /// cases, the in-place evaluation is essential, since later initializers for
  9382. /// an object can indirectly refer to subobjects which were initialized earlier.
  9383. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  9384. const Expr *E, bool AllowNonLiteralTypes) {
  9385. assert(!E->isValueDependent());
  9386. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  9387. return false;
  9388. if (E->isRValue()) {
  9389. // Evaluate arrays and record types in-place, so that later initializers can
  9390. // refer to earlier-initialized members of the object.
  9391. QualType T = E->getType();
  9392. if (T->isArrayType())
  9393. return EvaluateArray(E, This, Result, Info);
  9394. else if (T->isRecordType())
  9395. return EvaluateRecord(E, This, Result, Info);
  9396. else if (T->isAtomicType()) {
  9397. QualType Unqual = T.getAtomicUnqualifiedType();
  9398. if (Unqual->isArrayType() || Unqual->isRecordType())
  9399. return EvaluateAtomic(E, &This, Result, Info);
  9400. }
  9401. }
  9402. // For any other type, in-place evaluation is unimportant.
  9403. return Evaluate(Result, Info, E);
  9404. }
  9405. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  9406. /// lvalue-to-rvalue cast if it is an lvalue.
  9407. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  9408. if (E->getType().isNull())
  9409. return false;
  9410. if (!CheckLiteralType(Info, E))
  9411. return false;
  9412. if (!::Evaluate(Result, Info, E))
  9413. return false;
  9414. if (E->isGLValue()) {
  9415. LValue LV;
  9416. LV.setFrom(Info.Ctx, Result);
  9417. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  9418. return false;
  9419. }
  9420. // Check this core constant expression is a constant expression.
  9421. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  9422. }
  9423. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  9424. const ASTContext &Ctx, bool &IsConst) {
  9425. // Fast-path evaluations of integer literals, since we sometimes see files
  9426. // containing vast quantities of these.
  9427. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  9428. Result.Val = APValue(APSInt(L->getValue(),
  9429. L->getType()->isUnsignedIntegerType()));
  9430. IsConst = true;
  9431. return true;
  9432. }
  9433. // This case should be rare, but we need to check it before we check on
  9434. // the type below.
  9435. if (Exp->getType().isNull()) {
  9436. IsConst = false;
  9437. return true;
  9438. }
  9439. // FIXME: Evaluating values of large array and record types can cause
  9440. // performance problems. Only do so in C++11 for now.
  9441. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  9442. Exp->getType()->isRecordType()) &&
  9443. !Ctx.getLangOpts().CPlusPlus11) {
  9444. IsConst = false;
  9445. return true;
  9446. }
  9447. return false;
  9448. }
  9449. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  9450. /// any crazy technique (that has nothing to do with language standards) that
  9451. /// we want to. If this function returns true, it returns the folded constant
  9452. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  9453. /// will be applied to the result.
  9454. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  9455. bool IsConst;
  9456. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
  9457. return IsConst;
  9458. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  9459. return ::EvaluateAsRValue(Info, this, Result.Val);
  9460. }
  9461. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  9462. const ASTContext &Ctx) const {
  9463. EvalResult Scratch;
  9464. return EvaluateAsRValue(Scratch, Ctx) &&
  9465. HandleConversionToBool(Scratch.Val, Result);
  9466. }
  9467. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  9468. Expr::SideEffectsKind SEK) {
  9469. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  9470. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  9471. }
  9472. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  9473. SideEffectsKind AllowSideEffects) const {
  9474. if (!getType()->isIntegralOrEnumerationType())
  9475. return false;
  9476. EvalResult ExprResult;
  9477. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  9478. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9479. return false;
  9480. Result = ExprResult.Val.getInt();
  9481. return true;
  9482. }
  9483. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  9484. SideEffectsKind AllowSideEffects) const {
  9485. if (!getType()->isRealFloatingType())
  9486. return false;
  9487. EvalResult ExprResult;
  9488. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
  9489. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9490. return false;
  9491. Result = ExprResult.Val.getFloat();
  9492. return true;
  9493. }
  9494. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  9495. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  9496. LValue LV;
  9497. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  9498. !CheckLValueConstantExpression(Info, getExprLoc(),
  9499. Ctx.getLValueReferenceType(getType()), LV,
  9500. Expr::EvaluateForCodeGen))
  9501. return false;
  9502. LV.moveInto(Result.Val);
  9503. return true;
  9504. }
  9505. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  9506. const ASTContext &Ctx) const {
  9507. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  9508. EvalInfo Info(Ctx, Result, EM);
  9509. if (!::Evaluate(Result.Val, Info, this))
  9510. return false;
  9511. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  9512. Usage);
  9513. }
  9514. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  9515. const VarDecl *VD,
  9516. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  9517. // FIXME: Evaluating initializers for large array and record types can cause
  9518. // performance problems. Only do so in C++11 for now.
  9519. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  9520. !Ctx.getLangOpts().CPlusPlus11)
  9521. return false;
  9522. Expr::EvalStatus EStatus;
  9523. EStatus.Diag = &Notes;
  9524. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  9525. ? EvalInfo::EM_ConstantExpression
  9526. : EvalInfo::EM_ConstantFold);
  9527. InitInfo.setEvaluatingDecl(VD, Value);
  9528. LValue LVal;
  9529. LVal.set(VD);
  9530. // C++11 [basic.start.init]p2:
  9531. // Variables with static storage duration or thread storage duration shall be
  9532. // zero-initialized before any other initialization takes place.
  9533. // This behavior is not present in C.
  9534. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  9535. !VD->getType()->isReferenceType()) {
  9536. ImplicitValueInitExpr VIE(VD->getType());
  9537. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  9538. /*AllowNonLiteralTypes=*/true))
  9539. return false;
  9540. }
  9541. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  9542. /*AllowNonLiteralTypes=*/true) ||
  9543. EStatus.HasSideEffects)
  9544. return false;
  9545. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  9546. Value);
  9547. }
  9548. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  9549. /// constant folded, but discard the result.
  9550. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  9551. EvalResult Result;
  9552. return EvaluateAsRValue(Result, Ctx) &&
  9553. !hasUnacceptableSideEffect(Result, SEK);
  9554. }
  9555. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  9556. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  9557. EvalResult EvalResult;
  9558. EvalResult.Diag = Diag;
  9559. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  9560. (void)Result;
  9561. assert(Result && "Could not evaluate expression");
  9562. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  9563. return EvalResult.Val.getInt();
  9564. }
  9565. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  9566. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  9567. EvalResult EvalResult;
  9568. EvalResult.Diag = Diag;
  9569. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  9570. bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val);
  9571. (void)Result;
  9572. assert(Result && "Could not evaluate expression");
  9573. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  9574. return EvalResult.Val.getInt();
  9575. }
  9576. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  9577. bool IsConst;
  9578. EvalResult EvalResult;
  9579. if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
  9580. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  9581. (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
  9582. }
  9583. }
  9584. bool Expr::EvalResult::isGlobalLValue() const {
  9585. assert(Val.isLValue());
  9586. return IsGlobalLValue(Val.getLValueBase());
  9587. }
  9588. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  9589. /// an integer constant expression.
  9590. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  9591. /// comma, etc
  9592. // CheckICE - This function does the fundamental ICE checking: the returned
  9593. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  9594. // and a (possibly null) SourceLocation indicating the location of the problem.
  9595. //
  9596. // Note that to reduce code duplication, this helper does no evaluation
  9597. // itself; the caller checks whether the expression is evaluatable, and
  9598. // in the rare cases where CheckICE actually cares about the evaluated
  9599. // value, it calls into Evaluate.
  9600. namespace {
  9601. enum ICEKind {
  9602. /// This expression is an ICE.
  9603. IK_ICE,
  9604. /// This expression is not an ICE, but if it isn't evaluated, it's
  9605. /// a legal subexpression for an ICE. This return value is used to handle
  9606. /// the comma operator in C99 mode, and non-constant subexpressions.
  9607. IK_ICEIfUnevaluated,
  9608. /// This expression is not an ICE, and is not a legal subexpression for one.
  9609. IK_NotICE
  9610. };
  9611. struct ICEDiag {
  9612. ICEKind Kind;
  9613. SourceLocation Loc;
  9614. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  9615. };
  9616. }
  9617. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  9618. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  9619. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  9620. Expr::EvalResult EVResult;
  9621. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  9622. !EVResult.Val.isInt())
  9623. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9624. return NoDiag();
  9625. }
  9626. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  9627. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  9628. if (!E->getType()->isIntegralOrEnumerationType())
  9629. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9630. switch (E->getStmtClass()) {
  9631. #define ABSTRACT_STMT(Node)
  9632. #define STMT(Node, Base) case Expr::Node##Class:
  9633. #define EXPR(Node, Base)
  9634. #include "clang/AST/StmtNodes.inc"
  9635. case Expr::PredefinedExprClass:
  9636. case Expr::FloatingLiteralClass:
  9637. case Expr::ImaginaryLiteralClass:
  9638. case Expr::StringLiteralClass:
  9639. case Expr::ArraySubscriptExprClass:
  9640. case Expr::OMPArraySectionExprClass:
  9641. case Expr::MemberExprClass:
  9642. case Expr::CompoundAssignOperatorClass:
  9643. case Expr::CompoundLiteralExprClass:
  9644. case Expr::ExtVectorElementExprClass:
  9645. case Expr::DesignatedInitExprClass:
  9646. case Expr::ArrayInitLoopExprClass:
  9647. case Expr::ArrayInitIndexExprClass:
  9648. case Expr::NoInitExprClass:
  9649. case Expr::DesignatedInitUpdateExprClass:
  9650. case Expr::ImplicitValueInitExprClass:
  9651. case Expr::ParenListExprClass:
  9652. case Expr::VAArgExprClass:
  9653. case Expr::AddrLabelExprClass:
  9654. case Expr::StmtExprClass:
  9655. case Expr::CXXMemberCallExprClass:
  9656. case Expr::CUDAKernelCallExprClass:
  9657. case Expr::CXXDynamicCastExprClass:
  9658. case Expr::CXXTypeidExprClass:
  9659. case Expr::CXXUuidofExprClass:
  9660. case Expr::MSPropertyRefExprClass:
  9661. case Expr::MSPropertySubscriptExprClass:
  9662. case Expr::CXXNullPtrLiteralExprClass:
  9663. case Expr::UserDefinedLiteralClass:
  9664. case Expr::CXXThisExprClass:
  9665. case Expr::CXXThrowExprClass:
  9666. case Expr::CXXNewExprClass:
  9667. case Expr::CXXDeleteExprClass:
  9668. case Expr::CXXPseudoDestructorExprClass:
  9669. case Expr::UnresolvedLookupExprClass:
  9670. case Expr::TypoExprClass:
  9671. case Expr::DependentScopeDeclRefExprClass:
  9672. case Expr::CXXConstructExprClass:
  9673. case Expr::CXXInheritedCtorInitExprClass:
  9674. case Expr::CXXStdInitializerListExprClass:
  9675. case Expr::CXXBindTemporaryExprClass:
  9676. case Expr::ExprWithCleanupsClass:
  9677. case Expr::CXXTemporaryObjectExprClass:
  9678. case Expr::CXXUnresolvedConstructExprClass:
  9679. case Expr::CXXDependentScopeMemberExprClass:
  9680. case Expr::UnresolvedMemberExprClass:
  9681. case Expr::ObjCStringLiteralClass:
  9682. case Expr::ObjCBoxedExprClass:
  9683. case Expr::ObjCArrayLiteralClass:
  9684. case Expr::ObjCDictionaryLiteralClass:
  9685. case Expr::ObjCEncodeExprClass:
  9686. case Expr::ObjCMessageExprClass:
  9687. case Expr::ObjCSelectorExprClass:
  9688. case Expr::ObjCProtocolExprClass:
  9689. case Expr::ObjCIvarRefExprClass:
  9690. case Expr::ObjCPropertyRefExprClass:
  9691. case Expr::ObjCSubscriptRefExprClass:
  9692. case Expr::ObjCIsaExprClass:
  9693. case Expr::ObjCAvailabilityCheckExprClass:
  9694. case Expr::ShuffleVectorExprClass:
  9695. case Expr::ConvertVectorExprClass:
  9696. case Expr::BlockExprClass:
  9697. case Expr::NoStmtClass:
  9698. case Expr::OpaqueValueExprClass:
  9699. case Expr::PackExpansionExprClass:
  9700. case Expr::SubstNonTypeTemplateParmPackExprClass:
  9701. case Expr::FunctionParmPackExprClass:
  9702. case Expr::AsTypeExprClass:
  9703. case Expr::ObjCIndirectCopyRestoreExprClass:
  9704. case Expr::MaterializeTemporaryExprClass:
  9705. case Expr::PseudoObjectExprClass:
  9706. case Expr::AtomicExprClass:
  9707. case Expr::LambdaExprClass:
  9708. case Expr::CXXFoldExprClass:
  9709. case Expr::CoawaitExprClass:
  9710. case Expr::DependentCoawaitExprClass:
  9711. case Expr::CoyieldExprClass:
  9712. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9713. case Expr::InitListExprClass: {
  9714. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  9715. // form "T x = { a };" is equivalent to "T x = a;".
  9716. // Unless we're initializing a reference, T is a scalar as it is known to be
  9717. // of integral or enumeration type.
  9718. if (E->isRValue())
  9719. if (cast<InitListExpr>(E)->getNumInits() == 1)
  9720. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  9721. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9722. }
  9723. case Expr::SizeOfPackExprClass:
  9724. case Expr::GNUNullExprClass:
  9725. // GCC considers the GNU __null value to be an integral constant expression.
  9726. return NoDiag();
  9727. case Expr::SubstNonTypeTemplateParmExprClass:
  9728. return
  9729. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  9730. case Expr::ConstantExprClass:
  9731. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  9732. case Expr::ParenExprClass:
  9733. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  9734. case Expr::GenericSelectionExprClass:
  9735. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  9736. case Expr::IntegerLiteralClass:
  9737. case Expr::FixedPointLiteralClass:
  9738. case Expr::CharacterLiteralClass:
  9739. case Expr::ObjCBoolLiteralExprClass:
  9740. case Expr::CXXBoolLiteralExprClass:
  9741. case Expr::CXXScalarValueInitExprClass:
  9742. case Expr::TypeTraitExprClass:
  9743. case Expr::ArrayTypeTraitExprClass:
  9744. case Expr::ExpressionTraitExprClass:
  9745. case Expr::CXXNoexceptExprClass:
  9746. return NoDiag();
  9747. case Expr::CallExprClass:
  9748. case Expr::CXXOperatorCallExprClass: {
  9749. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  9750. // constant expressions, but they can never be ICEs because an ICE cannot
  9751. // contain an operand of (pointer to) function type.
  9752. const CallExpr *CE = cast<CallExpr>(E);
  9753. if (CE->getBuiltinCallee())
  9754. return CheckEvalInICE(E, Ctx);
  9755. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9756. }
  9757. case Expr::DeclRefExprClass: {
  9758. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  9759. return NoDiag();
  9760. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  9761. if (Ctx.getLangOpts().CPlusPlus &&
  9762. D && IsConstNonVolatile(D->getType())) {
  9763. // Parameter variables are never constants. Without this check,
  9764. // getAnyInitializer() can find a default argument, which leads
  9765. // to chaos.
  9766. if (isa<ParmVarDecl>(D))
  9767. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9768. // C++ 7.1.5.1p2
  9769. // A variable of non-volatile const-qualified integral or enumeration
  9770. // type initialized by an ICE can be used in ICEs.
  9771. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  9772. if (!Dcl->getType()->isIntegralOrEnumerationType())
  9773. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9774. const VarDecl *VD;
  9775. // Look for a declaration of this variable that has an initializer, and
  9776. // check whether it is an ICE.
  9777. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  9778. return NoDiag();
  9779. else
  9780. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9781. }
  9782. }
  9783. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9784. }
  9785. case Expr::UnaryOperatorClass: {
  9786. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  9787. switch (Exp->getOpcode()) {
  9788. case UO_PostInc:
  9789. case UO_PostDec:
  9790. case UO_PreInc:
  9791. case UO_PreDec:
  9792. case UO_AddrOf:
  9793. case UO_Deref:
  9794. case UO_Coawait:
  9795. // C99 6.6/3 allows increment and decrement within unevaluated
  9796. // subexpressions of constant expressions, but they can never be ICEs
  9797. // because an ICE cannot contain an lvalue operand.
  9798. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9799. case UO_Extension:
  9800. case UO_LNot:
  9801. case UO_Plus:
  9802. case UO_Minus:
  9803. case UO_Not:
  9804. case UO_Real:
  9805. case UO_Imag:
  9806. return CheckICE(Exp->getSubExpr(), Ctx);
  9807. }
  9808. // OffsetOf falls through here.
  9809. LLVM_FALLTHROUGH;
  9810. }
  9811. case Expr::OffsetOfExprClass: {
  9812. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  9813. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  9814. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  9815. // compliance: we should warn earlier for offsetof expressions with
  9816. // array subscripts that aren't ICEs, and if the array subscripts
  9817. // are ICEs, the value of the offsetof must be an integer constant.
  9818. return CheckEvalInICE(E, Ctx);
  9819. }
  9820. case Expr::UnaryExprOrTypeTraitExprClass: {
  9821. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  9822. if ((Exp->getKind() == UETT_SizeOf) &&
  9823. Exp->getTypeOfArgument()->isVariableArrayType())
  9824. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9825. return NoDiag();
  9826. }
  9827. case Expr::BinaryOperatorClass: {
  9828. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  9829. switch (Exp->getOpcode()) {
  9830. case BO_PtrMemD:
  9831. case BO_PtrMemI:
  9832. case BO_Assign:
  9833. case BO_MulAssign:
  9834. case BO_DivAssign:
  9835. case BO_RemAssign:
  9836. case BO_AddAssign:
  9837. case BO_SubAssign:
  9838. case BO_ShlAssign:
  9839. case BO_ShrAssign:
  9840. case BO_AndAssign:
  9841. case BO_XorAssign:
  9842. case BO_OrAssign:
  9843. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  9844. // constant expressions, but they can never be ICEs because an ICE cannot
  9845. // contain an lvalue operand.
  9846. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9847. case BO_Mul:
  9848. case BO_Div:
  9849. case BO_Rem:
  9850. case BO_Add:
  9851. case BO_Sub:
  9852. case BO_Shl:
  9853. case BO_Shr:
  9854. case BO_LT:
  9855. case BO_GT:
  9856. case BO_LE:
  9857. case BO_GE:
  9858. case BO_EQ:
  9859. case BO_NE:
  9860. case BO_And:
  9861. case BO_Xor:
  9862. case BO_Or:
  9863. case BO_Comma:
  9864. case BO_Cmp: {
  9865. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9866. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9867. if (Exp->getOpcode() == BO_Div ||
  9868. Exp->getOpcode() == BO_Rem) {
  9869. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  9870. // we don't evaluate one.
  9871. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  9872. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  9873. if (REval == 0)
  9874. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9875. if (REval.isSigned() && REval.isAllOnesValue()) {
  9876. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  9877. if (LEval.isMinSignedValue())
  9878. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9879. }
  9880. }
  9881. }
  9882. if (Exp->getOpcode() == BO_Comma) {
  9883. if (Ctx.getLangOpts().C99) {
  9884. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  9885. // if it isn't evaluated.
  9886. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  9887. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9888. } else {
  9889. // In both C89 and C++, commas in ICEs are illegal.
  9890. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9891. }
  9892. }
  9893. return Worst(LHSResult, RHSResult);
  9894. }
  9895. case BO_LAnd:
  9896. case BO_LOr: {
  9897. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9898. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9899. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  9900. // Rare case where the RHS has a comma "side-effect"; we need
  9901. // to actually check the condition to see whether the side
  9902. // with the comma is evaluated.
  9903. if ((Exp->getOpcode() == BO_LAnd) !=
  9904. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  9905. return RHSResult;
  9906. return NoDiag();
  9907. }
  9908. return Worst(LHSResult, RHSResult);
  9909. }
  9910. }
  9911. LLVM_FALLTHROUGH;
  9912. }
  9913. case Expr::ImplicitCastExprClass:
  9914. case Expr::CStyleCastExprClass:
  9915. case Expr::CXXFunctionalCastExprClass:
  9916. case Expr::CXXStaticCastExprClass:
  9917. case Expr::CXXReinterpretCastExprClass:
  9918. case Expr::CXXConstCastExprClass:
  9919. case Expr::ObjCBridgedCastExprClass: {
  9920. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  9921. if (isa<ExplicitCastExpr>(E)) {
  9922. if (const FloatingLiteral *FL
  9923. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  9924. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  9925. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  9926. APSInt IgnoredVal(DestWidth, !DestSigned);
  9927. bool Ignored;
  9928. // If the value does not fit in the destination type, the behavior is
  9929. // undefined, so we are not required to treat it as a constant
  9930. // expression.
  9931. if (FL->getValue().convertToInteger(IgnoredVal,
  9932. llvm::APFloat::rmTowardZero,
  9933. &Ignored) & APFloat::opInvalidOp)
  9934. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9935. return NoDiag();
  9936. }
  9937. }
  9938. switch (cast<CastExpr>(E)->getCastKind()) {
  9939. case CK_LValueToRValue:
  9940. case CK_AtomicToNonAtomic:
  9941. case CK_NonAtomicToAtomic:
  9942. case CK_NoOp:
  9943. case CK_IntegralToBoolean:
  9944. case CK_IntegralCast:
  9945. return CheckICE(SubExpr, Ctx);
  9946. default:
  9947. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9948. }
  9949. }
  9950. case Expr::BinaryConditionalOperatorClass: {
  9951. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  9952. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  9953. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  9954. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9955. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  9956. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  9957. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  9958. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  9959. return FalseResult;
  9960. }
  9961. case Expr::ConditionalOperatorClass: {
  9962. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  9963. // If the condition (ignoring parens) is a __builtin_constant_p call,
  9964. // then only the true side is actually considered in an integer constant
  9965. // expression, and it is fully evaluated. This is an important GNU
  9966. // extension. See GCC PR38377 for discussion.
  9967. if (const CallExpr *CallCE
  9968. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  9969. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  9970. return CheckEvalInICE(E, Ctx);
  9971. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  9972. if (CondResult.Kind == IK_NotICE)
  9973. return CondResult;
  9974. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  9975. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9976. if (TrueResult.Kind == IK_NotICE)
  9977. return TrueResult;
  9978. if (FalseResult.Kind == IK_NotICE)
  9979. return FalseResult;
  9980. if (CondResult.Kind == IK_ICEIfUnevaluated)
  9981. return CondResult;
  9982. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  9983. return NoDiag();
  9984. // Rare case where the diagnostics depend on which side is evaluated
  9985. // Note that if we get here, CondResult is 0, and at least one of
  9986. // TrueResult and FalseResult is non-zero.
  9987. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  9988. return FalseResult;
  9989. return TrueResult;
  9990. }
  9991. case Expr::CXXDefaultArgExprClass:
  9992. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  9993. case Expr::CXXDefaultInitExprClass:
  9994. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  9995. case Expr::ChooseExprClass: {
  9996. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  9997. }
  9998. }
  9999. llvm_unreachable("Invalid StmtClass!");
  10000. }
  10001. /// Evaluate an expression as a C++11 integral constant expression.
  10002. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  10003. const Expr *E,
  10004. llvm::APSInt *Value,
  10005. SourceLocation *Loc) {
  10006. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10007. if (Loc) *Loc = E->getExprLoc();
  10008. return false;
  10009. }
  10010. APValue Result;
  10011. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  10012. return false;
  10013. if (!Result.isInt()) {
  10014. if (Loc) *Loc = E->getExprLoc();
  10015. return false;
  10016. }
  10017. if (Value) *Value = Result.getInt();
  10018. return true;
  10019. }
  10020. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  10021. SourceLocation *Loc) const {
  10022. if (Ctx.getLangOpts().CPlusPlus11)
  10023. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  10024. ICEDiag D = CheckICE(this, Ctx);
  10025. if (D.Kind != IK_ICE) {
  10026. if (Loc) *Loc = D.Loc;
  10027. return false;
  10028. }
  10029. return true;
  10030. }
  10031. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  10032. SourceLocation *Loc, bool isEvaluated) const {
  10033. if (Ctx.getLangOpts().CPlusPlus11)
  10034. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  10035. if (!isIntegerConstantExpr(Ctx, Loc))
  10036. return false;
  10037. // The only possible side-effects here are due to UB discovered in the
  10038. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  10039. // required to treat the expression as an ICE, so we produce the folded
  10040. // value.
  10041. if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
  10042. llvm_unreachable("ICE cannot be evaluated!");
  10043. return true;
  10044. }
  10045. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  10046. return CheckICE(this, Ctx).Kind == IK_ICE;
  10047. }
  10048. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  10049. SourceLocation *Loc) const {
  10050. // We support this checking in C++98 mode in order to diagnose compatibility
  10051. // issues.
  10052. assert(Ctx.getLangOpts().CPlusPlus);
  10053. // Build evaluation settings.
  10054. Expr::EvalStatus Status;
  10055. SmallVector<PartialDiagnosticAt, 8> Diags;
  10056. Status.Diag = &Diags;
  10057. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  10058. APValue Scratch;
  10059. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  10060. if (!Diags.empty()) {
  10061. IsConstExpr = false;
  10062. if (Loc) *Loc = Diags[0].first;
  10063. } else if (!IsConstExpr) {
  10064. // FIXME: This shouldn't happen.
  10065. if (Loc) *Loc = getExprLoc();
  10066. }
  10067. return IsConstExpr;
  10068. }
  10069. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  10070. const FunctionDecl *Callee,
  10071. ArrayRef<const Expr*> Args,
  10072. const Expr *This) const {
  10073. Expr::EvalStatus Status;
  10074. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  10075. LValue ThisVal;
  10076. const LValue *ThisPtr = nullptr;
  10077. if (This) {
  10078. #ifndef NDEBUG
  10079. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  10080. assert(MD && "Don't provide `this` for non-methods.");
  10081. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  10082. #endif
  10083. if (EvaluateObjectArgument(Info, This, ThisVal))
  10084. ThisPtr = &ThisVal;
  10085. if (Info.EvalStatus.HasSideEffects)
  10086. return false;
  10087. }
  10088. ArgVector ArgValues(Args.size());
  10089. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  10090. I != E; ++I) {
  10091. if ((*I)->isValueDependent() ||
  10092. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  10093. // If evaluation fails, throw away the argument entirely.
  10094. ArgValues[I - Args.begin()] = APValue();
  10095. if (Info.EvalStatus.HasSideEffects)
  10096. return false;
  10097. }
  10098. // Build fake call to Callee.
  10099. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  10100. ArgValues.data());
  10101. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  10102. }
  10103. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  10104. SmallVectorImpl<
  10105. PartialDiagnosticAt> &Diags) {
  10106. // FIXME: It would be useful to check constexpr function templates, but at the
  10107. // moment the constant expression evaluator cannot cope with the non-rigorous
  10108. // ASTs which we build for dependent expressions.
  10109. if (FD->isDependentContext())
  10110. return true;
  10111. Expr::EvalStatus Status;
  10112. Status.Diag = &Diags;
  10113. EvalInfo Info(FD->getASTContext(), Status,
  10114. EvalInfo::EM_PotentialConstantExpression);
  10115. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  10116. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  10117. // Fabricate an arbitrary expression on the stack and pretend that it
  10118. // is a temporary being used as the 'this' pointer.
  10119. LValue This;
  10120. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  10121. This.set({&VIE, Info.CurrentCall->Index});
  10122. ArrayRef<const Expr*> Args;
  10123. APValue Scratch;
  10124. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  10125. // Evaluate the call as a constant initializer, to allow the construction
  10126. // of objects of non-literal types.
  10127. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  10128. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  10129. } else {
  10130. SourceLocation Loc = FD->getLocation();
  10131. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  10132. Args, FD->getBody(), Info, Scratch, nullptr);
  10133. }
  10134. return Diags.empty();
  10135. }
  10136. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  10137. const FunctionDecl *FD,
  10138. SmallVectorImpl<
  10139. PartialDiagnosticAt> &Diags) {
  10140. Expr::EvalStatus Status;
  10141. Status.Diag = &Diags;
  10142. EvalInfo Info(FD->getASTContext(), Status,
  10143. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  10144. // Fabricate a call stack frame to give the arguments a plausible cover story.
  10145. ArrayRef<const Expr*> Args;
  10146. ArgVector ArgValues(0);
  10147. bool Success = EvaluateArgs(Args, ArgValues, Info);
  10148. (void)Success;
  10149. assert(Success &&
  10150. "Failed to set up arguments for potential constant evaluation");
  10151. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  10152. APValue ResultScratch;
  10153. Evaluate(ResultScratch, Info, E);
  10154. return Diags.empty();
  10155. }
  10156. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  10157. unsigned Type) const {
  10158. if (!getType()->isPointerType())
  10159. return false;
  10160. Expr::EvalStatus Status;
  10161. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  10162. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  10163. }