ExprConstant.cpp 242 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899
  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 rules only, at the moment), or, if folding failed too,
  27. // 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/CharUnits.h"
  39. #include "clang/AST/Expr.h"
  40. #include "clang/AST/RecordLayout.h"
  41. #include "clang/AST/StmtVisitor.h"
  42. #include "clang/AST/TypeLoc.h"
  43. #include "clang/Basic/Builtins.h"
  44. #include "clang/Basic/TargetInfo.h"
  45. #include "llvm/ADT/SmallString.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using llvm::APSInt;
  51. using llvm::APFloat;
  52. static bool IsGlobalLValue(APValue::LValueBase B);
  53. namespace {
  54. struct LValue;
  55. struct CallStackFrame;
  56. struct EvalInfo;
  57. static QualType getType(APValue::LValueBase B) {
  58. if (!B) return QualType();
  59. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
  60. return D->getType();
  61. return B.get<const Expr*>()->getType();
  62. }
  63. /// Get an LValue path entry, which is known to not be an array index, as a
  64. /// field or base class.
  65. static
  66. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  67. APValue::BaseOrMemberType Value;
  68. Value.setFromOpaqueValue(E.BaseOrMember);
  69. return Value;
  70. }
  71. /// Get an LValue path entry, which is known to not be an array index, as a
  72. /// field declaration.
  73. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  74. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  75. }
  76. /// Get an LValue path entry, which is known to not be an array index, as a
  77. /// base class declaration.
  78. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  79. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  80. }
  81. /// Determine whether this LValue path entry for a base class names a virtual
  82. /// base class.
  83. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  84. return getAsBaseOrMember(E).getInt();
  85. }
  86. /// Find the path length and type of the most-derived subobject in the given
  87. /// path, and find the size of the containing array, if any.
  88. static
  89. unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
  90. ArrayRef<APValue::LValuePathEntry> Path,
  91. uint64_t &ArraySize, QualType &Type) {
  92. unsigned MostDerivedLength = 0;
  93. Type = Base;
  94. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  95. if (Type->isArrayType()) {
  96. const ConstantArrayType *CAT =
  97. cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
  98. Type = CAT->getElementType();
  99. ArraySize = CAT->getSize().getZExtValue();
  100. MostDerivedLength = I + 1;
  101. } else if (Type->isAnyComplexType()) {
  102. const ComplexType *CT = Type->castAs<ComplexType>();
  103. Type = CT->getElementType();
  104. ArraySize = 2;
  105. MostDerivedLength = I + 1;
  106. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  107. Type = FD->getType();
  108. ArraySize = 0;
  109. MostDerivedLength = I + 1;
  110. } else {
  111. // Path[I] describes a base class.
  112. ArraySize = 0;
  113. }
  114. }
  115. return MostDerivedLength;
  116. }
  117. // The order of this enum is important for diagnostics.
  118. enum CheckSubobjectKind {
  119. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  120. CSK_This, CSK_Real, CSK_Imag
  121. };
  122. /// A path from a glvalue to a subobject of that glvalue.
  123. struct SubobjectDesignator {
  124. /// True if the subobject was named in a manner not supported by C++11. Such
  125. /// lvalues can still be folded, but they are not core constant expressions
  126. /// and we cannot perform lvalue-to-rvalue conversions on them.
  127. bool Invalid : 1;
  128. /// Is this a pointer one past the end of an object?
  129. bool IsOnePastTheEnd : 1;
  130. /// The length of the path to the most-derived object of which this is a
  131. /// subobject.
  132. unsigned MostDerivedPathLength : 30;
  133. /// The size of the array of which the most-derived object is an element, or
  134. /// 0 if the most-derived object is not an array element.
  135. uint64_t MostDerivedArraySize;
  136. /// The type of the most derived object referred to by this address.
  137. QualType MostDerivedType;
  138. typedef APValue::LValuePathEntry PathEntry;
  139. /// The entries on the path from the glvalue to the designated subobject.
  140. SmallVector<PathEntry, 8> Entries;
  141. SubobjectDesignator() : Invalid(true) {}
  142. explicit SubobjectDesignator(QualType T)
  143. : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
  144. MostDerivedArraySize(0), MostDerivedType(T) {}
  145. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  146. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  147. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  148. if (!Invalid) {
  149. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  150. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  151. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  152. if (V.getLValueBase())
  153. MostDerivedPathLength =
  154. findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
  155. V.getLValuePath(), MostDerivedArraySize,
  156. MostDerivedType);
  157. }
  158. }
  159. void setInvalid() {
  160. Invalid = true;
  161. Entries.clear();
  162. }
  163. /// Determine whether this is a one-past-the-end pointer.
  164. bool isOnePastTheEnd() const {
  165. if (IsOnePastTheEnd)
  166. return true;
  167. if (MostDerivedArraySize &&
  168. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  169. return true;
  170. return false;
  171. }
  172. /// Check that this refers to a valid subobject.
  173. bool isValidSubobject() const {
  174. if (Invalid)
  175. return false;
  176. return !isOnePastTheEnd();
  177. }
  178. /// Check that this refers to a valid subobject, and if not, produce a
  179. /// relevant diagnostic and set the designator as invalid.
  180. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  181. /// Update this designator to refer to the first element within this array.
  182. void addArrayUnchecked(const ConstantArrayType *CAT) {
  183. PathEntry Entry;
  184. Entry.ArrayIndex = 0;
  185. Entries.push_back(Entry);
  186. // This is a most-derived object.
  187. MostDerivedType = CAT->getElementType();
  188. MostDerivedArraySize = CAT->getSize().getZExtValue();
  189. MostDerivedPathLength = Entries.size();
  190. }
  191. /// Update this designator to refer to the given base or member of this
  192. /// object.
  193. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  194. PathEntry Entry;
  195. APValue::BaseOrMemberType Value(D, Virtual);
  196. Entry.BaseOrMember = Value.getOpaqueValue();
  197. Entries.push_back(Entry);
  198. // If this isn't a base class, it's a new most-derived object.
  199. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  200. MostDerivedType = FD->getType();
  201. MostDerivedArraySize = 0;
  202. MostDerivedPathLength = Entries.size();
  203. }
  204. }
  205. /// Update this designator to refer to the given complex component.
  206. void addComplexUnchecked(QualType EltTy, bool Imag) {
  207. PathEntry Entry;
  208. Entry.ArrayIndex = Imag;
  209. Entries.push_back(Entry);
  210. // This is technically a most-derived object, though in practice this
  211. // is unlikely to matter.
  212. MostDerivedType = EltTy;
  213. MostDerivedArraySize = 2;
  214. MostDerivedPathLength = Entries.size();
  215. }
  216. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
  217. /// Add N to the address of this subobject.
  218. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  219. if (Invalid) return;
  220. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
  221. Entries.back().ArrayIndex += N;
  222. if (Entries.back().ArrayIndex > MostDerivedArraySize) {
  223. diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
  224. setInvalid();
  225. }
  226. return;
  227. }
  228. // [expr.add]p4: For the purposes of these operators, a pointer to a
  229. // nonarray object behaves the same as a pointer to the first element of
  230. // an array of length one with the type of the object as its element type.
  231. if (IsOnePastTheEnd && N == (uint64_t)-1)
  232. IsOnePastTheEnd = false;
  233. else if (!IsOnePastTheEnd && N == 1)
  234. IsOnePastTheEnd = true;
  235. else if (N != 0) {
  236. diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
  237. setInvalid();
  238. }
  239. }
  240. };
  241. /// A stack frame in the constexpr call stack.
  242. struct CallStackFrame {
  243. EvalInfo &Info;
  244. /// Parent - The caller of this stack frame.
  245. CallStackFrame *Caller;
  246. /// CallLoc - The location of the call expression for this call.
  247. SourceLocation CallLoc;
  248. /// Callee - The function which was called.
  249. const FunctionDecl *Callee;
  250. /// Index - The call index of this call.
  251. unsigned Index;
  252. /// This - The binding for the this pointer in this call, if any.
  253. const LValue *This;
  254. /// ParmBindings - Parameter bindings for this function call, indexed by
  255. /// parameters' function scope indices.
  256. const APValue *Arguments;
  257. // Note that we intentionally use std::map here so that references to
  258. // values are stable.
  259. typedef std::map<const Expr*, APValue> MapTy;
  260. typedef MapTy::const_iterator temp_iterator;
  261. /// Temporaries - Temporary lvalues materialized within this stack frame.
  262. MapTy Temporaries;
  263. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  264. const FunctionDecl *Callee, const LValue *This,
  265. const APValue *Arguments);
  266. ~CallStackFrame();
  267. };
  268. /// A partial diagnostic which we might know in advance that we are not going
  269. /// to emit.
  270. class OptionalDiagnostic {
  271. PartialDiagnostic *Diag;
  272. public:
  273. explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
  274. template<typename T>
  275. OptionalDiagnostic &operator<<(const T &v) {
  276. if (Diag)
  277. *Diag << v;
  278. return *this;
  279. }
  280. OptionalDiagnostic &operator<<(const APSInt &I) {
  281. if (Diag) {
  282. SmallVector<char, 32> Buffer;
  283. I.toString(Buffer);
  284. *Diag << StringRef(Buffer.data(), Buffer.size());
  285. }
  286. return *this;
  287. }
  288. OptionalDiagnostic &operator<<(const APFloat &F) {
  289. if (Diag) {
  290. SmallVector<char, 32> Buffer;
  291. F.toString(Buffer);
  292. *Diag << StringRef(Buffer.data(), Buffer.size());
  293. }
  294. return *this;
  295. }
  296. };
  297. /// EvalInfo - This is a private struct used by the evaluator to capture
  298. /// information about a subexpression as it is folded. It retains information
  299. /// about the AST context, but also maintains information about the folded
  300. /// expression.
  301. ///
  302. /// If an expression could be evaluated, it is still possible it is not a C
  303. /// "integer constant expression" or constant expression. If not, this struct
  304. /// captures information about how and why not.
  305. ///
  306. /// One bit of information passed *into* the request for constant folding
  307. /// indicates whether the subexpression is "evaluated" or not according to C
  308. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  309. /// evaluate the expression regardless of what the RHS is, but C only allows
  310. /// certain things in certain situations.
  311. struct EvalInfo {
  312. ASTContext &Ctx;
  313. /// EvalStatus - Contains information about the evaluation.
  314. Expr::EvalStatus &EvalStatus;
  315. /// CurrentCall - The top of the constexpr call stack.
  316. CallStackFrame *CurrentCall;
  317. /// CallStackDepth - The number of calls in the call stack right now.
  318. unsigned CallStackDepth;
  319. /// NextCallIndex - The next call index to assign.
  320. unsigned NextCallIndex;
  321. /// BottomFrame - The frame in which evaluation started. This must be
  322. /// initialized after CurrentCall and CallStackDepth.
  323. CallStackFrame BottomFrame;
  324. /// EvaluatingDecl - This is the declaration whose initializer is being
  325. /// evaluated, if any.
  326. const VarDecl *EvaluatingDecl;
  327. /// EvaluatingDeclValue - This is the value being constructed for the
  328. /// declaration whose initializer is being evaluated, if any.
  329. APValue *EvaluatingDeclValue;
  330. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  331. /// notes attached to it will also be stored, otherwise they will not be.
  332. bool HasActiveDiagnostic;
  333. /// CheckingPotentialConstantExpression - Are we checking whether the
  334. /// expression is a potential constant expression? If so, some diagnostics
  335. /// are suppressed.
  336. bool CheckingPotentialConstantExpression;
  337. EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
  338. : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
  339. CallStackDepth(0), NextCallIndex(1),
  340. BottomFrame(*this, SourceLocation(), 0, 0, 0),
  341. EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
  342. CheckingPotentialConstantExpression(false) {}
  343. void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
  344. EvaluatingDecl = VD;
  345. EvaluatingDeclValue = &Value;
  346. }
  347. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  348. bool CheckCallLimit(SourceLocation Loc) {
  349. // Don't perform any constexpr calls (other than the call we're checking)
  350. // when checking a potential constant expression.
  351. if (CheckingPotentialConstantExpression && CallStackDepth > 1)
  352. return false;
  353. if (NextCallIndex == 0) {
  354. // NextCallIndex has wrapped around.
  355. Diag(Loc, diag::note_constexpr_call_limit_exceeded);
  356. return false;
  357. }
  358. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  359. return true;
  360. Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
  361. << getLangOpts().ConstexprCallDepth;
  362. return false;
  363. }
  364. CallStackFrame *getCallFrame(unsigned CallIndex) {
  365. assert(CallIndex && "no call index in getCallFrame");
  366. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  367. // be null in this loop.
  368. CallStackFrame *Frame = CurrentCall;
  369. while (Frame->Index > CallIndex)
  370. Frame = Frame->Caller;
  371. return (Frame->Index == CallIndex) ? Frame : 0;
  372. }
  373. private:
  374. /// Add a diagnostic to the diagnostics list.
  375. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  376. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  377. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  378. return EvalStatus.Diag->back().second;
  379. }
  380. /// Add notes containing a call stack to the current point of evaluation.
  381. void addCallStack(unsigned Limit);
  382. public:
  383. /// Diagnose that the evaluation cannot be folded.
  384. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
  385. = diag::note_invalid_subexpr_in_const_expr,
  386. unsigned ExtraNotes = 0) {
  387. // If we have a prior diagnostic, it will be noting that the expression
  388. // isn't a constant expression. This diagnostic is more important.
  389. // FIXME: We might want to show both diagnostics to the user.
  390. if (EvalStatus.Diag) {
  391. unsigned CallStackNotes = CallStackDepth - 1;
  392. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  393. if (Limit)
  394. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  395. if (CheckingPotentialConstantExpression)
  396. CallStackNotes = 0;
  397. HasActiveDiagnostic = true;
  398. EvalStatus.Diag->clear();
  399. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  400. addDiag(Loc, DiagId);
  401. if (!CheckingPotentialConstantExpression)
  402. addCallStack(Limit);
  403. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  404. }
  405. HasActiveDiagnostic = false;
  406. return OptionalDiagnostic();
  407. }
  408. OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
  409. = diag::note_invalid_subexpr_in_const_expr,
  410. unsigned ExtraNotes = 0) {
  411. if (EvalStatus.Diag)
  412. return Diag(E->getExprLoc(), DiagId, ExtraNotes);
  413. HasActiveDiagnostic = false;
  414. return OptionalDiagnostic();
  415. }
  416. /// Diagnose that the evaluation does not produce a C++11 core constant
  417. /// expression.
  418. template<typename LocArg>
  419. OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
  420. = diag::note_invalid_subexpr_in_const_expr,
  421. unsigned ExtraNotes = 0) {
  422. // Don't override a previous diagnostic.
  423. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  424. HasActiveDiagnostic = false;
  425. return OptionalDiagnostic();
  426. }
  427. return Diag(Loc, DiagId, ExtraNotes);
  428. }
  429. /// Add a note to a prior diagnostic.
  430. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  431. if (!HasActiveDiagnostic)
  432. return OptionalDiagnostic();
  433. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  434. }
  435. /// Add a stack of notes to a prior diagnostic.
  436. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  437. if (HasActiveDiagnostic) {
  438. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  439. Diags.begin(), Diags.end());
  440. }
  441. }
  442. /// Should we continue evaluation as much as possible after encountering a
  443. /// construct which can't be folded?
  444. bool keepEvaluatingAfterFailure() {
  445. return CheckingPotentialConstantExpression &&
  446. EvalStatus.Diag && EvalStatus.Diag->empty();
  447. }
  448. };
  449. /// Object used to treat all foldable expressions as constant expressions.
  450. struct FoldConstant {
  451. bool Enabled;
  452. explicit FoldConstant(EvalInfo &Info)
  453. : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
  454. !Info.EvalStatus.HasSideEffects) {
  455. }
  456. // Treat the value we've computed since this object was created as constant.
  457. void Fold(EvalInfo &Info) {
  458. if (Enabled && !Info.EvalStatus.Diag->empty() &&
  459. !Info.EvalStatus.HasSideEffects)
  460. Info.EvalStatus.Diag->clear();
  461. }
  462. };
  463. /// RAII object used to suppress diagnostics and side-effects from a
  464. /// speculative evaluation.
  465. class SpeculativeEvaluationRAII {
  466. EvalInfo &Info;
  467. Expr::EvalStatus Old;
  468. public:
  469. SpeculativeEvaluationRAII(EvalInfo &Info,
  470. SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
  471. : Info(Info), Old(Info.EvalStatus) {
  472. Info.EvalStatus.Diag = NewDiag;
  473. }
  474. ~SpeculativeEvaluationRAII() {
  475. Info.EvalStatus = Old;
  476. }
  477. };
  478. }
  479. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  480. CheckSubobjectKind CSK) {
  481. if (Invalid)
  482. return false;
  483. if (isOnePastTheEnd()) {
  484. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  485. << CSK;
  486. setInvalid();
  487. return false;
  488. }
  489. return true;
  490. }
  491. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  492. const Expr *E, uint64_t N) {
  493. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
  494. Info.CCEDiag(E, diag::note_constexpr_array_index)
  495. << static_cast<int>(N) << /*array*/ 0
  496. << static_cast<unsigned>(MostDerivedArraySize);
  497. else
  498. Info.CCEDiag(E, diag::note_constexpr_array_index)
  499. << static_cast<int>(N) << /*non-array*/ 1;
  500. setInvalid();
  501. }
  502. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  503. const FunctionDecl *Callee, const LValue *This,
  504. const APValue *Arguments)
  505. : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
  506. Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
  507. Info.CurrentCall = this;
  508. ++Info.CallStackDepth;
  509. }
  510. CallStackFrame::~CallStackFrame() {
  511. assert(Info.CurrentCall == this && "calls retired out of order");
  512. --Info.CallStackDepth;
  513. Info.CurrentCall = Caller;
  514. }
  515. /// Produce a string describing the given constexpr call.
  516. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  517. unsigned ArgIndex = 0;
  518. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  519. !isa<CXXConstructorDecl>(Frame->Callee) &&
  520. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  521. if (!IsMemberCall)
  522. Out << *Frame->Callee << '(';
  523. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  524. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  525. if (ArgIndex > (unsigned)IsMemberCall)
  526. Out << ", ";
  527. const ParmVarDecl *Param = *I;
  528. const APValue &Arg = Frame->Arguments[ArgIndex];
  529. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  530. if (ArgIndex == 0 && IsMemberCall)
  531. Out << "->" << *Frame->Callee << '(';
  532. }
  533. Out << ')';
  534. }
  535. void EvalInfo::addCallStack(unsigned Limit) {
  536. // Determine which calls to skip, if any.
  537. unsigned ActiveCalls = CallStackDepth - 1;
  538. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  539. if (Limit && Limit < ActiveCalls) {
  540. SkipStart = Limit / 2 + Limit % 2;
  541. SkipEnd = ActiveCalls - Limit / 2;
  542. }
  543. // Walk the call stack and add the diagnostics.
  544. unsigned CallIdx = 0;
  545. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  546. Frame = Frame->Caller, ++CallIdx) {
  547. // Skip this call?
  548. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  549. if (CallIdx == SkipStart) {
  550. // Note that we're skipping calls.
  551. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  552. << unsigned(ActiveCalls - Limit);
  553. }
  554. continue;
  555. }
  556. SmallVector<char, 128> Buffer;
  557. llvm::raw_svector_ostream Out(Buffer);
  558. describeCall(Frame, Out);
  559. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  560. }
  561. }
  562. namespace {
  563. struct ComplexValue {
  564. private:
  565. bool IsInt;
  566. public:
  567. APSInt IntReal, IntImag;
  568. APFloat FloatReal, FloatImag;
  569. ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
  570. void makeComplexFloat() { IsInt = false; }
  571. bool isComplexFloat() const { return !IsInt; }
  572. APFloat &getComplexFloatReal() { return FloatReal; }
  573. APFloat &getComplexFloatImag() { return FloatImag; }
  574. void makeComplexInt() { IsInt = true; }
  575. bool isComplexInt() const { return IsInt; }
  576. APSInt &getComplexIntReal() { return IntReal; }
  577. APSInt &getComplexIntImag() { return IntImag; }
  578. void moveInto(APValue &v) const {
  579. if (isComplexFloat())
  580. v = APValue(FloatReal, FloatImag);
  581. else
  582. v = APValue(IntReal, IntImag);
  583. }
  584. void setFrom(const APValue &v) {
  585. assert(v.isComplexFloat() || v.isComplexInt());
  586. if (v.isComplexFloat()) {
  587. makeComplexFloat();
  588. FloatReal = v.getComplexFloatReal();
  589. FloatImag = v.getComplexFloatImag();
  590. } else {
  591. makeComplexInt();
  592. IntReal = v.getComplexIntReal();
  593. IntImag = v.getComplexIntImag();
  594. }
  595. }
  596. };
  597. struct LValue {
  598. APValue::LValueBase Base;
  599. CharUnits Offset;
  600. unsigned CallIndex;
  601. SubobjectDesignator Designator;
  602. const APValue::LValueBase getLValueBase() const { return Base; }
  603. CharUnits &getLValueOffset() { return Offset; }
  604. const CharUnits &getLValueOffset() const { return Offset; }
  605. unsigned getLValueCallIndex() const { return CallIndex; }
  606. SubobjectDesignator &getLValueDesignator() { return Designator; }
  607. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  608. void moveInto(APValue &V) const {
  609. if (Designator.Invalid)
  610. V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
  611. else
  612. V = APValue(Base, Offset, Designator.Entries,
  613. Designator.IsOnePastTheEnd, CallIndex);
  614. }
  615. void setFrom(ASTContext &Ctx, const APValue &V) {
  616. assert(V.isLValue());
  617. Base = V.getLValueBase();
  618. Offset = V.getLValueOffset();
  619. CallIndex = V.getLValueCallIndex();
  620. Designator = SubobjectDesignator(Ctx, V);
  621. }
  622. void set(APValue::LValueBase B, unsigned I = 0) {
  623. Base = B;
  624. Offset = CharUnits::Zero();
  625. CallIndex = I;
  626. Designator = SubobjectDesignator(getType(B));
  627. }
  628. // Check that this LValue is not based on a null pointer. If it is, produce
  629. // a diagnostic and mark the designator as invalid.
  630. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  631. CheckSubobjectKind CSK) {
  632. if (Designator.Invalid)
  633. return false;
  634. if (!Base) {
  635. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  636. << CSK;
  637. Designator.setInvalid();
  638. return false;
  639. }
  640. return true;
  641. }
  642. // Check this LValue refers to an object. If not, set the designator to be
  643. // invalid and emit a diagnostic.
  644. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  645. // Outside C++11, do not build a designator referring to a subobject of
  646. // any object: we won't use such a designator for anything.
  647. if (!Info.getLangOpts().CPlusPlus11)
  648. Designator.setInvalid();
  649. return checkNullPointer(Info, E, CSK) &&
  650. Designator.checkSubobject(Info, E, CSK);
  651. }
  652. void addDecl(EvalInfo &Info, const Expr *E,
  653. const Decl *D, bool Virtual = false) {
  654. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  655. Designator.addDeclUnchecked(D, Virtual);
  656. }
  657. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  658. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  659. Designator.addArrayUnchecked(CAT);
  660. }
  661. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  662. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  663. Designator.addComplexUnchecked(EltTy, Imag);
  664. }
  665. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  666. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  667. Designator.adjustIndex(Info, E, N);
  668. }
  669. };
  670. struct MemberPtr {
  671. MemberPtr() {}
  672. explicit MemberPtr(const ValueDecl *Decl) :
  673. DeclAndIsDerivedMember(Decl, false), Path() {}
  674. /// The member or (direct or indirect) field referred to by this member
  675. /// pointer, or 0 if this is a null member pointer.
  676. const ValueDecl *getDecl() const {
  677. return DeclAndIsDerivedMember.getPointer();
  678. }
  679. /// Is this actually a member of some type derived from the relevant class?
  680. bool isDerivedMember() const {
  681. return DeclAndIsDerivedMember.getInt();
  682. }
  683. /// Get the class which the declaration actually lives in.
  684. const CXXRecordDecl *getContainingRecord() const {
  685. return cast<CXXRecordDecl>(
  686. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  687. }
  688. void moveInto(APValue &V) const {
  689. V = APValue(getDecl(), isDerivedMember(), Path);
  690. }
  691. void setFrom(const APValue &V) {
  692. assert(V.isMemberPointer());
  693. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  694. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  695. Path.clear();
  696. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  697. Path.insert(Path.end(), P.begin(), P.end());
  698. }
  699. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  700. /// whether the member is a member of some class derived from the class type
  701. /// of the member pointer.
  702. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  703. /// Path - The path of base/derived classes from the member declaration's
  704. /// class (exclusive) to the class type of the member pointer (inclusive).
  705. SmallVector<const CXXRecordDecl*, 4> Path;
  706. /// Perform a cast towards the class of the Decl (either up or down the
  707. /// hierarchy).
  708. bool castBack(const CXXRecordDecl *Class) {
  709. assert(!Path.empty());
  710. const CXXRecordDecl *Expected;
  711. if (Path.size() >= 2)
  712. Expected = Path[Path.size() - 2];
  713. else
  714. Expected = getContainingRecord();
  715. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  716. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  717. // if B does not contain the original member and is not a base or
  718. // derived class of the class containing the original member, the result
  719. // of the cast is undefined.
  720. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  721. // (D::*). We consider that to be a language defect.
  722. return false;
  723. }
  724. Path.pop_back();
  725. return true;
  726. }
  727. /// Perform a base-to-derived member pointer cast.
  728. bool castToDerived(const CXXRecordDecl *Derived) {
  729. if (!getDecl())
  730. return true;
  731. if (!isDerivedMember()) {
  732. Path.push_back(Derived);
  733. return true;
  734. }
  735. if (!castBack(Derived))
  736. return false;
  737. if (Path.empty())
  738. DeclAndIsDerivedMember.setInt(false);
  739. return true;
  740. }
  741. /// Perform a derived-to-base member pointer cast.
  742. bool castToBase(const CXXRecordDecl *Base) {
  743. if (!getDecl())
  744. return true;
  745. if (Path.empty())
  746. DeclAndIsDerivedMember.setInt(true);
  747. if (isDerivedMember()) {
  748. Path.push_back(Base);
  749. return true;
  750. }
  751. return castBack(Base);
  752. }
  753. };
  754. /// Compare two member pointers, which are assumed to be of the same type.
  755. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  756. if (!LHS.getDecl() || !RHS.getDecl())
  757. return !LHS.getDecl() && !RHS.getDecl();
  758. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  759. return false;
  760. return LHS.Path == RHS.Path;
  761. }
  762. /// Kinds of constant expression checking, for diagnostics.
  763. enum CheckConstantExpressionKind {
  764. CCEK_Constant, ///< A normal constant.
  765. CCEK_ReturnValue, ///< A constexpr function return value.
  766. CCEK_MemberInit ///< A constexpr constructor mem-initializer.
  767. };
  768. }
  769. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  770. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  771. const LValue &This, const Expr *E,
  772. CheckConstantExpressionKind CCEK = CCEK_Constant,
  773. bool AllowNonLiteralTypes = false);
  774. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
  775. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
  776. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  777. EvalInfo &Info);
  778. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  779. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  780. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  781. EvalInfo &Info);
  782. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  783. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  784. //===----------------------------------------------------------------------===//
  785. // Misc utilities
  786. //===----------------------------------------------------------------------===//
  787. /// Should this call expression be treated as a string literal?
  788. static bool IsStringLiteralCall(const CallExpr *E) {
  789. unsigned Builtin = E->isBuiltinCall();
  790. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  791. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  792. }
  793. static bool IsGlobalLValue(APValue::LValueBase B) {
  794. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  795. // constant expression of pointer type that evaluates to...
  796. // ... a null pointer value, or a prvalue core constant expression of type
  797. // std::nullptr_t.
  798. if (!B) return true;
  799. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  800. // ... the address of an object with static storage duration,
  801. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  802. return VD->hasGlobalStorage();
  803. // ... the address of a function,
  804. return isa<FunctionDecl>(D);
  805. }
  806. const Expr *E = B.get<const Expr*>();
  807. switch (E->getStmtClass()) {
  808. default:
  809. return false;
  810. case Expr::CompoundLiteralExprClass: {
  811. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  812. return CLE->isFileScope() && CLE->isLValue();
  813. }
  814. // A string literal has static storage duration.
  815. case Expr::StringLiteralClass:
  816. case Expr::PredefinedExprClass:
  817. case Expr::ObjCStringLiteralClass:
  818. case Expr::ObjCEncodeExprClass:
  819. case Expr::CXXTypeidExprClass:
  820. case Expr::CXXUuidofExprClass:
  821. return true;
  822. case Expr::CallExprClass:
  823. return IsStringLiteralCall(cast<CallExpr>(E));
  824. // For GCC compatibility, &&label has static storage duration.
  825. case Expr::AddrLabelExprClass:
  826. return true;
  827. // A Block literal expression may be used as the initialization value for
  828. // Block variables at global or local static scope.
  829. case Expr::BlockExprClass:
  830. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  831. case Expr::ImplicitValueInitExprClass:
  832. // FIXME:
  833. // We can never form an lvalue with an implicit value initialization as its
  834. // base through expression evaluation, so these only appear in one case: the
  835. // implicit variable declaration we invent when checking whether a constexpr
  836. // constructor can produce a constant expression. We must assume that such
  837. // an expression might be a global lvalue.
  838. return true;
  839. }
  840. }
  841. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  842. assert(Base && "no location for a null lvalue");
  843. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  844. if (VD)
  845. Info.Note(VD->getLocation(), diag::note_declared_at);
  846. else
  847. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  848. diag::note_constexpr_temporary_here);
  849. }
  850. /// Check that this reference or pointer core constant expression is a valid
  851. /// value for an address or reference constant expression. Return true if we
  852. /// can fold this expression, whether or not it's a constant expression.
  853. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  854. QualType Type, const LValue &LVal) {
  855. bool IsReferenceType = Type->isReferenceType();
  856. APValue::LValueBase Base = LVal.getLValueBase();
  857. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  858. // Check that the object is a global. Note that the fake 'this' object we
  859. // manufacture when checking potential constant expressions is conservatively
  860. // assumed to be global here.
  861. if (!IsGlobalLValue(Base)) {
  862. if (Info.getLangOpts().CPlusPlus11) {
  863. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  864. Info.Diag(Loc, diag::note_constexpr_non_global, 1)
  865. << IsReferenceType << !Designator.Entries.empty()
  866. << !!VD << VD;
  867. NoteLValueLocation(Info, Base);
  868. } else {
  869. Info.Diag(Loc);
  870. }
  871. // Don't allow references to temporaries to escape.
  872. return false;
  873. }
  874. assert((Info.CheckingPotentialConstantExpression ||
  875. LVal.getLValueCallIndex() == 0) &&
  876. "have call index for global lvalue");
  877. // Check if this is a thread-local variable.
  878. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  879. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  880. if (Var->isThreadSpecified())
  881. return false;
  882. }
  883. }
  884. // Allow address constant expressions to be past-the-end pointers. This is
  885. // an extension: the standard requires them to point to an object.
  886. if (!IsReferenceType)
  887. return true;
  888. // A reference constant expression must refer to an object.
  889. if (!Base) {
  890. // FIXME: diagnostic
  891. Info.CCEDiag(Loc);
  892. return true;
  893. }
  894. // Does this refer one past the end of some object?
  895. if (Designator.isOnePastTheEnd()) {
  896. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  897. Info.Diag(Loc, diag::note_constexpr_past_end, 1)
  898. << !Designator.Entries.empty() << !!VD << VD;
  899. NoteLValueLocation(Info, Base);
  900. }
  901. return true;
  902. }
  903. /// Check that this core constant expression is of literal type, and if not,
  904. /// produce an appropriate diagnostic.
  905. static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
  906. if (!E->isRValue() || E->getType()->isLiteralType())
  907. return true;
  908. // Prvalue constant expressions must be of literal types.
  909. if (Info.getLangOpts().CPlusPlus11)
  910. Info.Diag(E, diag::note_constexpr_nonliteral)
  911. << E->getType();
  912. else
  913. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  914. return false;
  915. }
  916. /// Check that this core constant expression value is a valid value for a
  917. /// constant expression. If not, report an appropriate diagnostic. Does not
  918. /// check that the expression is of literal type.
  919. static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
  920. QualType Type, const APValue &Value) {
  921. // Core issue 1454: For a literal constant expression of array or class type,
  922. // each subobject of its value shall have been initialized by a constant
  923. // expression.
  924. if (Value.isArray()) {
  925. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  926. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  927. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  928. Value.getArrayInitializedElt(I)))
  929. return false;
  930. }
  931. if (!Value.hasArrayFiller())
  932. return true;
  933. return CheckConstantExpression(Info, DiagLoc, EltTy,
  934. Value.getArrayFiller());
  935. }
  936. if (Value.isUnion() && Value.getUnionField()) {
  937. return CheckConstantExpression(Info, DiagLoc,
  938. Value.getUnionField()->getType(),
  939. Value.getUnionValue());
  940. }
  941. if (Value.isStruct()) {
  942. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  943. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  944. unsigned BaseIndex = 0;
  945. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  946. End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
  947. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  948. Value.getStructBase(BaseIndex)))
  949. return false;
  950. }
  951. }
  952. for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
  953. I != E; ++I) {
  954. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  955. Value.getStructField(I->getFieldIndex())))
  956. return false;
  957. }
  958. }
  959. if (Value.isLValue()) {
  960. LValue LVal;
  961. LVal.setFrom(Info.Ctx, Value);
  962. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
  963. }
  964. // Everything else is fine.
  965. return true;
  966. }
  967. const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  968. return LVal.Base.dyn_cast<const ValueDecl*>();
  969. }
  970. static bool IsLiteralLValue(const LValue &Value) {
  971. return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
  972. }
  973. static bool IsWeakLValue(const LValue &Value) {
  974. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  975. return Decl && Decl->isWeak();
  976. }
  977. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  978. // A null base expression indicates a null pointer. These are always
  979. // evaluatable, and they are false unless the offset is zero.
  980. if (!Value.getLValueBase()) {
  981. Result = !Value.getLValueOffset().isZero();
  982. return true;
  983. }
  984. // We have a non-null base. These are generally known to be true, but if it's
  985. // a weak declaration it can be null at runtime.
  986. Result = true;
  987. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  988. return !Decl || !Decl->isWeak();
  989. }
  990. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  991. switch (Val.getKind()) {
  992. case APValue::Uninitialized:
  993. return false;
  994. case APValue::Int:
  995. Result = Val.getInt().getBoolValue();
  996. return true;
  997. case APValue::Float:
  998. Result = !Val.getFloat().isZero();
  999. return true;
  1000. case APValue::ComplexInt:
  1001. Result = Val.getComplexIntReal().getBoolValue() ||
  1002. Val.getComplexIntImag().getBoolValue();
  1003. return true;
  1004. case APValue::ComplexFloat:
  1005. Result = !Val.getComplexFloatReal().isZero() ||
  1006. !Val.getComplexFloatImag().isZero();
  1007. return true;
  1008. case APValue::LValue:
  1009. return EvalPointerValueAsBool(Val, Result);
  1010. case APValue::MemberPointer:
  1011. Result = Val.getMemberPointerDecl();
  1012. return true;
  1013. case APValue::Vector:
  1014. case APValue::Array:
  1015. case APValue::Struct:
  1016. case APValue::Union:
  1017. case APValue::AddrLabelDiff:
  1018. return false;
  1019. }
  1020. llvm_unreachable("unknown APValue kind");
  1021. }
  1022. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1023. EvalInfo &Info) {
  1024. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1025. APValue Val;
  1026. if (!Evaluate(Val, Info, E))
  1027. return false;
  1028. return HandleConversionToBool(Val, Result);
  1029. }
  1030. template<typename T>
  1031. static void HandleOverflow(EvalInfo &Info, const Expr *E,
  1032. const T &SrcValue, QualType DestType) {
  1033. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1034. << SrcValue << DestType;
  1035. }
  1036. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1037. QualType SrcType, const APFloat &Value,
  1038. QualType DestType, APSInt &Result) {
  1039. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1040. // Determine whether we are converting to unsigned or signed.
  1041. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1042. Result = APSInt(DestWidth, !DestSigned);
  1043. bool ignored;
  1044. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1045. & APFloat::opInvalidOp)
  1046. HandleOverflow(Info, E, Value, DestType);
  1047. return true;
  1048. }
  1049. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1050. QualType SrcType, QualType DestType,
  1051. APFloat &Result) {
  1052. APFloat Value = Result;
  1053. bool ignored;
  1054. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1055. APFloat::rmNearestTiesToEven, &ignored)
  1056. & APFloat::opOverflow)
  1057. HandleOverflow(Info, E, Value, DestType);
  1058. return true;
  1059. }
  1060. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1061. QualType DestType, QualType SrcType,
  1062. APSInt &Value) {
  1063. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1064. APSInt Result = Value;
  1065. // Figure out if this is a truncate, extend or noop cast.
  1066. // If the input is signed, do a sign extend, noop, or truncate.
  1067. Result = Result.extOrTrunc(DestWidth);
  1068. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1069. return Result;
  1070. }
  1071. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1072. QualType SrcType, const APSInt &Value,
  1073. QualType DestType, APFloat &Result) {
  1074. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1075. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1076. APFloat::rmNearestTiesToEven)
  1077. & APFloat::opOverflow)
  1078. HandleOverflow(Info, E, Value, DestType);
  1079. return true;
  1080. }
  1081. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1082. llvm::APInt &Res) {
  1083. APValue SVal;
  1084. if (!Evaluate(SVal, Info, E))
  1085. return false;
  1086. if (SVal.isInt()) {
  1087. Res = SVal.getInt();
  1088. return true;
  1089. }
  1090. if (SVal.isFloat()) {
  1091. Res = SVal.getFloat().bitcastToAPInt();
  1092. return true;
  1093. }
  1094. if (SVal.isVector()) {
  1095. QualType VecTy = E->getType();
  1096. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1097. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1098. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1099. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1100. Res = llvm::APInt::getNullValue(VecSize);
  1101. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1102. APValue &Elt = SVal.getVectorElt(i);
  1103. llvm::APInt EltAsInt;
  1104. if (Elt.isInt()) {
  1105. EltAsInt = Elt.getInt();
  1106. } else if (Elt.isFloat()) {
  1107. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1108. } else {
  1109. // Don't try to handle vectors of anything other than int or float
  1110. // (not sure if it's possible to hit this case).
  1111. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1112. return false;
  1113. }
  1114. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1115. if (BigEndian)
  1116. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1117. else
  1118. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1119. }
  1120. return true;
  1121. }
  1122. // Give up if the input isn't an int, float, or vector. For example, we
  1123. // reject "(v4i16)(intptr_t)&a".
  1124. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1125. return false;
  1126. }
  1127. /// Cast an lvalue referring to a base subobject to a derived class, by
  1128. /// truncating the lvalue's path to the given length.
  1129. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  1130. const RecordDecl *TruncatedType,
  1131. unsigned TruncatedElements) {
  1132. SubobjectDesignator &D = Result.Designator;
  1133. // Check we actually point to a derived class object.
  1134. if (TruncatedElements == D.Entries.size())
  1135. return true;
  1136. assert(TruncatedElements >= D.MostDerivedPathLength &&
  1137. "not casting to a derived class");
  1138. if (!Result.checkSubobject(Info, E, CSK_Derived))
  1139. return false;
  1140. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  1141. const RecordDecl *RD = TruncatedType;
  1142. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  1143. if (RD->isInvalidDecl()) return false;
  1144. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1145. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  1146. if (isVirtualBaseClass(D.Entries[I]))
  1147. Result.Offset -= Layout.getVBaseClassOffset(Base);
  1148. else
  1149. Result.Offset -= Layout.getBaseClassOffset(Base);
  1150. RD = Base;
  1151. }
  1152. D.Entries.resize(TruncatedElements);
  1153. return true;
  1154. }
  1155. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1156. const CXXRecordDecl *Derived,
  1157. const CXXRecordDecl *Base,
  1158. const ASTRecordLayout *RL = 0) {
  1159. if (!RL) {
  1160. if (Derived->isInvalidDecl()) return false;
  1161. RL = &Info.Ctx.getASTRecordLayout(Derived);
  1162. }
  1163. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  1164. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  1165. return true;
  1166. }
  1167. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1168. const CXXRecordDecl *DerivedDecl,
  1169. const CXXBaseSpecifier *Base) {
  1170. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  1171. if (!Base->isVirtual())
  1172. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  1173. SubobjectDesignator &D = Obj.Designator;
  1174. if (D.Invalid)
  1175. return false;
  1176. // Extract most-derived object and corresponding type.
  1177. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  1178. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  1179. return false;
  1180. // Find the virtual base class.
  1181. if (DerivedDecl->isInvalidDecl()) return false;
  1182. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  1183. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  1184. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  1185. return true;
  1186. }
  1187. /// Update LVal to refer to the given field, which must be a member of the type
  1188. /// currently described by LVal.
  1189. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  1190. const FieldDecl *FD,
  1191. const ASTRecordLayout *RL = 0) {
  1192. if (!RL) {
  1193. if (FD->getParent()->isInvalidDecl()) return false;
  1194. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  1195. }
  1196. unsigned I = FD->getFieldIndex();
  1197. LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
  1198. LVal.addDecl(Info, E, FD);
  1199. return true;
  1200. }
  1201. /// Update LVal to refer to the given indirect field.
  1202. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  1203. LValue &LVal,
  1204. const IndirectFieldDecl *IFD) {
  1205. for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
  1206. CE = IFD->chain_end(); C != CE; ++C)
  1207. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
  1208. return false;
  1209. return true;
  1210. }
  1211. /// Get the size of the given type in char units.
  1212. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  1213. QualType Type, CharUnits &Size) {
  1214. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  1215. // extension.
  1216. if (Type->isVoidType() || Type->isFunctionType()) {
  1217. Size = CharUnits::One();
  1218. return true;
  1219. }
  1220. if (!Type->isConstantSizeType()) {
  1221. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  1222. // FIXME: Better diagnostic.
  1223. Info.Diag(Loc);
  1224. return false;
  1225. }
  1226. Size = Info.Ctx.getTypeSizeInChars(Type);
  1227. return true;
  1228. }
  1229. /// Update a pointer value to model pointer arithmetic.
  1230. /// \param Info - Information about the ongoing evaluation.
  1231. /// \param E - The expression being evaluated, for diagnostic purposes.
  1232. /// \param LVal - The pointer value to be updated.
  1233. /// \param EltTy - The pointee type represented by LVal.
  1234. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  1235. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  1236. LValue &LVal, QualType EltTy,
  1237. int64_t Adjustment) {
  1238. CharUnits SizeOfPointee;
  1239. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  1240. return false;
  1241. // Compute the new offset in the appropriate width.
  1242. LVal.Offset += Adjustment * SizeOfPointee;
  1243. LVal.adjustIndex(Info, E, Adjustment);
  1244. return true;
  1245. }
  1246. /// Update an lvalue to refer to a component of a complex number.
  1247. /// \param Info - Information about the ongoing evaluation.
  1248. /// \param LVal - The lvalue to be updated.
  1249. /// \param EltTy - The complex number's component type.
  1250. /// \param Imag - False for the real component, true for the imaginary.
  1251. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  1252. LValue &LVal, QualType EltTy,
  1253. bool Imag) {
  1254. if (Imag) {
  1255. CharUnits SizeOfComponent;
  1256. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  1257. return false;
  1258. LVal.Offset += SizeOfComponent;
  1259. }
  1260. LVal.addComplex(Info, E, EltTy, Imag);
  1261. return true;
  1262. }
  1263. /// Try to evaluate the initializer for a variable declaration.
  1264. static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  1265. const VarDecl *VD,
  1266. CallStackFrame *Frame, APValue &Result) {
  1267. // If this is a parameter to an active constexpr function call, perform
  1268. // argument substitution.
  1269. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  1270. // Assume arguments of a potential constant expression are unknown
  1271. // constant expressions.
  1272. if (Info.CheckingPotentialConstantExpression)
  1273. return false;
  1274. if (!Frame || !Frame->Arguments) {
  1275. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1276. return false;
  1277. }
  1278. Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
  1279. return true;
  1280. }
  1281. // Dig out the initializer, and use the declaration which it's attached to.
  1282. const Expr *Init = VD->getAnyInitializer(VD);
  1283. if (!Init || Init->isValueDependent()) {
  1284. // If we're checking a potential constant expression, the variable could be
  1285. // initialized later.
  1286. if (!Info.CheckingPotentialConstantExpression)
  1287. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1288. return false;
  1289. }
  1290. // If we're currently evaluating the initializer of this declaration, use that
  1291. // in-flight value.
  1292. if (Info.EvaluatingDecl == VD) {
  1293. Result = *Info.EvaluatingDeclValue;
  1294. return !Result.isUninit();
  1295. }
  1296. // Never evaluate the initializer of a weak variable. We can't be sure that
  1297. // this is the definition which will be used.
  1298. if (VD->isWeak()) {
  1299. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1300. return false;
  1301. }
  1302. // Check that we can fold the initializer. In C++, we will have already done
  1303. // this in the cases where it matters for conformance.
  1304. SmallVector<PartialDiagnosticAt, 8> Notes;
  1305. if (!VD->evaluateValue(Notes)) {
  1306. Info.Diag(E, diag::note_constexpr_var_init_non_constant,
  1307. Notes.size() + 1) << VD;
  1308. Info.Note(VD->getLocation(), diag::note_declared_at);
  1309. Info.addNotes(Notes);
  1310. return false;
  1311. } else if (!VD->checkInitIsICE()) {
  1312. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  1313. Notes.size() + 1) << VD;
  1314. Info.Note(VD->getLocation(), diag::note_declared_at);
  1315. Info.addNotes(Notes);
  1316. }
  1317. Result = *VD->getEvaluatedValue();
  1318. return true;
  1319. }
  1320. static bool IsConstNonVolatile(QualType T) {
  1321. Qualifiers Quals = T.getQualifiers();
  1322. return Quals.hasConst() && !Quals.hasVolatile();
  1323. }
  1324. /// Get the base index of the given base class within an APValue representing
  1325. /// the given derived class.
  1326. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  1327. const CXXRecordDecl *Base) {
  1328. Base = Base->getCanonicalDecl();
  1329. unsigned Index = 0;
  1330. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  1331. E = Derived->bases_end(); I != E; ++I, ++Index) {
  1332. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  1333. return Index;
  1334. }
  1335. llvm_unreachable("base class missing from derived class's bases list");
  1336. }
  1337. /// Extract the value of a character from a string literal. CharType is used to
  1338. /// determine the expected signedness of the result -- a string literal used to
  1339. /// initialize an array of 'signed char' or 'unsigned char' might contain chars
  1340. /// of the wrong signedness.
  1341. static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  1342. uint64_t Index, QualType CharType) {
  1343. // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
  1344. const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
  1345. assert(S && "unexpected string literal expression kind");
  1346. assert(CharType->isIntegerType() && "unexpected character type");
  1347. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  1348. CharType->isUnsignedIntegerType());
  1349. if (Index < S->getLength())
  1350. Value = S->getCodeUnit(Index);
  1351. return Value;
  1352. }
  1353. /// Extract the designated sub-object of an rvalue.
  1354. static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
  1355. APValue &Obj, QualType ObjType,
  1356. const SubobjectDesignator &Sub, QualType SubType) {
  1357. if (Sub.Invalid)
  1358. // A diagnostic will have already been produced.
  1359. return false;
  1360. if (Sub.isOnePastTheEnd()) {
  1361. Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
  1362. (unsigned)diag::note_constexpr_read_past_end :
  1363. (unsigned)diag::note_invalid_subexpr_in_const_expr);
  1364. return false;
  1365. }
  1366. if (Sub.Entries.empty())
  1367. return true;
  1368. if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
  1369. // This object might be initialized later.
  1370. return false;
  1371. APValue *O = &Obj;
  1372. // Walk the designator's path to find the subobject.
  1373. for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
  1374. if (ObjType->isArrayType()) {
  1375. // Next subobject is an array element.
  1376. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  1377. assert(CAT && "vla in literal type?");
  1378. uint64_t Index = Sub.Entries[I].ArrayIndex;
  1379. if (CAT->getSize().ule(Index)) {
  1380. // Note, it should not be possible to form a pointer with a valid
  1381. // designator which points more than one past the end of the array.
  1382. Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
  1383. (unsigned)diag::note_constexpr_read_past_end :
  1384. (unsigned)diag::note_invalid_subexpr_in_const_expr);
  1385. return false;
  1386. }
  1387. // An array object is represented as either an Array APValue or as an
  1388. // LValue which refers to a string literal.
  1389. if (O->isLValue()) {
  1390. assert(I == N - 1 && "extracting subobject of character?");
  1391. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  1392. Obj = APValue(ExtractStringLiteralCharacter(
  1393. Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
  1394. return true;
  1395. } else if (O->getArrayInitializedElts() > Index)
  1396. O = &O->getArrayInitializedElt(Index);
  1397. else
  1398. O = &O->getArrayFiller();
  1399. ObjType = CAT->getElementType();
  1400. } else if (ObjType->isAnyComplexType()) {
  1401. // Next subobject is a complex number.
  1402. uint64_t Index = Sub.Entries[I].ArrayIndex;
  1403. if (Index > 1) {
  1404. Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
  1405. (unsigned)diag::note_constexpr_read_past_end :
  1406. (unsigned)diag::note_invalid_subexpr_in_const_expr);
  1407. return false;
  1408. }
  1409. assert(I == N - 1 && "extracting subobject of scalar?");
  1410. if (O->isComplexInt()) {
  1411. Obj = APValue(Index ? O->getComplexIntImag()
  1412. : O->getComplexIntReal());
  1413. } else {
  1414. assert(O->isComplexFloat());
  1415. Obj = APValue(Index ? O->getComplexFloatImag()
  1416. : O->getComplexFloatReal());
  1417. }
  1418. return true;
  1419. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  1420. if (Field->isMutable()) {
  1421. Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
  1422. << Field;
  1423. Info.Note(Field->getLocation(), diag::note_declared_at);
  1424. return false;
  1425. }
  1426. // Next subobject is a class, struct or union field.
  1427. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  1428. if (RD->isUnion()) {
  1429. const FieldDecl *UnionField = O->getUnionField();
  1430. if (!UnionField ||
  1431. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  1432. Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
  1433. << Field << !UnionField << UnionField;
  1434. return false;
  1435. }
  1436. O = &O->getUnionValue();
  1437. } else
  1438. O = &O->getStructField(Field->getFieldIndex());
  1439. ObjType = Field->getType();
  1440. if (ObjType.isVolatileQualified()) {
  1441. if (Info.getLangOpts().CPlusPlus) {
  1442. // FIXME: Include a description of the path to the volatile subobject.
  1443. Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
  1444. << 2 << Field;
  1445. Info.Note(Field->getLocation(), diag::note_declared_at);
  1446. } else {
  1447. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1448. }
  1449. return false;
  1450. }
  1451. } else {
  1452. // Next subobject is a base class.
  1453. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  1454. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  1455. O = &O->getStructBase(getBaseIndex(Derived, Base));
  1456. ObjType = Info.Ctx.getRecordType(Base);
  1457. }
  1458. if (O->isUninit()) {
  1459. if (!Info.CheckingPotentialConstantExpression)
  1460. Info.Diag(E, diag::note_constexpr_read_uninit);
  1461. return false;
  1462. }
  1463. }
  1464. // This may look super-stupid, but it serves an important purpose: if we just
  1465. // swapped Obj and *O, we'd create an object which had itself as a subobject.
  1466. // To avoid the leak, we ensure that Tmp ends up owning the original complete
  1467. // object, which is destroyed by Tmp's destructor.
  1468. APValue Tmp;
  1469. O->swap(Tmp);
  1470. Obj.swap(Tmp);
  1471. return true;
  1472. }
  1473. /// Find the position where two subobject designators diverge, or equivalently
  1474. /// the length of the common initial subsequence.
  1475. static unsigned FindDesignatorMismatch(QualType ObjType,
  1476. const SubobjectDesignator &A,
  1477. const SubobjectDesignator &B,
  1478. bool &WasArrayIndex) {
  1479. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  1480. for (/**/; I != N; ++I) {
  1481. if (!ObjType.isNull() &&
  1482. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  1483. // Next subobject is an array element.
  1484. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  1485. WasArrayIndex = true;
  1486. return I;
  1487. }
  1488. if (ObjType->isAnyComplexType())
  1489. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  1490. else
  1491. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  1492. } else {
  1493. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  1494. WasArrayIndex = false;
  1495. return I;
  1496. }
  1497. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  1498. // Next subobject is a field.
  1499. ObjType = FD->getType();
  1500. else
  1501. // Next subobject is a base class.
  1502. ObjType = QualType();
  1503. }
  1504. }
  1505. WasArrayIndex = false;
  1506. return I;
  1507. }
  1508. /// Determine whether the given subobject designators refer to elements of the
  1509. /// same array object.
  1510. static bool AreElementsOfSameArray(QualType ObjType,
  1511. const SubobjectDesignator &A,
  1512. const SubobjectDesignator &B) {
  1513. if (A.Entries.size() != B.Entries.size())
  1514. return false;
  1515. bool IsArray = A.MostDerivedArraySize != 0;
  1516. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  1517. // A is a subobject of the array element.
  1518. return false;
  1519. // If A (and B) designates an array element, the last entry will be the array
  1520. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  1521. // of length 1' case, and the entire path must match.
  1522. bool WasArrayIndex;
  1523. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  1524. return CommonLength >= A.Entries.size() - IsArray;
  1525. }
  1526. /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
  1527. /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
  1528. /// for looking up the glvalue referred to by an entity of reference type.
  1529. ///
  1530. /// \param Info - Information about the ongoing evaluation.
  1531. /// \param Conv - The expression for which we are performing the conversion.
  1532. /// Used for diagnostics.
  1533. /// \param Type - The type we expect this conversion to produce, before
  1534. /// stripping cv-qualifiers in the case of a non-clas type.
  1535. /// \param LVal - The glvalue on which we are attempting to perform this action.
  1536. /// \param RVal - The produced value will be placed here.
  1537. static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  1538. QualType Type,
  1539. const LValue &LVal, APValue &RVal) {
  1540. if (LVal.Designator.Invalid)
  1541. // A diagnostic will have already been produced.
  1542. return false;
  1543. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  1544. if (!LVal.Base) {
  1545. // FIXME: Indirection through a null pointer deserves a specific diagnostic.
  1546. Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
  1547. return false;
  1548. }
  1549. CallStackFrame *Frame = 0;
  1550. if (LVal.CallIndex) {
  1551. Frame = Info.getCallFrame(LVal.CallIndex);
  1552. if (!Frame) {
  1553. Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
  1554. NoteLValueLocation(Info, LVal.Base);
  1555. return false;
  1556. }
  1557. }
  1558. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  1559. // is not a constant expression (even if the object is non-volatile). We also
  1560. // apply this rule to C++98, in order to conform to the expected 'volatile'
  1561. // semantics.
  1562. if (Type.isVolatileQualified()) {
  1563. if (Info.getLangOpts().CPlusPlus)
  1564. Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
  1565. else
  1566. Info.Diag(Conv);
  1567. return false;
  1568. }
  1569. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  1570. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  1571. // In C++11, constexpr, non-volatile variables initialized with constant
  1572. // expressions are constant expressions too. Inside constexpr functions,
  1573. // parameters are constant expressions even if they're non-const.
  1574. // In C, such things can also be folded, although they are not ICEs.
  1575. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1576. if (VD) {
  1577. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  1578. VD = VDef;
  1579. }
  1580. if (!VD || VD->isInvalidDecl()) {
  1581. Info.Diag(Conv);
  1582. return false;
  1583. }
  1584. // DR1313: If the object is volatile-qualified but the glvalue was not,
  1585. // behavior is undefined so the result is not a constant expression.
  1586. QualType VT = VD->getType();
  1587. if (VT.isVolatileQualified()) {
  1588. if (Info.getLangOpts().CPlusPlus) {
  1589. Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
  1590. Info.Note(VD->getLocation(), diag::note_declared_at);
  1591. } else {
  1592. Info.Diag(Conv);
  1593. }
  1594. return false;
  1595. }
  1596. if (!isa<ParmVarDecl>(VD)) {
  1597. if (VD->isConstexpr()) {
  1598. // OK, we can read this variable.
  1599. } else if (VT->isIntegralOrEnumerationType()) {
  1600. if (!VT.isConstQualified()) {
  1601. if (Info.getLangOpts().CPlusPlus) {
  1602. Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  1603. Info.Note(VD->getLocation(), diag::note_declared_at);
  1604. } else {
  1605. Info.Diag(Conv);
  1606. }
  1607. return false;
  1608. }
  1609. } else if (VT->isFloatingType() && VT.isConstQualified()) {
  1610. // We support folding of const floating-point types, in order to make
  1611. // static const data members of such types (supported as an extension)
  1612. // more useful.
  1613. if (Info.getLangOpts().CPlusPlus11) {
  1614. Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  1615. Info.Note(VD->getLocation(), diag::note_declared_at);
  1616. } else {
  1617. Info.CCEDiag(Conv);
  1618. }
  1619. } else {
  1620. // FIXME: Allow folding of values of any literal type in all languages.
  1621. if (Info.getLangOpts().CPlusPlus11) {
  1622. Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  1623. Info.Note(VD->getLocation(), diag::note_declared_at);
  1624. } else {
  1625. Info.Diag(Conv);
  1626. }
  1627. return false;
  1628. }
  1629. }
  1630. if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
  1631. return false;
  1632. if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
  1633. return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
  1634. // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
  1635. // conversion. This happens when the declaration and the lvalue should be
  1636. // considered synonymous, for instance when initializing an array of char
  1637. // from a string literal. Continue as if the initializer lvalue was the
  1638. // value we were originally given.
  1639. assert(RVal.getLValueOffset().isZero() &&
  1640. "offset for lvalue init of non-reference");
  1641. Base = RVal.getLValueBase().get<const Expr*>();
  1642. if (unsigned CallIndex = RVal.getLValueCallIndex()) {
  1643. Frame = Info.getCallFrame(CallIndex);
  1644. if (!Frame) {
  1645. Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
  1646. NoteLValueLocation(Info, RVal.getLValueBase());
  1647. return false;
  1648. }
  1649. } else {
  1650. Frame = 0;
  1651. }
  1652. }
  1653. // Volatile temporary objects cannot be read in constant expressions.
  1654. if (Base->getType().isVolatileQualified()) {
  1655. if (Info.getLangOpts().CPlusPlus) {
  1656. Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
  1657. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  1658. } else {
  1659. Info.Diag(Conv);
  1660. }
  1661. return false;
  1662. }
  1663. if (Frame) {
  1664. // If this is a temporary expression with a nontrivial initializer, grab the
  1665. // value from the relevant stack frame.
  1666. RVal = Frame->Temporaries[Base];
  1667. } else if (const CompoundLiteralExpr *CLE
  1668. = dyn_cast<CompoundLiteralExpr>(Base)) {
  1669. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  1670. // initializer until now for such expressions. Such an expression can't be
  1671. // an ICE in C, so this only matters for fold.
  1672. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  1673. if (!Evaluate(RVal, Info, CLE->getInitializer()))
  1674. return false;
  1675. } else if (isa<StringLiteral>(Base)) {
  1676. // We represent a string literal array as an lvalue pointing at the
  1677. // corresponding expression, rather than building an array of chars.
  1678. // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
  1679. RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  1680. } else {
  1681. Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
  1682. return false;
  1683. }
  1684. return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
  1685. Type);
  1686. }
  1687. /// Build an lvalue for the object argument of a member function call.
  1688. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  1689. LValue &This) {
  1690. if (Object->getType()->isPointerType())
  1691. return EvaluatePointer(Object, This, Info);
  1692. if (Object->isGLValue())
  1693. return EvaluateLValue(Object, This, Info);
  1694. if (Object->getType()->isLiteralType())
  1695. return EvaluateTemporary(Object, This, Info);
  1696. return false;
  1697. }
  1698. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  1699. /// lvalue referring to the result.
  1700. ///
  1701. /// \param Info - Information about the ongoing evaluation.
  1702. /// \param BO - The member pointer access operation.
  1703. /// \param LV - Filled in with a reference to the resulting object.
  1704. /// \param IncludeMember - Specifies whether the member itself is included in
  1705. /// the resulting LValue subobject designator. This is not possible when
  1706. /// creating a bound member function.
  1707. /// \return The field or method declaration to which the member pointer refers,
  1708. /// or 0 if evaluation fails.
  1709. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  1710. const BinaryOperator *BO,
  1711. LValue &LV,
  1712. bool IncludeMember = true) {
  1713. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  1714. bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
  1715. if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
  1716. return 0;
  1717. MemberPtr MemPtr;
  1718. if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
  1719. return 0;
  1720. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  1721. // member value, the behavior is undefined.
  1722. if (!MemPtr.getDecl())
  1723. return 0;
  1724. if (!EvalObjOK)
  1725. return 0;
  1726. if (MemPtr.isDerivedMember()) {
  1727. // This is a member of some derived class. Truncate LV appropriately.
  1728. // The end of the derived-to-base path for the base object must match the
  1729. // derived-to-base path for the member pointer.
  1730. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  1731. LV.Designator.Entries.size())
  1732. return 0;
  1733. unsigned PathLengthToMember =
  1734. LV.Designator.Entries.size() - MemPtr.Path.size();
  1735. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  1736. const CXXRecordDecl *LVDecl = getAsBaseClass(
  1737. LV.Designator.Entries[PathLengthToMember + I]);
  1738. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  1739. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
  1740. return 0;
  1741. }
  1742. // Truncate the lvalue to the appropriate derived class.
  1743. if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
  1744. PathLengthToMember))
  1745. return 0;
  1746. } else if (!MemPtr.Path.empty()) {
  1747. // Extend the LValue path with the member pointer's path.
  1748. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  1749. MemPtr.Path.size() + IncludeMember);
  1750. // Walk down to the appropriate base class.
  1751. QualType LVType = BO->getLHS()->getType();
  1752. if (const PointerType *PT = LVType->getAs<PointerType>())
  1753. LVType = PT->getPointeeType();
  1754. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  1755. assert(RD && "member pointer access on non-class-type expression");
  1756. // The first class in the path is that of the lvalue.
  1757. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  1758. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  1759. if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
  1760. return 0;
  1761. RD = Base;
  1762. }
  1763. // Finally cast to the class containing the member.
  1764. if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
  1765. return 0;
  1766. }
  1767. // Add the member. Note that we cannot build bound member functions here.
  1768. if (IncludeMember) {
  1769. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  1770. if (!HandleLValueMember(Info, BO, LV, FD))
  1771. return 0;
  1772. } else if (const IndirectFieldDecl *IFD =
  1773. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  1774. if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
  1775. return 0;
  1776. } else {
  1777. llvm_unreachable("can't construct reference to bound member function");
  1778. }
  1779. }
  1780. return MemPtr.getDecl();
  1781. }
  1782. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  1783. /// the provided lvalue, which currently refers to the base object.
  1784. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  1785. LValue &Result) {
  1786. SubobjectDesignator &D = Result.Designator;
  1787. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  1788. return false;
  1789. QualType TargetQT = E->getType();
  1790. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  1791. TargetQT = PT->getPointeeType();
  1792. // Check this cast lands within the final derived-to-base subobject path.
  1793. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  1794. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  1795. << D.MostDerivedType << TargetQT;
  1796. return false;
  1797. }
  1798. // Check the type of the final cast. We don't need to check the path,
  1799. // since a cast can only be formed if the path is unique.
  1800. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  1801. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  1802. const CXXRecordDecl *FinalType;
  1803. if (NewEntriesSize == D.MostDerivedPathLength)
  1804. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  1805. else
  1806. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  1807. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  1808. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  1809. << D.MostDerivedType << TargetQT;
  1810. return false;
  1811. }
  1812. // Truncate the lvalue to the appropriate derived class.
  1813. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  1814. }
  1815. namespace {
  1816. enum EvalStmtResult {
  1817. /// Evaluation failed.
  1818. ESR_Failed,
  1819. /// Hit a 'return' statement.
  1820. ESR_Returned,
  1821. /// Evaluation succeeded.
  1822. ESR_Succeeded
  1823. };
  1824. }
  1825. // Evaluate a statement.
  1826. static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
  1827. const Stmt *S) {
  1828. switch (S->getStmtClass()) {
  1829. default:
  1830. return ESR_Failed;
  1831. case Stmt::NullStmtClass:
  1832. case Stmt::DeclStmtClass:
  1833. return ESR_Succeeded;
  1834. case Stmt::ReturnStmtClass: {
  1835. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  1836. if (!Evaluate(Result, Info, RetExpr))
  1837. return ESR_Failed;
  1838. return ESR_Returned;
  1839. }
  1840. case Stmt::CompoundStmtClass: {
  1841. const CompoundStmt *CS = cast<CompoundStmt>(S);
  1842. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  1843. BE = CS->body_end(); BI != BE; ++BI) {
  1844. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  1845. if (ESR != ESR_Succeeded)
  1846. return ESR;
  1847. }
  1848. return ESR_Succeeded;
  1849. }
  1850. }
  1851. }
  1852. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  1853. /// default constructor. If so, we'll fold it whether or not it's marked as
  1854. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  1855. /// so we need special handling.
  1856. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  1857. const CXXConstructorDecl *CD,
  1858. bool IsValueInitialization) {
  1859. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  1860. return false;
  1861. // Value-initialization does not call a trivial default constructor, so such a
  1862. // call is a core constant expression whether or not the constructor is
  1863. // constexpr.
  1864. if (!CD->isConstexpr() && !IsValueInitialization) {
  1865. if (Info.getLangOpts().CPlusPlus11) {
  1866. // FIXME: If DiagDecl is an implicitly-declared special member function,
  1867. // we should be much more explicit about why it's not constexpr.
  1868. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  1869. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  1870. Info.Note(CD->getLocation(), diag::note_declared_at);
  1871. } else {
  1872. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  1873. }
  1874. }
  1875. return true;
  1876. }
  1877. /// CheckConstexprFunction - Check that a function can be called in a constant
  1878. /// expression.
  1879. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  1880. const FunctionDecl *Declaration,
  1881. const FunctionDecl *Definition) {
  1882. // Potential constant expressions can contain calls to declared, but not yet
  1883. // defined, constexpr functions.
  1884. if (Info.CheckingPotentialConstantExpression && !Definition &&
  1885. Declaration->isConstexpr())
  1886. return false;
  1887. // Can we evaluate this function call?
  1888. if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
  1889. return true;
  1890. if (Info.getLangOpts().CPlusPlus11) {
  1891. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  1892. // FIXME: If DiagDecl is an implicitly-declared special member function, we
  1893. // should be much more explicit about why it's not constexpr.
  1894. Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
  1895. << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
  1896. << DiagDecl;
  1897. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  1898. } else {
  1899. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  1900. }
  1901. return false;
  1902. }
  1903. namespace {
  1904. typedef SmallVector<APValue, 8> ArgVector;
  1905. }
  1906. /// EvaluateArgs - Evaluate the arguments to a function call.
  1907. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  1908. EvalInfo &Info) {
  1909. bool Success = true;
  1910. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  1911. I != E; ++I) {
  1912. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  1913. // If we're checking for a potential constant expression, evaluate all
  1914. // initializers even if some of them fail.
  1915. if (!Info.keepEvaluatingAfterFailure())
  1916. return false;
  1917. Success = false;
  1918. }
  1919. }
  1920. return Success;
  1921. }
  1922. /// Evaluate a function call.
  1923. static bool HandleFunctionCall(SourceLocation CallLoc,
  1924. const FunctionDecl *Callee, const LValue *This,
  1925. ArrayRef<const Expr*> Args, const Stmt *Body,
  1926. EvalInfo &Info, APValue &Result) {
  1927. ArgVector ArgValues(Args.size());
  1928. if (!EvaluateArgs(Args, ArgValues, Info))
  1929. return false;
  1930. if (!Info.CheckCallLimit(CallLoc))
  1931. return false;
  1932. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  1933. return EvaluateStmt(Result, Info, Body) == ESR_Returned;
  1934. }
  1935. /// Evaluate a constructor call.
  1936. static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
  1937. ArrayRef<const Expr*> Args,
  1938. const CXXConstructorDecl *Definition,
  1939. EvalInfo &Info, APValue &Result) {
  1940. ArgVector ArgValues(Args.size());
  1941. if (!EvaluateArgs(Args, ArgValues, Info))
  1942. return false;
  1943. if (!Info.CheckCallLimit(CallLoc))
  1944. return false;
  1945. const CXXRecordDecl *RD = Definition->getParent();
  1946. if (RD->getNumVBases()) {
  1947. Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  1948. return false;
  1949. }
  1950. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
  1951. // If it's a delegating constructor, just delegate.
  1952. if (Definition->isDelegatingConstructor()) {
  1953. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  1954. return EvaluateInPlace(Result, Info, This, (*I)->getInit());
  1955. }
  1956. // For a trivial copy or move constructor, perform an APValue copy. This is
  1957. // essential for unions, where the operations performed by the constructor
  1958. // cannot be represented by ctor-initializers.
  1959. if (Definition->isDefaulted() &&
  1960. ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
  1961. (Definition->isMoveConstructor() && Definition->isTrivial()))) {
  1962. LValue RHS;
  1963. RHS.setFrom(Info.Ctx, ArgValues[0]);
  1964. return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  1965. RHS, Result);
  1966. }
  1967. // Reserve space for the struct members.
  1968. if (!RD->isUnion() && Result.isUninit())
  1969. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  1970. std::distance(RD->field_begin(), RD->field_end()));
  1971. if (RD->isInvalidDecl()) return false;
  1972. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1973. bool Success = true;
  1974. unsigned BasesSeen = 0;
  1975. #ifndef NDEBUG
  1976. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  1977. #endif
  1978. for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
  1979. E = Definition->init_end(); I != E; ++I) {
  1980. LValue Subobject = This;
  1981. APValue *Value = &Result;
  1982. // Determine the subobject to initialize.
  1983. if ((*I)->isBaseInitializer()) {
  1984. QualType BaseType((*I)->getBaseClass(), 0);
  1985. #ifndef NDEBUG
  1986. // Non-virtual base classes are initialized in the order in the class
  1987. // definition. We have already checked for virtual base classes.
  1988. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  1989. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  1990. "base class initializers not in expected order");
  1991. ++BaseIt;
  1992. #endif
  1993. if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
  1994. BaseType->getAsCXXRecordDecl(), &Layout))
  1995. return false;
  1996. Value = &Result.getStructBase(BasesSeen++);
  1997. } else if (FieldDecl *FD = (*I)->getMember()) {
  1998. if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
  1999. return false;
  2000. if (RD->isUnion()) {
  2001. Result = APValue(FD);
  2002. Value = &Result.getUnionValue();
  2003. } else {
  2004. Value = &Result.getStructField(FD->getFieldIndex());
  2005. }
  2006. } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
  2007. // Walk the indirect field decl's chain to find the object to initialize,
  2008. // and make sure we've initialized every step along it.
  2009. for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
  2010. CE = IFD->chain_end();
  2011. C != CE; ++C) {
  2012. FieldDecl *FD = cast<FieldDecl>(*C);
  2013. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  2014. // Switch the union field if it differs. This happens if we had
  2015. // preceding zero-initialization, and we're now initializing a union
  2016. // subobject other than the first.
  2017. // FIXME: In this case, the values of the other subobjects are
  2018. // specified, since zero-initialization sets all padding bits to zero.
  2019. if (Value->isUninit() ||
  2020. (Value->isUnion() && Value->getUnionField() != FD)) {
  2021. if (CD->isUnion())
  2022. *Value = APValue(FD);
  2023. else
  2024. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  2025. std::distance(CD->field_begin(), CD->field_end()));
  2026. }
  2027. if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
  2028. return false;
  2029. if (CD->isUnion())
  2030. Value = &Value->getUnionValue();
  2031. else
  2032. Value = &Value->getStructField(FD->getFieldIndex());
  2033. }
  2034. } else {
  2035. llvm_unreachable("unknown base initializer kind");
  2036. }
  2037. if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
  2038. (*I)->isBaseInitializer()
  2039. ? CCEK_Constant : CCEK_MemberInit)) {
  2040. // If we're checking for a potential constant expression, evaluate all
  2041. // initializers even if some of them fail.
  2042. if (!Info.keepEvaluatingAfterFailure())
  2043. return false;
  2044. Success = false;
  2045. }
  2046. }
  2047. return Success;
  2048. }
  2049. //===----------------------------------------------------------------------===//
  2050. // Generic Evaluation
  2051. //===----------------------------------------------------------------------===//
  2052. namespace {
  2053. // FIXME: RetTy is always bool. Remove it.
  2054. template <class Derived, typename RetTy=bool>
  2055. class ExprEvaluatorBase
  2056. : public ConstStmtVisitor<Derived, RetTy> {
  2057. private:
  2058. RetTy DerivedSuccess(const APValue &V, const Expr *E) {
  2059. return static_cast<Derived*>(this)->Success(V, E);
  2060. }
  2061. RetTy DerivedZeroInitialization(const Expr *E) {
  2062. return static_cast<Derived*>(this)->ZeroInitialization(E);
  2063. }
  2064. // Check whether a conditional operator with a non-constant condition is a
  2065. // potential constant expression. If neither arm is a potential constant
  2066. // expression, then the conditional operator is not either.
  2067. template<typename ConditionalOperator>
  2068. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  2069. assert(Info.CheckingPotentialConstantExpression);
  2070. // Speculatively evaluate both arms.
  2071. {
  2072. SmallVector<PartialDiagnosticAt, 8> Diag;
  2073. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  2074. StmtVisitorTy::Visit(E->getFalseExpr());
  2075. if (Diag.empty())
  2076. return;
  2077. Diag.clear();
  2078. StmtVisitorTy::Visit(E->getTrueExpr());
  2079. if (Diag.empty())
  2080. return;
  2081. }
  2082. Error(E, diag::note_constexpr_conditional_never_const);
  2083. }
  2084. template<typename ConditionalOperator>
  2085. bool HandleConditionalOperator(const ConditionalOperator *E) {
  2086. bool BoolResult;
  2087. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  2088. if (Info.CheckingPotentialConstantExpression)
  2089. CheckPotentialConstantConditional(E);
  2090. return false;
  2091. }
  2092. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  2093. return StmtVisitorTy::Visit(EvalExpr);
  2094. }
  2095. protected:
  2096. EvalInfo &Info;
  2097. typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
  2098. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  2099. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  2100. return Info.CCEDiag(E, D);
  2101. }
  2102. RetTy ZeroInitialization(const Expr *E) { return Error(E); }
  2103. public:
  2104. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  2105. EvalInfo &getEvalInfo() { return Info; }
  2106. /// Report an evaluation error. This should only be called when an error is
  2107. /// first discovered. When propagating an error, just return false.
  2108. bool Error(const Expr *E, diag::kind D) {
  2109. Info.Diag(E, D);
  2110. return false;
  2111. }
  2112. bool Error(const Expr *E) {
  2113. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  2114. }
  2115. RetTy VisitStmt(const Stmt *) {
  2116. llvm_unreachable("Expression evaluator should not be called on stmts");
  2117. }
  2118. RetTy VisitExpr(const Expr *E) {
  2119. return Error(E);
  2120. }
  2121. RetTy VisitParenExpr(const ParenExpr *E)
  2122. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2123. RetTy VisitUnaryExtension(const UnaryOperator *E)
  2124. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2125. RetTy VisitUnaryPlus(const UnaryOperator *E)
  2126. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2127. RetTy VisitChooseExpr(const ChooseExpr *E)
  2128. { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
  2129. RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  2130. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  2131. RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  2132. { return StmtVisitorTy::Visit(E->getReplacement()); }
  2133. RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
  2134. { return StmtVisitorTy::Visit(E->getExpr()); }
  2135. // We cannot create any objects for which cleanups are required, so there is
  2136. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  2137. RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
  2138. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2139. RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  2140. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  2141. return static_cast<Derived*>(this)->VisitCastExpr(E);
  2142. }
  2143. RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  2144. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  2145. return static_cast<Derived*>(this)->VisitCastExpr(E);
  2146. }
  2147. RetTy VisitBinaryOperator(const BinaryOperator *E) {
  2148. switch (E->getOpcode()) {
  2149. default:
  2150. return Error(E);
  2151. case BO_Comma:
  2152. VisitIgnoredValue(E->getLHS());
  2153. return StmtVisitorTy::Visit(E->getRHS());
  2154. case BO_PtrMemD:
  2155. case BO_PtrMemI: {
  2156. LValue Obj;
  2157. if (!HandleMemberPointerAccess(Info, E, Obj))
  2158. return false;
  2159. APValue Result;
  2160. if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  2161. return false;
  2162. return DerivedSuccess(Result, E);
  2163. }
  2164. }
  2165. }
  2166. RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  2167. // Evaluate and cache the common expression. We treat it as a temporary,
  2168. // even though it's not quite the same thing.
  2169. if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
  2170. Info, E->getCommon()))
  2171. return false;
  2172. return HandleConditionalOperator(E);
  2173. }
  2174. RetTy VisitConditionalOperator(const ConditionalOperator *E) {
  2175. bool IsBcpCall = false;
  2176. // If the condition (ignoring parens) is a __builtin_constant_p call,
  2177. // the result is a constant expression if it can be folded without
  2178. // side-effects. This is an important GNU extension. See GCC PR38377
  2179. // for discussion.
  2180. if (const CallExpr *CallCE =
  2181. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  2182. if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
  2183. IsBcpCall = true;
  2184. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  2185. // constant expression; we can't check whether it's potentially foldable.
  2186. if (Info.CheckingPotentialConstantExpression && IsBcpCall)
  2187. return false;
  2188. FoldConstant Fold(Info);
  2189. if (!HandleConditionalOperator(E))
  2190. return false;
  2191. if (IsBcpCall)
  2192. Fold.Fold(Info);
  2193. return true;
  2194. }
  2195. RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  2196. APValue &Value = Info.CurrentCall->Temporaries[E];
  2197. if (Value.isUninit()) {
  2198. const Expr *Source = E->getSourceExpr();
  2199. if (!Source)
  2200. return Error(E);
  2201. if (Source == E) { // sanity checking.
  2202. assert(0 && "OpaqueValueExpr recursively refers to itself");
  2203. return Error(E);
  2204. }
  2205. return StmtVisitorTy::Visit(Source);
  2206. }
  2207. return DerivedSuccess(Value, E);
  2208. }
  2209. RetTy VisitCallExpr(const CallExpr *E) {
  2210. const Expr *Callee = E->getCallee()->IgnoreParens();
  2211. QualType CalleeType = Callee->getType();
  2212. const FunctionDecl *FD = 0;
  2213. LValue *This = 0, ThisVal;
  2214. ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
  2215. bool HasQualifier = false;
  2216. // Extract function decl and 'this' pointer from the callee.
  2217. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  2218. const ValueDecl *Member = 0;
  2219. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  2220. // Explicit bound member calls, such as x.f() or p->g();
  2221. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  2222. return false;
  2223. Member = ME->getMemberDecl();
  2224. This = &ThisVal;
  2225. HasQualifier = ME->hasQualifier();
  2226. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  2227. // Indirect bound member calls ('.*' or '->*').
  2228. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  2229. if (!Member) return false;
  2230. This = &ThisVal;
  2231. } else
  2232. return Error(Callee);
  2233. FD = dyn_cast<FunctionDecl>(Member);
  2234. if (!FD)
  2235. return Error(Callee);
  2236. } else if (CalleeType->isFunctionPointerType()) {
  2237. LValue Call;
  2238. if (!EvaluatePointer(Callee, Call, Info))
  2239. return false;
  2240. if (!Call.getLValueOffset().isZero())
  2241. return Error(Callee);
  2242. FD = dyn_cast_or_null<FunctionDecl>(
  2243. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  2244. if (!FD)
  2245. return Error(Callee);
  2246. // Overloaded operator calls to member functions are represented as normal
  2247. // calls with '*this' as the first argument.
  2248. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  2249. if (MD && !MD->isStatic()) {
  2250. // FIXME: When selecting an implicit conversion for an overloaded
  2251. // operator delete, we sometimes try to evaluate calls to conversion
  2252. // operators without a 'this' parameter!
  2253. if (Args.empty())
  2254. return Error(E);
  2255. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  2256. return false;
  2257. This = &ThisVal;
  2258. Args = Args.slice(1);
  2259. }
  2260. // Don't call function pointers which have been cast to some other type.
  2261. if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
  2262. return Error(E);
  2263. } else
  2264. return Error(E);
  2265. if (This && !This->checkSubobject(Info, E, CSK_This))
  2266. return false;
  2267. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  2268. // calls to such functions in constant expressions.
  2269. if (This && !HasQualifier &&
  2270. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  2271. return Error(E, diag::note_constexpr_virtual_call);
  2272. const FunctionDecl *Definition = 0;
  2273. Stmt *Body = FD->getBody(Definition);
  2274. APValue Result;
  2275. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
  2276. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
  2277. Info, Result))
  2278. return false;
  2279. return DerivedSuccess(Result, E);
  2280. }
  2281. RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  2282. return StmtVisitorTy::Visit(E->getInitializer());
  2283. }
  2284. RetTy VisitInitListExpr(const InitListExpr *E) {
  2285. if (E->getNumInits() == 0)
  2286. return DerivedZeroInitialization(E);
  2287. if (E->getNumInits() == 1)
  2288. return StmtVisitorTy::Visit(E->getInit(0));
  2289. return Error(E);
  2290. }
  2291. RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  2292. return DerivedZeroInitialization(E);
  2293. }
  2294. RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  2295. return DerivedZeroInitialization(E);
  2296. }
  2297. RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  2298. return DerivedZeroInitialization(E);
  2299. }
  2300. /// A member expression where the object is a prvalue is itself a prvalue.
  2301. RetTy VisitMemberExpr(const MemberExpr *E) {
  2302. assert(!E->isArrow() && "missing call to bound member function?");
  2303. APValue Val;
  2304. if (!Evaluate(Val, Info, E->getBase()))
  2305. return false;
  2306. QualType BaseTy = E->getBase()->getType();
  2307. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2308. if (!FD) return Error(E);
  2309. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  2310. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  2311. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  2312. SubobjectDesignator Designator(BaseTy);
  2313. Designator.addDeclUnchecked(FD);
  2314. return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
  2315. DerivedSuccess(Val, E);
  2316. }
  2317. RetTy VisitCastExpr(const CastExpr *E) {
  2318. switch (E->getCastKind()) {
  2319. default:
  2320. break;
  2321. case CK_AtomicToNonAtomic:
  2322. case CK_NonAtomicToAtomic:
  2323. case CK_NoOp:
  2324. case CK_UserDefinedConversion:
  2325. return StmtVisitorTy::Visit(E->getSubExpr());
  2326. case CK_LValueToRValue: {
  2327. LValue LVal;
  2328. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  2329. return false;
  2330. APValue RVal;
  2331. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  2332. if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  2333. LVal, RVal))
  2334. return false;
  2335. return DerivedSuccess(RVal, E);
  2336. }
  2337. }
  2338. return Error(E);
  2339. }
  2340. /// Visit a value which is evaluated, but whose value is ignored.
  2341. void VisitIgnoredValue(const Expr *E) {
  2342. APValue Scratch;
  2343. if (!Evaluate(Scratch, Info, E))
  2344. Info.EvalStatus.HasSideEffects = true;
  2345. }
  2346. };
  2347. }
  2348. //===----------------------------------------------------------------------===//
  2349. // Common base class for lvalue and temporary evaluation.
  2350. //===----------------------------------------------------------------------===//
  2351. namespace {
  2352. template<class Derived>
  2353. class LValueExprEvaluatorBase
  2354. : public ExprEvaluatorBase<Derived, bool> {
  2355. protected:
  2356. LValue &Result;
  2357. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  2358. typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
  2359. bool Success(APValue::LValueBase B) {
  2360. Result.set(B);
  2361. return true;
  2362. }
  2363. public:
  2364. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
  2365. ExprEvaluatorBaseTy(Info), Result(Result) {}
  2366. bool Success(const APValue &V, const Expr *E) {
  2367. Result.setFrom(this->Info.Ctx, V);
  2368. return true;
  2369. }
  2370. bool VisitMemberExpr(const MemberExpr *E) {
  2371. // Handle non-static data members.
  2372. QualType BaseTy;
  2373. if (E->isArrow()) {
  2374. if (!EvaluatePointer(E->getBase(), Result, this->Info))
  2375. return false;
  2376. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  2377. } else if (E->getBase()->isRValue()) {
  2378. assert(E->getBase()->getType()->isRecordType());
  2379. if (!EvaluateTemporary(E->getBase(), Result, this->Info))
  2380. return false;
  2381. BaseTy = E->getBase()->getType();
  2382. } else {
  2383. if (!this->Visit(E->getBase()))
  2384. return false;
  2385. BaseTy = E->getBase()->getType();
  2386. }
  2387. const ValueDecl *MD = E->getMemberDecl();
  2388. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  2389. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  2390. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  2391. (void)BaseTy;
  2392. if (!HandleLValueMember(this->Info, E, Result, FD))
  2393. return false;
  2394. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  2395. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  2396. return false;
  2397. } else
  2398. return this->Error(E);
  2399. if (MD->getType()->isReferenceType()) {
  2400. APValue RefValue;
  2401. if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  2402. RefValue))
  2403. return false;
  2404. return Success(RefValue, E);
  2405. }
  2406. return true;
  2407. }
  2408. bool VisitBinaryOperator(const BinaryOperator *E) {
  2409. switch (E->getOpcode()) {
  2410. default:
  2411. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  2412. case BO_PtrMemD:
  2413. case BO_PtrMemI:
  2414. return HandleMemberPointerAccess(this->Info, E, Result);
  2415. }
  2416. }
  2417. bool VisitCastExpr(const CastExpr *E) {
  2418. switch (E->getCastKind()) {
  2419. default:
  2420. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2421. case CK_DerivedToBase:
  2422. case CK_UncheckedDerivedToBase: {
  2423. if (!this->Visit(E->getSubExpr()))
  2424. return false;
  2425. // Now figure out the necessary offset to add to the base LV to get from
  2426. // the derived class to the base class.
  2427. QualType Type = E->getSubExpr()->getType();
  2428. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2429. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2430. if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
  2431. *PathI))
  2432. return false;
  2433. Type = (*PathI)->getType();
  2434. }
  2435. return true;
  2436. }
  2437. }
  2438. }
  2439. };
  2440. }
  2441. //===----------------------------------------------------------------------===//
  2442. // LValue Evaluation
  2443. //
  2444. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  2445. // function designators (in C), decl references to void objects (in C), and
  2446. // temporaries (if building with -Wno-address-of-temporary).
  2447. //
  2448. // LValue evaluation produces values comprising a base expression of one of the
  2449. // following types:
  2450. // - Declarations
  2451. // * VarDecl
  2452. // * FunctionDecl
  2453. // - Literals
  2454. // * CompoundLiteralExpr in C
  2455. // * StringLiteral
  2456. // * CXXTypeidExpr
  2457. // * PredefinedExpr
  2458. // * ObjCStringLiteralExpr
  2459. // * ObjCEncodeExpr
  2460. // * AddrLabelExpr
  2461. // * BlockExpr
  2462. // * CallExpr for a MakeStringConstant builtin
  2463. // - Locals and temporaries
  2464. // * Any Expr, with a CallIndex indicating the function in which the temporary
  2465. // was evaluated.
  2466. // plus an offset in bytes.
  2467. //===----------------------------------------------------------------------===//
  2468. namespace {
  2469. class LValueExprEvaluator
  2470. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  2471. public:
  2472. LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
  2473. LValueExprEvaluatorBaseTy(Info, Result) {}
  2474. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  2475. bool VisitDeclRefExpr(const DeclRefExpr *E);
  2476. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  2477. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2478. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  2479. bool VisitMemberExpr(const MemberExpr *E);
  2480. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  2481. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  2482. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  2483. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  2484. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  2485. bool VisitUnaryDeref(const UnaryOperator *E);
  2486. bool VisitUnaryReal(const UnaryOperator *E);
  2487. bool VisitUnaryImag(const UnaryOperator *E);
  2488. bool VisitCastExpr(const CastExpr *E) {
  2489. switch (E->getCastKind()) {
  2490. default:
  2491. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  2492. case CK_LValueBitCast:
  2493. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2494. if (!Visit(E->getSubExpr()))
  2495. return false;
  2496. Result.Designator.setInvalid();
  2497. return true;
  2498. case CK_BaseToDerived:
  2499. if (!Visit(E->getSubExpr()))
  2500. return false;
  2501. return HandleBaseToDerivedCast(Info, E, Result);
  2502. }
  2503. }
  2504. };
  2505. } // end anonymous namespace
  2506. /// Evaluate an expression as an lvalue. This can be legitimately called on
  2507. /// expressions which are not glvalues, in a few cases:
  2508. /// * function designators in C,
  2509. /// * "extern void" objects,
  2510. /// * temporaries, if building with -Wno-address-of-temporary.
  2511. static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
  2512. assert((E->isGLValue() || E->getType()->isFunctionType() ||
  2513. E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
  2514. "can't evaluate expression as an lvalue");
  2515. return LValueExprEvaluator(Info, Result).Visit(E);
  2516. }
  2517. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  2518. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  2519. return Success(FD);
  2520. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  2521. return VisitVarDecl(E, VD);
  2522. return Error(E);
  2523. }
  2524. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  2525. if (!VD->getType()->isReferenceType()) {
  2526. if (isa<ParmVarDecl>(VD)) {
  2527. Result.set(VD, Info.CurrentCall->Index);
  2528. return true;
  2529. }
  2530. return Success(VD);
  2531. }
  2532. APValue V;
  2533. if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
  2534. return false;
  2535. return Success(V, E);
  2536. }
  2537. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  2538. const MaterializeTemporaryExpr *E) {
  2539. if (E->GetTemporaryExpr()->isRValue()) {
  2540. if (E->getType()->isRecordType())
  2541. return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
  2542. Result.set(E, Info.CurrentCall->Index);
  2543. return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
  2544. Result, E->GetTemporaryExpr());
  2545. }
  2546. // Materialization of an lvalue temporary occurs when we need to force a copy
  2547. // (for instance, if it's a bitfield).
  2548. // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
  2549. if (!Visit(E->GetTemporaryExpr()))
  2550. return false;
  2551. if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
  2552. Info.CurrentCall->Temporaries[E]))
  2553. return false;
  2554. Result.set(E, Info.CurrentCall->Index);
  2555. return true;
  2556. }
  2557. bool
  2558. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  2559. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  2560. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  2561. // only see this when folding in C, so there's no standard to follow here.
  2562. return Success(E);
  2563. }
  2564. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  2565. if (!E->isPotentiallyEvaluated())
  2566. return Success(E);
  2567. Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
  2568. << E->getExprOperand()->getType()
  2569. << E->getExprOperand()->getSourceRange();
  2570. return false;
  2571. }
  2572. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  2573. return Success(E);
  2574. }
  2575. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  2576. // Handle static data members.
  2577. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  2578. VisitIgnoredValue(E->getBase());
  2579. return VisitVarDecl(E, VD);
  2580. }
  2581. // Handle static member functions.
  2582. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  2583. if (MD->isStatic()) {
  2584. VisitIgnoredValue(E->getBase());
  2585. return Success(MD);
  2586. }
  2587. }
  2588. // Handle non-static data members.
  2589. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  2590. }
  2591. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  2592. // FIXME: Deal with vectors as array subscript bases.
  2593. if (E->getBase()->getType()->isVectorType())
  2594. return Error(E);
  2595. if (!EvaluatePointer(E->getBase(), Result, Info))
  2596. return false;
  2597. APSInt Index;
  2598. if (!EvaluateInteger(E->getIdx(), Index, Info))
  2599. return false;
  2600. int64_t IndexValue
  2601. = Index.isSigned() ? Index.getSExtValue()
  2602. : static_cast<int64_t>(Index.getZExtValue());
  2603. return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
  2604. }
  2605. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  2606. return EvaluatePointer(E->getSubExpr(), Result, Info);
  2607. }
  2608. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  2609. if (!Visit(E->getSubExpr()))
  2610. return false;
  2611. // __real is a no-op on scalar lvalues.
  2612. if (E->getSubExpr()->getType()->isAnyComplexType())
  2613. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  2614. return true;
  2615. }
  2616. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  2617. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  2618. "lvalue __imag__ on scalar?");
  2619. if (!Visit(E->getSubExpr()))
  2620. return false;
  2621. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  2622. return true;
  2623. }
  2624. //===----------------------------------------------------------------------===//
  2625. // Pointer Evaluation
  2626. //===----------------------------------------------------------------------===//
  2627. namespace {
  2628. class PointerExprEvaluator
  2629. : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
  2630. LValue &Result;
  2631. bool Success(const Expr *E) {
  2632. Result.set(E);
  2633. return true;
  2634. }
  2635. public:
  2636. PointerExprEvaluator(EvalInfo &info, LValue &Result)
  2637. : ExprEvaluatorBaseTy(info), Result(Result) {}
  2638. bool Success(const APValue &V, const Expr *E) {
  2639. Result.setFrom(Info.Ctx, V);
  2640. return true;
  2641. }
  2642. bool ZeroInitialization(const Expr *E) {
  2643. return Success((Expr*)0);
  2644. }
  2645. bool VisitBinaryOperator(const BinaryOperator *E);
  2646. bool VisitCastExpr(const CastExpr* E);
  2647. bool VisitUnaryAddrOf(const UnaryOperator *E);
  2648. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  2649. { return Success(E); }
  2650. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
  2651. { return Success(E); }
  2652. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  2653. { return Success(E); }
  2654. bool VisitCallExpr(const CallExpr *E);
  2655. bool VisitBlockExpr(const BlockExpr *E) {
  2656. if (!E->getBlockDecl()->hasCaptures())
  2657. return Success(E);
  2658. return Error(E);
  2659. }
  2660. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  2661. if (!Info.CurrentCall->This)
  2662. return Error(E);
  2663. Result = *Info.CurrentCall->This;
  2664. return true;
  2665. }
  2666. // FIXME: Missing: @protocol, @selector
  2667. };
  2668. } // end anonymous namespace
  2669. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
  2670. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  2671. return PointerExprEvaluator(Info, Result).Visit(E);
  2672. }
  2673. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  2674. if (E->getOpcode() != BO_Add &&
  2675. E->getOpcode() != BO_Sub)
  2676. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  2677. const Expr *PExp = E->getLHS();
  2678. const Expr *IExp = E->getRHS();
  2679. if (IExp->getType()->isPointerType())
  2680. std::swap(PExp, IExp);
  2681. bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
  2682. if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
  2683. return false;
  2684. llvm::APSInt Offset;
  2685. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  2686. return false;
  2687. int64_t AdditionalOffset
  2688. = Offset.isSigned() ? Offset.getSExtValue()
  2689. : static_cast<int64_t>(Offset.getZExtValue());
  2690. if (E->getOpcode() == BO_Sub)
  2691. AdditionalOffset = -AdditionalOffset;
  2692. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  2693. return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
  2694. AdditionalOffset);
  2695. }
  2696. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  2697. return EvaluateLValue(E->getSubExpr(), Result, Info);
  2698. }
  2699. bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  2700. const Expr* SubExpr = E->getSubExpr();
  2701. switch (E->getCastKind()) {
  2702. default:
  2703. break;
  2704. case CK_BitCast:
  2705. case CK_CPointerToObjCPointerCast:
  2706. case CK_BlockPointerToObjCPointerCast:
  2707. case CK_AnyPointerToBlockPointerCast:
  2708. if (!Visit(SubExpr))
  2709. return false;
  2710. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  2711. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  2712. // also static_casts, but we disallow them as a resolution to DR1312.
  2713. if (!E->getType()->isVoidPointerType()) {
  2714. Result.Designator.setInvalid();
  2715. if (SubExpr->getType()->isVoidPointerType())
  2716. CCEDiag(E, diag::note_constexpr_invalid_cast)
  2717. << 3 << SubExpr->getType();
  2718. else
  2719. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2720. }
  2721. return true;
  2722. case CK_DerivedToBase:
  2723. case CK_UncheckedDerivedToBase: {
  2724. if (!EvaluatePointer(E->getSubExpr(), Result, Info))
  2725. return false;
  2726. if (!Result.Base && Result.Offset.isZero())
  2727. return true;
  2728. // Now figure out the necessary offset to add to the base LV to get from
  2729. // the derived class to the base class.
  2730. QualType Type =
  2731. E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
  2732. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2733. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2734. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2735. *PathI))
  2736. return false;
  2737. Type = (*PathI)->getType();
  2738. }
  2739. return true;
  2740. }
  2741. case CK_BaseToDerived:
  2742. if (!Visit(E->getSubExpr()))
  2743. return false;
  2744. if (!Result.Base && Result.Offset.isZero())
  2745. return true;
  2746. return HandleBaseToDerivedCast(Info, E, Result);
  2747. case CK_NullToPointer:
  2748. VisitIgnoredValue(E->getSubExpr());
  2749. return ZeroInitialization(E);
  2750. case CK_IntegralToPointer: {
  2751. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2752. APValue Value;
  2753. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  2754. break;
  2755. if (Value.isInt()) {
  2756. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  2757. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  2758. Result.Base = (Expr*)0;
  2759. Result.Offset = CharUnits::fromQuantity(N);
  2760. Result.CallIndex = 0;
  2761. Result.Designator.setInvalid();
  2762. return true;
  2763. } else {
  2764. // Cast is of an lvalue, no need to change value.
  2765. Result.setFrom(Info.Ctx, Value);
  2766. return true;
  2767. }
  2768. }
  2769. case CK_ArrayToPointerDecay:
  2770. if (SubExpr->isGLValue()) {
  2771. if (!EvaluateLValue(SubExpr, Result, Info))
  2772. return false;
  2773. } else {
  2774. Result.set(SubExpr, Info.CurrentCall->Index);
  2775. if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
  2776. Info, Result, SubExpr))
  2777. return false;
  2778. }
  2779. // The result is a pointer to the first element of the array.
  2780. if (const ConstantArrayType *CAT
  2781. = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
  2782. Result.addArray(Info, E, CAT);
  2783. else
  2784. Result.Designator.setInvalid();
  2785. return true;
  2786. case CK_FunctionToPointerDecay:
  2787. return EvaluateLValue(SubExpr, Result, Info);
  2788. }
  2789. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2790. }
  2791. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  2792. if (IsStringLiteralCall(E))
  2793. return Success(E);
  2794. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  2795. }
  2796. //===----------------------------------------------------------------------===//
  2797. // Member Pointer Evaluation
  2798. //===----------------------------------------------------------------------===//
  2799. namespace {
  2800. class MemberPointerExprEvaluator
  2801. : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
  2802. MemberPtr &Result;
  2803. bool Success(const ValueDecl *D) {
  2804. Result = MemberPtr(D);
  2805. return true;
  2806. }
  2807. public:
  2808. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  2809. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  2810. bool Success(const APValue &V, const Expr *E) {
  2811. Result.setFrom(V);
  2812. return true;
  2813. }
  2814. bool ZeroInitialization(const Expr *E) {
  2815. return Success((const ValueDecl*)0);
  2816. }
  2817. bool VisitCastExpr(const CastExpr *E);
  2818. bool VisitUnaryAddrOf(const UnaryOperator *E);
  2819. };
  2820. } // end anonymous namespace
  2821. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  2822. EvalInfo &Info) {
  2823. assert(E->isRValue() && E->getType()->isMemberPointerType());
  2824. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  2825. }
  2826. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  2827. switch (E->getCastKind()) {
  2828. default:
  2829. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2830. case CK_NullToMemberPointer:
  2831. VisitIgnoredValue(E->getSubExpr());
  2832. return ZeroInitialization(E);
  2833. case CK_BaseToDerivedMemberPointer: {
  2834. if (!Visit(E->getSubExpr()))
  2835. return false;
  2836. if (E->path_empty())
  2837. return true;
  2838. // Base-to-derived member pointer casts store the path in derived-to-base
  2839. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  2840. // the wrong end of the derived->base arc, so stagger the path by one class.
  2841. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  2842. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  2843. PathI != PathE; ++PathI) {
  2844. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  2845. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  2846. if (!Result.castToDerived(Derived))
  2847. return Error(E);
  2848. }
  2849. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  2850. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  2851. return Error(E);
  2852. return true;
  2853. }
  2854. case CK_DerivedToBaseMemberPointer:
  2855. if (!Visit(E->getSubExpr()))
  2856. return false;
  2857. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2858. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2859. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  2860. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  2861. if (!Result.castToBase(Base))
  2862. return Error(E);
  2863. }
  2864. return true;
  2865. }
  2866. }
  2867. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  2868. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  2869. // member can be formed.
  2870. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  2871. }
  2872. //===----------------------------------------------------------------------===//
  2873. // Record Evaluation
  2874. //===----------------------------------------------------------------------===//
  2875. namespace {
  2876. class RecordExprEvaluator
  2877. : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
  2878. const LValue &This;
  2879. APValue &Result;
  2880. public:
  2881. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  2882. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  2883. bool Success(const APValue &V, const Expr *E) {
  2884. Result = V;
  2885. return true;
  2886. }
  2887. bool ZeroInitialization(const Expr *E);
  2888. bool VisitCastExpr(const CastExpr *E);
  2889. bool VisitInitListExpr(const InitListExpr *E);
  2890. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  2891. };
  2892. }
  2893. /// Perform zero-initialization on an object of non-union class type.
  2894. /// C++11 [dcl.init]p5:
  2895. /// To zero-initialize an object or reference of type T means:
  2896. /// [...]
  2897. /// -- if T is a (possibly cv-qualified) non-union class type,
  2898. /// each non-static data member and each base-class subobject is
  2899. /// zero-initialized
  2900. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  2901. const RecordDecl *RD,
  2902. const LValue &This, APValue &Result) {
  2903. assert(!RD->isUnion() && "Expected non-union class type");
  2904. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  2905. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  2906. std::distance(RD->field_begin(), RD->field_end()));
  2907. if (RD->isInvalidDecl()) return false;
  2908. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2909. if (CD) {
  2910. unsigned Index = 0;
  2911. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  2912. End = CD->bases_end(); I != End; ++I, ++Index) {
  2913. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  2914. LValue Subobject = This;
  2915. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  2916. return false;
  2917. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  2918. Result.getStructBase(Index)))
  2919. return false;
  2920. }
  2921. }
  2922. for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
  2923. I != End; ++I) {
  2924. // -- if T is a reference type, no initialization is performed.
  2925. if (I->getType()->isReferenceType())
  2926. continue;
  2927. LValue Subobject = This;
  2928. if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
  2929. return false;
  2930. ImplicitValueInitExpr VIE(I->getType());
  2931. if (!EvaluateInPlace(
  2932. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  2933. return false;
  2934. }
  2935. return true;
  2936. }
  2937. bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
  2938. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  2939. if (RD->isInvalidDecl()) return false;
  2940. if (RD->isUnion()) {
  2941. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  2942. // object's first non-static named data member is zero-initialized
  2943. RecordDecl::field_iterator I = RD->field_begin();
  2944. if (I == RD->field_end()) {
  2945. Result = APValue((const FieldDecl*)0);
  2946. return true;
  2947. }
  2948. LValue Subobject = This;
  2949. if (!HandleLValueMember(Info, E, Subobject, *I))
  2950. return false;
  2951. Result = APValue(*I);
  2952. ImplicitValueInitExpr VIE(I->getType());
  2953. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  2954. }
  2955. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  2956. Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
  2957. return false;
  2958. }
  2959. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  2960. }
  2961. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  2962. switch (E->getCastKind()) {
  2963. default:
  2964. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2965. case CK_ConstructorConversion:
  2966. return Visit(E->getSubExpr());
  2967. case CK_DerivedToBase:
  2968. case CK_UncheckedDerivedToBase: {
  2969. APValue DerivedObject;
  2970. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  2971. return false;
  2972. if (!DerivedObject.isStruct())
  2973. return Error(E->getSubExpr());
  2974. // Derived-to-base rvalue conversion: just slice off the derived part.
  2975. APValue *Value = &DerivedObject;
  2976. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  2977. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2978. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2979. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  2980. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  2981. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  2982. RD = Base;
  2983. }
  2984. Result = *Value;
  2985. return true;
  2986. }
  2987. }
  2988. }
  2989. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  2990. // Cannot constant-evaluate std::initializer_list inits.
  2991. if (E->initializesStdInitializerList())
  2992. return false;
  2993. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  2994. if (RD->isInvalidDecl()) return false;
  2995. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2996. if (RD->isUnion()) {
  2997. const FieldDecl *Field = E->getInitializedFieldInUnion();
  2998. Result = APValue(Field);
  2999. if (!Field)
  3000. return true;
  3001. // If the initializer list for a union does not contain any elements, the
  3002. // first element of the union is value-initialized.
  3003. ImplicitValueInitExpr VIE(Field->getType());
  3004. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  3005. LValue Subobject = This;
  3006. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  3007. return false;
  3008. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  3009. }
  3010. assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
  3011. "initializer list for class with base classes");
  3012. Result = APValue(APValue::UninitStruct(), 0,
  3013. std::distance(RD->field_begin(), RD->field_end()));
  3014. unsigned ElementNo = 0;
  3015. bool Success = true;
  3016. for (RecordDecl::field_iterator Field = RD->field_begin(),
  3017. FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
  3018. // Anonymous bit-fields are not considered members of the class for
  3019. // purposes of aggregate initialization.
  3020. if (Field->isUnnamedBitfield())
  3021. continue;
  3022. LValue Subobject = This;
  3023. bool HaveInit = ElementNo < E->getNumInits();
  3024. // FIXME: Diagnostics here should point to the end of the initializer
  3025. // list, not the start.
  3026. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  3027. Subobject, *Field, &Layout))
  3028. return false;
  3029. // Perform an implicit value-initialization for members beyond the end of
  3030. // the initializer list.
  3031. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  3032. if (!EvaluateInPlace(
  3033. Result.getStructField(Field->getFieldIndex()),
  3034. Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
  3035. if (!Info.keepEvaluatingAfterFailure())
  3036. return false;
  3037. Success = false;
  3038. }
  3039. }
  3040. return Success;
  3041. }
  3042. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  3043. const CXXConstructorDecl *FD = E->getConstructor();
  3044. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  3045. bool ZeroInit = E->requiresZeroInitialization();
  3046. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  3047. // If we've already performed zero-initialization, we're already done.
  3048. if (!Result.isUninit())
  3049. return true;
  3050. if (ZeroInit)
  3051. return ZeroInitialization(E);
  3052. const CXXRecordDecl *RD = FD->getParent();
  3053. if (RD->isUnion())
  3054. Result = APValue((FieldDecl*)0);
  3055. else
  3056. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  3057. std::distance(RD->field_begin(), RD->field_end()));
  3058. return true;
  3059. }
  3060. const FunctionDecl *Definition = 0;
  3061. FD->getBody(Definition);
  3062. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  3063. return false;
  3064. // Avoid materializing a temporary for an elidable copy/move constructor.
  3065. if (E->isElidable() && !ZeroInit)
  3066. if (const MaterializeTemporaryExpr *ME
  3067. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  3068. return Visit(ME->GetTemporaryExpr());
  3069. if (ZeroInit && !ZeroInitialization(E))
  3070. return false;
  3071. ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
  3072. return HandleConstructorCall(E->getExprLoc(), This, Args,
  3073. cast<CXXConstructorDecl>(Definition), Info,
  3074. Result);
  3075. }
  3076. static bool EvaluateRecord(const Expr *E, const LValue &This,
  3077. APValue &Result, EvalInfo &Info) {
  3078. assert(E->isRValue() && E->getType()->isRecordType() &&
  3079. "can't evaluate expression as a record rvalue");
  3080. return RecordExprEvaluator(Info, This, Result).Visit(E);
  3081. }
  3082. //===----------------------------------------------------------------------===//
  3083. // Temporary Evaluation
  3084. //
  3085. // Temporaries are represented in the AST as rvalues, but generally behave like
  3086. // lvalues. The full-object of which the temporary is a subobject is implicitly
  3087. // materialized so that a reference can bind to it.
  3088. //===----------------------------------------------------------------------===//
  3089. namespace {
  3090. class TemporaryExprEvaluator
  3091. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  3092. public:
  3093. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  3094. LValueExprEvaluatorBaseTy(Info, Result) {}
  3095. /// Visit an expression which constructs the value of this temporary.
  3096. bool VisitConstructExpr(const Expr *E) {
  3097. Result.set(E, Info.CurrentCall->Index);
  3098. return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
  3099. }
  3100. bool VisitCastExpr(const CastExpr *E) {
  3101. switch (E->getCastKind()) {
  3102. default:
  3103. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  3104. case CK_ConstructorConversion:
  3105. return VisitConstructExpr(E->getSubExpr());
  3106. }
  3107. }
  3108. bool VisitInitListExpr(const InitListExpr *E) {
  3109. return VisitConstructExpr(E);
  3110. }
  3111. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  3112. return VisitConstructExpr(E);
  3113. }
  3114. bool VisitCallExpr(const CallExpr *E) {
  3115. return VisitConstructExpr(E);
  3116. }
  3117. };
  3118. } // end anonymous namespace
  3119. /// Evaluate an expression of record type as a temporary.
  3120. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  3121. assert(E->isRValue() && E->getType()->isRecordType());
  3122. return TemporaryExprEvaluator(Info, Result).Visit(E);
  3123. }
  3124. //===----------------------------------------------------------------------===//
  3125. // Vector Evaluation
  3126. //===----------------------------------------------------------------------===//
  3127. namespace {
  3128. class VectorExprEvaluator
  3129. : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
  3130. APValue &Result;
  3131. public:
  3132. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  3133. : ExprEvaluatorBaseTy(info), Result(Result) {}
  3134. bool Success(const ArrayRef<APValue> &V, const Expr *E) {
  3135. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  3136. // FIXME: remove this APValue copy.
  3137. Result = APValue(V.data(), V.size());
  3138. return true;
  3139. }
  3140. bool Success(const APValue &V, const Expr *E) {
  3141. assert(V.isVector());
  3142. Result = V;
  3143. return true;
  3144. }
  3145. bool ZeroInitialization(const Expr *E);
  3146. bool VisitUnaryReal(const UnaryOperator *E)
  3147. { return Visit(E->getSubExpr()); }
  3148. bool VisitCastExpr(const CastExpr* E);
  3149. bool VisitInitListExpr(const InitListExpr *E);
  3150. bool VisitUnaryImag(const UnaryOperator *E);
  3151. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  3152. // binary comparisons, binary and/or/xor,
  3153. // shufflevector, ExtVectorElementExpr
  3154. };
  3155. } // end anonymous namespace
  3156. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  3157. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  3158. return VectorExprEvaluator(Info, Result).Visit(E);
  3159. }
  3160. bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
  3161. const VectorType *VTy = E->getType()->castAs<VectorType>();
  3162. unsigned NElts = VTy->getNumElements();
  3163. const Expr *SE = E->getSubExpr();
  3164. QualType SETy = SE->getType();
  3165. switch (E->getCastKind()) {
  3166. case CK_VectorSplat: {
  3167. APValue Val = APValue();
  3168. if (SETy->isIntegerType()) {
  3169. APSInt IntResult;
  3170. if (!EvaluateInteger(SE, IntResult, Info))
  3171. return false;
  3172. Val = APValue(IntResult);
  3173. } else if (SETy->isRealFloatingType()) {
  3174. APFloat F(0.0);
  3175. if (!EvaluateFloat(SE, F, Info))
  3176. return false;
  3177. Val = APValue(F);
  3178. } else {
  3179. return Error(E);
  3180. }
  3181. // Splat and create vector APValue.
  3182. SmallVector<APValue, 4> Elts(NElts, Val);
  3183. return Success(Elts, E);
  3184. }
  3185. case CK_BitCast: {
  3186. // Evaluate the operand into an APInt we can extract from.
  3187. llvm::APInt SValInt;
  3188. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  3189. return false;
  3190. // Extract the elements
  3191. QualType EltTy = VTy->getElementType();
  3192. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  3193. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  3194. SmallVector<APValue, 4> Elts;
  3195. if (EltTy->isRealFloatingType()) {
  3196. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  3197. bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
  3198. unsigned FloatEltSize = EltSize;
  3199. if (&Sem == &APFloat::x87DoubleExtended)
  3200. FloatEltSize = 80;
  3201. for (unsigned i = 0; i < NElts; i++) {
  3202. llvm::APInt Elt;
  3203. if (BigEndian)
  3204. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  3205. else
  3206. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  3207. Elts.push_back(APValue(APFloat(Elt, isIEESem)));
  3208. }
  3209. } else if (EltTy->isIntegerType()) {
  3210. for (unsigned i = 0; i < NElts; i++) {
  3211. llvm::APInt Elt;
  3212. if (BigEndian)
  3213. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  3214. else
  3215. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  3216. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  3217. }
  3218. } else {
  3219. return Error(E);
  3220. }
  3221. return Success(Elts, E);
  3222. }
  3223. default:
  3224. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  3225. }
  3226. }
  3227. bool
  3228. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  3229. const VectorType *VT = E->getType()->castAs<VectorType>();
  3230. unsigned NumInits = E->getNumInits();
  3231. unsigned NumElements = VT->getNumElements();
  3232. QualType EltTy = VT->getElementType();
  3233. SmallVector<APValue, 4> Elements;
  3234. // The number of initializers can be less than the number of
  3235. // vector elements. For OpenCL, this can be due to nested vector
  3236. // initialization. For GCC compatibility, missing trailing elements
  3237. // should be initialized with zeroes.
  3238. unsigned CountInits = 0, CountElts = 0;
  3239. while (CountElts < NumElements) {
  3240. // Handle nested vector initialization.
  3241. if (CountInits < NumInits
  3242. && E->getInit(CountInits)->getType()->isExtVectorType()) {
  3243. APValue v;
  3244. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  3245. return Error(E);
  3246. unsigned vlen = v.getVectorLength();
  3247. for (unsigned j = 0; j < vlen; j++)
  3248. Elements.push_back(v.getVectorElt(j));
  3249. CountElts += vlen;
  3250. } else if (EltTy->isIntegerType()) {
  3251. llvm::APSInt sInt(32);
  3252. if (CountInits < NumInits) {
  3253. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  3254. return false;
  3255. } else // trailing integer zero.
  3256. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  3257. Elements.push_back(APValue(sInt));
  3258. CountElts++;
  3259. } else {
  3260. llvm::APFloat f(0.0);
  3261. if (CountInits < NumInits) {
  3262. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  3263. return false;
  3264. } else // trailing float zero.
  3265. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  3266. Elements.push_back(APValue(f));
  3267. CountElts++;
  3268. }
  3269. CountInits++;
  3270. }
  3271. return Success(Elements, E);
  3272. }
  3273. bool
  3274. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  3275. const VectorType *VT = E->getType()->getAs<VectorType>();
  3276. QualType EltTy = VT->getElementType();
  3277. APValue ZeroElement;
  3278. if (EltTy->isIntegerType())
  3279. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  3280. else
  3281. ZeroElement =
  3282. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  3283. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  3284. return Success(Elements, E);
  3285. }
  3286. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  3287. VisitIgnoredValue(E->getSubExpr());
  3288. return ZeroInitialization(E);
  3289. }
  3290. //===----------------------------------------------------------------------===//
  3291. // Array Evaluation
  3292. //===----------------------------------------------------------------------===//
  3293. namespace {
  3294. class ArrayExprEvaluator
  3295. : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
  3296. const LValue &This;
  3297. APValue &Result;
  3298. public:
  3299. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  3300. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  3301. bool Success(const APValue &V, const Expr *E) {
  3302. assert((V.isArray() || V.isLValue()) &&
  3303. "expected array or string literal");
  3304. Result = V;
  3305. return true;
  3306. }
  3307. bool ZeroInitialization(const Expr *E) {
  3308. const ConstantArrayType *CAT =
  3309. Info.Ctx.getAsConstantArrayType(E->getType());
  3310. if (!CAT)
  3311. return Error(E);
  3312. Result = APValue(APValue::UninitArray(), 0,
  3313. CAT->getSize().getZExtValue());
  3314. if (!Result.hasArrayFiller()) return true;
  3315. // Zero-initialize all elements.
  3316. LValue Subobject = This;
  3317. Subobject.addArray(Info, E, CAT);
  3318. ImplicitValueInitExpr VIE(CAT->getElementType());
  3319. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  3320. }
  3321. bool VisitInitListExpr(const InitListExpr *E);
  3322. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  3323. };
  3324. } // end anonymous namespace
  3325. static bool EvaluateArray(const Expr *E, const LValue &This,
  3326. APValue &Result, EvalInfo &Info) {
  3327. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  3328. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  3329. }
  3330. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  3331. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  3332. if (!CAT)
  3333. return Error(E);
  3334. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  3335. // an appropriately-typed string literal enclosed in braces.
  3336. if (E->isStringLiteralInit()) {
  3337. LValue LV;
  3338. if (!EvaluateLValue(E->getInit(0), LV, Info))
  3339. return false;
  3340. APValue Val;
  3341. LV.moveInto(Val);
  3342. return Success(Val, E);
  3343. }
  3344. bool Success = true;
  3345. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  3346. "zero-initialized array shouldn't have any initialized elts");
  3347. APValue Filler;
  3348. if (Result.isArray() && Result.hasArrayFiller())
  3349. Filler = Result.getArrayFiller();
  3350. Result = APValue(APValue::UninitArray(), E->getNumInits(),
  3351. CAT->getSize().getZExtValue());
  3352. // If the array was previously zero-initialized, preserve the
  3353. // zero-initialized values.
  3354. if (!Filler.isUninit()) {
  3355. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  3356. Result.getArrayInitializedElt(I) = Filler;
  3357. if (Result.hasArrayFiller())
  3358. Result.getArrayFiller() = Filler;
  3359. }
  3360. LValue Subobject = This;
  3361. Subobject.addArray(Info, E, CAT);
  3362. unsigned Index = 0;
  3363. for (InitListExpr::const_iterator I = E->begin(), End = E->end();
  3364. I != End; ++I, ++Index) {
  3365. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  3366. Info, Subobject, cast<Expr>(*I)) ||
  3367. !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
  3368. CAT->getElementType(), 1)) {
  3369. if (!Info.keepEvaluatingAfterFailure())
  3370. return false;
  3371. Success = false;
  3372. }
  3373. }
  3374. if (!Result.hasArrayFiller()) return Success;
  3375. assert(E->hasArrayFiller() && "no array filler for incomplete init list");
  3376. // FIXME: The Subobject here isn't necessarily right. This rarely matters,
  3377. // but sometimes does:
  3378. // struct S { constexpr S() : p(&p) {} void *p; };
  3379. // S s[10] = {};
  3380. return EvaluateInPlace(Result.getArrayFiller(), Info,
  3381. Subobject, E->getArrayFiller()) && Success;
  3382. }
  3383. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  3384. // FIXME: The Subobject here isn't necessarily right. This rarely matters,
  3385. // but sometimes does:
  3386. // struct S { constexpr S() : p(&p) {} void *p; };
  3387. // S s[10];
  3388. LValue Subobject = This;
  3389. APValue *Value = &Result;
  3390. bool HadZeroInit = true;
  3391. QualType ElemTy = E->getType();
  3392. while (const ConstantArrayType *CAT =
  3393. Info.Ctx.getAsConstantArrayType(ElemTy)) {
  3394. Subobject.addArray(Info, E, CAT);
  3395. HadZeroInit &= !Value->isUninit();
  3396. if (!HadZeroInit)
  3397. *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
  3398. if (!Value->hasArrayFiller())
  3399. return true;
  3400. Value = &Value->getArrayFiller();
  3401. ElemTy = CAT->getElementType();
  3402. }
  3403. if (!ElemTy->isRecordType())
  3404. return Error(E);
  3405. const CXXConstructorDecl *FD = E->getConstructor();
  3406. bool ZeroInit = E->requiresZeroInitialization();
  3407. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  3408. if (HadZeroInit)
  3409. return true;
  3410. if (ZeroInit) {
  3411. ImplicitValueInitExpr VIE(ElemTy);
  3412. return EvaluateInPlace(*Value, Info, Subobject, &VIE);
  3413. }
  3414. const CXXRecordDecl *RD = FD->getParent();
  3415. if (RD->isUnion())
  3416. *Value = APValue((FieldDecl*)0);
  3417. else
  3418. *Value =
  3419. APValue(APValue::UninitStruct(), RD->getNumBases(),
  3420. std::distance(RD->field_begin(), RD->field_end()));
  3421. return true;
  3422. }
  3423. const FunctionDecl *Definition = 0;
  3424. FD->getBody(Definition);
  3425. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  3426. return false;
  3427. if (ZeroInit && !HadZeroInit) {
  3428. ImplicitValueInitExpr VIE(ElemTy);
  3429. if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
  3430. return false;
  3431. }
  3432. ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
  3433. return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
  3434. cast<CXXConstructorDecl>(Definition),
  3435. Info, *Value);
  3436. }
  3437. //===----------------------------------------------------------------------===//
  3438. // Integer Evaluation
  3439. //
  3440. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  3441. // types and back in constant folding. Integer values are thus represented
  3442. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  3443. //===----------------------------------------------------------------------===//
  3444. namespace {
  3445. class IntExprEvaluator
  3446. : public ExprEvaluatorBase<IntExprEvaluator, bool> {
  3447. APValue &Result;
  3448. public:
  3449. IntExprEvaluator(EvalInfo &info, APValue &result)
  3450. : ExprEvaluatorBaseTy(info), Result(result) {}
  3451. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  3452. assert(E->getType()->isIntegralOrEnumerationType() &&
  3453. "Invalid evaluation result.");
  3454. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  3455. "Invalid evaluation result.");
  3456. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  3457. "Invalid evaluation result.");
  3458. Result = APValue(SI);
  3459. return true;
  3460. }
  3461. bool Success(const llvm::APSInt &SI, const Expr *E) {
  3462. return Success(SI, E, Result);
  3463. }
  3464. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  3465. assert(E->getType()->isIntegralOrEnumerationType() &&
  3466. "Invalid evaluation result.");
  3467. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  3468. "Invalid evaluation result.");
  3469. Result = APValue(APSInt(I));
  3470. Result.getInt().setIsUnsigned(
  3471. E->getType()->isUnsignedIntegerOrEnumerationType());
  3472. return true;
  3473. }
  3474. bool Success(const llvm::APInt &I, const Expr *E) {
  3475. return Success(I, E, Result);
  3476. }
  3477. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  3478. assert(E->getType()->isIntegralOrEnumerationType() &&
  3479. "Invalid evaluation result.");
  3480. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  3481. return true;
  3482. }
  3483. bool Success(uint64_t Value, const Expr *E) {
  3484. return Success(Value, E, Result);
  3485. }
  3486. bool Success(CharUnits Size, const Expr *E) {
  3487. return Success(Size.getQuantity(), E);
  3488. }
  3489. bool Success(const APValue &V, const Expr *E) {
  3490. if (V.isLValue() || V.isAddrLabelDiff()) {
  3491. Result = V;
  3492. return true;
  3493. }
  3494. return Success(V.getInt(), E);
  3495. }
  3496. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  3497. //===--------------------------------------------------------------------===//
  3498. // Visitor Methods
  3499. //===--------------------------------------------------------------------===//
  3500. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  3501. return Success(E->getValue(), E);
  3502. }
  3503. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  3504. return Success(E->getValue(), E);
  3505. }
  3506. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  3507. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  3508. if (CheckReferencedDecl(E, E->getDecl()))
  3509. return true;
  3510. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  3511. }
  3512. bool VisitMemberExpr(const MemberExpr *E) {
  3513. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  3514. VisitIgnoredValue(E->getBase());
  3515. return true;
  3516. }
  3517. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  3518. }
  3519. bool VisitCallExpr(const CallExpr *E);
  3520. bool VisitBinaryOperator(const BinaryOperator *E);
  3521. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  3522. bool VisitUnaryOperator(const UnaryOperator *E);
  3523. bool VisitCastExpr(const CastExpr* E);
  3524. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  3525. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  3526. return Success(E->getValue(), E);
  3527. }
  3528. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  3529. return Success(E->getValue(), E);
  3530. }
  3531. // Note, GNU defines __null as an integer, not a pointer.
  3532. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  3533. return ZeroInitialization(E);
  3534. }
  3535. bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
  3536. return Success(E->getValue(), E);
  3537. }
  3538. bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
  3539. return Success(E->getValue(), E);
  3540. }
  3541. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  3542. return Success(E->getValue(), E);
  3543. }
  3544. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  3545. return Success(E->getValue(), E);
  3546. }
  3547. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  3548. return Success(E->getValue(), E);
  3549. }
  3550. bool VisitUnaryReal(const UnaryOperator *E);
  3551. bool VisitUnaryImag(const UnaryOperator *E);
  3552. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  3553. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  3554. private:
  3555. CharUnits GetAlignOfExpr(const Expr *E);
  3556. CharUnits GetAlignOfType(QualType T);
  3557. static QualType GetObjectType(APValue::LValueBase B);
  3558. bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
  3559. // FIXME: Missing: array subscript of vector, member of vector
  3560. };
  3561. } // end anonymous namespace
  3562. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  3563. /// produce either the integer value or a pointer.
  3564. ///
  3565. /// GCC has a heinous extension which folds casts between pointer types and
  3566. /// pointer-sized integral types. We support this by allowing the evaluation of
  3567. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  3568. /// Some simple arithmetic on such values is supported (they are treated much
  3569. /// like char*).
  3570. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  3571. EvalInfo &Info) {
  3572. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  3573. return IntExprEvaluator(Info, Result).Visit(E);
  3574. }
  3575. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  3576. APValue Val;
  3577. if (!EvaluateIntegerOrLValue(E, Val, Info))
  3578. return false;
  3579. if (!Val.isInt()) {
  3580. // FIXME: It would be better to produce the diagnostic for casting
  3581. // a pointer to an integer.
  3582. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  3583. return false;
  3584. }
  3585. Result = Val.getInt();
  3586. return true;
  3587. }
  3588. /// Check whether the given declaration can be directly converted to an integral
  3589. /// rvalue. If not, no diagnostic is produced; there are other things we can
  3590. /// try.
  3591. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  3592. // Enums are integer constant exprs.
  3593. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  3594. // Check for signedness/width mismatches between E type and ECD value.
  3595. bool SameSign = (ECD->getInitVal().isSigned()
  3596. == E->getType()->isSignedIntegerOrEnumerationType());
  3597. bool SameWidth = (ECD->getInitVal().getBitWidth()
  3598. == Info.Ctx.getIntWidth(E->getType()));
  3599. if (SameSign && SameWidth)
  3600. return Success(ECD->getInitVal(), E);
  3601. else {
  3602. // Get rid of mismatch (otherwise Success assertions will fail)
  3603. // by computing a new value matching the type of E.
  3604. llvm::APSInt Val = ECD->getInitVal();
  3605. if (!SameSign)
  3606. Val.setIsSigned(!ECD->getInitVal().isSigned());
  3607. if (!SameWidth)
  3608. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  3609. return Success(Val, E);
  3610. }
  3611. }
  3612. return false;
  3613. }
  3614. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  3615. /// as GCC.
  3616. static int EvaluateBuiltinClassifyType(const CallExpr *E) {
  3617. // The following enum mimics the values returned by GCC.
  3618. // FIXME: Does GCC differ between lvalue and rvalue references here?
  3619. enum gcc_type_class {
  3620. no_type_class = -1,
  3621. void_type_class, integer_type_class, char_type_class,
  3622. enumeral_type_class, boolean_type_class,
  3623. pointer_type_class, reference_type_class, offset_type_class,
  3624. real_type_class, complex_type_class,
  3625. function_type_class, method_type_class,
  3626. record_type_class, union_type_class,
  3627. array_type_class, string_type_class,
  3628. lang_type_class
  3629. };
  3630. // If no argument was supplied, default to "no_type_class". This isn't
  3631. // ideal, however it is what gcc does.
  3632. if (E->getNumArgs() == 0)
  3633. return no_type_class;
  3634. QualType ArgTy = E->getArg(0)->getType();
  3635. if (ArgTy->isVoidType())
  3636. return void_type_class;
  3637. else if (ArgTy->isEnumeralType())
  3638. return enumeral_type_class;
  3639. else if (ArgTy->isBooleanType())
  3640. return boolean_type_class;
  3641. else if (ArgTy->isCharType())
  3642. return string_type_class; // gcc doesn't appear to use char_type_class
  3643. else if (ArgTy->isIntegerType())
  3644. return integer_type_class;
  3645. else if (ArgTy->isPointerType())
  3646. return pointer_type_class;
  3647. else if (ArgTy->isReferenceType())
  3648. return reference_type_class;
  3649. else if (ArgTy->isRealType())
  3650. return real_type_class;
  3651. else if (ArgTy->isComplexType())
  3652. return complex_type_class;
  3653. else if (ArgTy->isFunctionType())
  3654. return function_type_class;
  3655. else if (ArgTy->isStructureOrClassType())
  3656. return record_type_class;
  3657. else if (ArgTy->isUnionType())
  3658. return union_type_class;
  3659. else if (ArgTy->isArrayType())
  3660. return array_type_class;
  3661. else if (ArgTy->isUnionType())
  3662. return union_type_class;
  3663. else // FIXME: offset_type_class, method_type_class, & lang_type_class?
  3664. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  3665. }
  3666. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  3667. /// __builtin_constant_p when applied to the given lvalue.
  3668. ///
  3669. /// An lvalue is only "constant" if it is a pointer or reference to the first
  3670. /// character of a string literal.
  3671. template<typename LValue>
  3672. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  3673. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  3674. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  3675. }
  3676. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  3677. /// GCC as we can manage.
  3678. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  3679. QualType ArgType = Arg->getType();
  3680. // __builtin_constant_p always has one operand. The rules which gcc follows
  3681. // are not precisely documented, but are as follows:
  3682. //
  3683. // - If the operand is of integral, floating, complex or enumeration type,
  3684. // and can be folded to a known value of that type, it returns 1.
  3685. // - If the operand and can be folded to a pointer to the first character
  3686. // of a string literal (or such a pointer cast to an integral type), it
  3687. // returns 1.
  3688. //
  3689. // Otherwise, it returns 0.
  3690. //
  3691. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  3692. // its support for this does not currently work.
  3693. if (ArgType->isIntegralOrEnumerationType()) {
  3694. Expr::EvalResult Result;
  3695. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  3696. return false;
  3697. APValue &V = Result.Val;
  3698. if (V.getKind() == APValue::Int)
  3699. return true;
  3700. return EvaluateBuiltinConstantPForLValue(V);
  3701. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  3702. return Arg->isEvaluatable(Ctx);
  3703. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  3704. LValue LV;
  3705. Expr::EvalStatus Status;
  3706. EvalInfo Info(Ctx, Status);
  3707. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  3708. : EvaluatePointer(Arg, LV, Info)) &&
  3709. !Status.HasSideEffects)
  3710. return EvaluateBuiltinConstantPForLValue(LV);
  3711. }
  3712. // Anything else isn't considered to be sufficiently constant.
  3713. return false;
  3714. }
  3715. /// Retrieves the "underlying object type" of the given expression,
  3716. /// as used by __builtin_object_size.
  3717. QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
  3718. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  3719. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3720. return VD->getType();
  3721. } else if (const Expr *E = B.get<const Expr*>()) {
  3722. if (isa<CompoundLiteralExpr>(E))
  3723. return E->getType();
  3724. }
  3725. return QualType();
  3726. }
  3727. bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
  3728. LValue Base;
  3729. {
  3730. // The operand of __builtin_object_size is never evaluated for side-effects.
  3731. // If there are any, but we can determine the pointed-to object anyway, then
  3732. // ignore the side-effects.
  3733. SpeculativeEvaluationRAII SpeculativeEval(Info);
  3734. if (!EvaluatePointer(E->getArg(0), Base, Info))
  3735. return false;
  3736. }
  3737. // If we can prove the base is null, lower to zero now.
  3738. if (!Base.getLValueBase()) return Success(0, E);
  3739. QualType T = GetObjectType(Base.getLValueBase());
  3740. if (T.isNull() ||
  3741. T->isIncompleteType() ||
  3742. T->isFunctionType() ||
  3743. T->isVariablyModifiedType() ||
  3744. T->isDependentType())
  3745. return Error(E);
  3746. CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
  3747. CharUnits Offset = Base.getLValueOffset();
  3748. if (!Offset.isNegative() && Offset <= Size)
  3749. Size -= Offset;
  3750. else
  3751. Size = CharUnits::Zero();
  3752. return Success(Size, E);
  3753. }
  3754. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  3755. switch (unsigned BuiltinOp = E->isBuiltinCall()) {
  3756. default:
  3757. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  3758. case Builtin::BI__builtin_object_size: {
  3759. if (TryEvaluateBuiltinObjectSize(E))
  3760. return true;
  3761. // If evaluating the argument has side-effects, we can't determine the size
  3762. // of the object, and so we lower it to unknown now. CodeGen relies on us to
  3763. // handle all cases where the expression has side-effects.
  3764. if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
  3765. if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
  3766. return Success(-1ULL, E);
  3767. return Success(0, E);
  3768. }
  3769. // Expression had no side effects, but we couldn't statically determine the
  3770. // size of the referenced object.
  3771. return Error(E);
  3772. }
  3773. case Builtin::BI__builtin_bswap16:
  3774. case Builtin::BI__builtin_bswap32:
  3775. case Builtin::BI__builtin_bswap64: {
  3776. APSInt Val;
  3777. if (!EvaluateInteger(E->getArg(0), Val, Info))
  3778. return false;
  3779. return Success(Val.byteSwap(), E);
  3780. }
  3781. case Builtin::BI__builtin_classify_type:
  3782. return Success(EvaluateBuiltinClassifyType(E), E);
  3783. case Builtin::BI__builtin_constant_p:
  3784. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  3785. case Builtin::BI__builtin_eh_return_data_regno: {
  3786. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  3787. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  3788. return Success(Operand, E);
  3789. }
  3790. case Builtin::BI__builtin_expect:
  3791. return Visit(E->getArg(0));
  3792. case Builtin::BIstrlen:
  3793. // A call to strlen is not a constant expression.
  3794. if (Info.getLangOpts().CPlusPlus11)
  3795. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  3796. << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
  3797. else
  3798. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  3799. // Fall through.
  3800. case Builtin::BI__builtin_strlen:
  3801. // As an extension, we support strlen() and __builtin_strlen() as constant
  3802. // expressions when the argument is a string literal.
  3803. if (const StringLiteral *S
  3804. = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
  3805. // The string literal may have embedded null characters. Find the first
  3806. // one and truncate there.
  3807. StringRef Str = S->getString();
  3808. StringRef::size_type Pos = Str.find(0);
  3809. if (Pos != StringRef::npos)
  3810. Str = Str.substr(0, Pos);
  3811. return Success(Str.size(), E);
  3812. }
  3813. return Error(E);
  3814. case Builtin::BI__atomic_always_lock_free:
  3815. case Builtin::BI__atomic_is_lock_free:
  3816. case Builtin::BI__c11_atomic_is_lock_free: {
  3817. APSInt SizeVal;
  3818. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  3819. return false;
  3820. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  3821. // of two less than the maximum inline atomic width, we know it is
  3822. // lock-free. If the size isn't a power of two, or greater than the
  3823. // maximum alignment where we promote atomics, we know it is not lock-free
  3824. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  3825. // the answer can only be determined at runtime; for example, 16-byte
  3826. // atomics have lock-free implementations on some, but not all,
  3827. // x86-64 processors.
  3828. // Check power-of-two.
  3829. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  3830. if (Size.isPowerOfTwo()) {
  3831. // Check against inlining width.
  3832. unsigned InlineWidthBits =
  3833. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  3834. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  3835. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  3836. Size == CharUnits::One() ||
  3837. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  3838. Expr::NPC_NeverValueDependent))
  3839. // OK, we will inline appropriately-aligned operations of this size,
  3840. // and _Atomic(T) is appropriately-aligned.
  3841. return Success(1, E);
  3842. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  3843. castAs<PointerType>()->getPointeeType();
  3844. if (!PointeeType->isIncompleteType() &&
  3845. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  3846. // OK, we will inline operations on this object.
  3847. return Success(1, E);
  3848. }
  3849. }
  3850. }
  3851. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  3852. Success(0, E) : Error(E);
  3853. }
  3854. }
  3855. }
  3856. static bool HasSameBase(const LValue &A, const LValue &B) {
  3857. if (!A.getLValueBase())
  3858. return !B.getLValueBase();
  3859. if (!B.getLValueBase())
  3860. return false;
  3861. if (A.getLValueBase().getOpaqueValue() !=
  3862. B.getLValueBase().getOpaqueValue()) {
  3863. const Decl *ADecl = GetLValueBaseDecl(A);
  3864. if (!ADecl)
  3865. return false;
  3866. const Decl *BDecl = GetLValueBaseDecl(B);
  3867. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  3868. return false;
  3869. }
  3870. return IsGlobalLValue(A.getLValueBase()) ||
  3871. A.getLValueCallIndex() == B.getLValueCallIndex();
  3872. }
  3873. /// Perform the given integer operation, which is known to need at most BitWidth
  3874. /// bits, and check for overflow in the original type (if that type was not an
  3875. /// unsigned type).
  3876. template<typename Operation>
  3877. static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  3878. const APSInt &LHS, const APSInt &RHS,
  3879. unsigned BitWidth, Operation Op) {
  3880. if (LHS.isUnsigned())
  3881. return Op(LHS, RHS);
  3882. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  3883. APSInt Result = Value.trunc(LHS.getBitWidth());
  3884. if (Result.extend(BitWidth) != Value)
  3885. HandleOverflow(Info, E, Value, E->getType());
  3886. return Result;
  3887. }
  3888. namespace {
  3889. /// \brief Data recursive integer evaluator of certain binary operators.
  3890. ///
  3891. /// We use a data recursive algorithm for binary operators so that we are able
  3892. /// to handle extreme cases of chained binary operators without causing stack
  3893. /// overflow.
  3894. class DataRecursiveIntBinOpEvaluator {
  3895. struct EvalResult {
  3896. APValue Val;
  3897. bool Failed;
  3898. EvalResult() : Failed(false) { }
  3899. void swap(EvalResult &RHS) {
  3900. Val.swap(RHS.Val);
  3901. Failed = RHS.Failed;
  3902. RHS.Failed = false;
  3903. }
  3904. };
  3905. struct Job {
  3906. const Expr *E;
  3907. EvalResult LHSResult; // meaningful only for binary operator expression.
  3908. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  3909. Job() : StoredInfo(0) { }
  3910. void startSpeculativeEval(EvalInfo &Info) {
  3911. OldEvalStatus = Info.EvalStatus;
  3912. Info.EvalStatus.Diag = 0;
  3913. StoredInfo = &Info;
  3914. }
  3915. ~Job() {
  3916. if (StoredInfo) {
  3917. StoredInfo->EvalStatus = OldEvalStatus;
  3918. }
  3919. }
  3920. private:
  3921. EvalInfo *StoredInfo; // non-null if status changed.
  3922. Expr::EvalStatus OldEvalStatus;
  3923. };
  3924. SmallVector<Job, 16> Queue;
  3925. IntExprEvaluator &IntEval;
  3926. EvalInfo &Info;
  3927. APValue &FinalResult;
  3928. public:
  3929. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  3930. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  3931. /// \brief True if \param E is a binary operator that we are going to handle
  3932. /// data recursively.
  3933. /// We handle binary operators that are comma, logical, or that have operands
  3934. /// with integral or enumeration type.
  3935. static bool shouldEnqueue(const BinaryOperator *E) {
  3936. return E->getOpcode() == BO_Comma ||
  3937. E->isLogicalOp() ||
  3938. (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  3939. E->getRHS()->getType()->isIntegralOrEnumerationType());
  3940. }
  3941. bool Traverse(const BinaryOperator *E) {
  3942. enqueue(E);
  3943. EvalResult PrevResult;
  3944. while (!Queue.empty())
  3945. process(PrevResult);
  3946. if (PrevResult.Failed) return false;
  3947. FinalResult.swap(PrevResult.Val);
  3948. return true;
  3949. }
  3950. private:
  3951. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  3952. return IntEval.Success(Value, E, Result);
  3953. }
  3954. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  3955. return IntEval.Success(Value, E, Result);
  3956. }
  3957. bool Error(const Expr *E) {
  3958. return IntEval.Error(E);
  3959. }
  3960. bool Error(const Expr *E, diag::kind D) {
  3961. return IntEval.Error(E, D);
  3962. }
  3963. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  3964. return Info.CCEDiag(E, D);
  3965. }
  3966. // \brief Returns true if visiting the RHS is necessary, false otherwise.
  3967. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  3968. bool &SuppressRHSDiags);
  3969. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  3970. const BinaryOperator *E, APValue &Result);
  3971. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  3972. Result.Failed = !Evaluate(Result.Val, Info, E);
  3973. if (Result.Failed)
  3974. Result.Val = APValue();
  3975. }
  3976. void process(EvalResult &Result);
  3977. void enqueue(const Expr *E) {
  3978. E = E->IgnoreParens();
  3979. Queue.resize(Queue.size()+1);
  3980. Queue.back().E = E;
  3981. Queue.back().Kind = Job::AnyExprKind;
  3982. }
  3983. };
  3984. }
  3985. bool DataRecursiveIntBinOpEvaluator::
  3986. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  3987. bool &SuppressRHSDiags) {
  3988. if (E->getOpcode() == BO_Comma) {
  3989. // Ignore LHS but note if we could not evaluate it.
  3990. if (LHSResult.Failed)
  3991. Info.EvalStatus.HasSideEffects = true;
  3992. return true;
  3993. }
  3994. if (E->isLogicalOp()) {
  3995. bool lhsResult;
  3996. if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
  3997. // We were able to evaluate the LHS, see if we can get away with not
  3998. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  3999. if (lhsResult == (E->getOpcode() == BO_LOr)) {
  4000. Success(lhsResult, E, LHSResult.Val);
  4001. return false; // Ignore RHS
  4002. }
  4003. } else {
  4004. // Since we weren't able to evaluate the left hand side, it
  4005. // must have had side effects.
  4006. Info.EvalStatus.HasSideEffects = true;
  4007. // We can't evaluate the LHS; however, sometimes the result
  4008. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  4009. // Don't ignore RHS and suppress diagnostics from this arm.
  4010. SuppressRHSDiags = true;
  4011. }
  4012. return true;
  4013. }
  4014. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  4015. E->getRHS()->getType()->isIntegralOrEnumerationType());
  4016. if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
  4017. return false; // Ignore RHS;
  4018. return true;
  4019. }
  4020. bool DataRecursiveIntBinOpEvaluator::
  4021. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  4022. const BinaryOperator *E, APValue &Result) {
  4023. if (E->getOpcode() == BO_Comma) {
  4024. if (RHSResult.Failed)
  4025. return false;
  4026. Result = RHSResult.Val;
  4027. return true;
  4028. }
  4029. if (E->isLogicalOp()) {
  4030. bool lhsResult, rhsResult;
  4031. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  4032. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  4033. if (LHSIsOK) {
  4034. if (RHSIsOK) {
  4035. if (E->getOpcode() == BO_LOr)
  4036. return Success(lhsResult || rhsResult, E, Result);
  4037. else
  4038. return Success(lhsResult && rhsResult, E, Result);
  4039. }
  4040. } else {
  4041. if (RHSIsOK) {
  4042. // We can't evaluate the LHS; however, sometimes the result
  4043. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  4044. if (rhsResult == (E->getOpcode() == BO_LOr))
  4045. return Success(rhsResult, E, Result);
  4046. }
  4047. }
  4048. return false;
  4049. }
  4050. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  4051. E->getRHS()->getType()->isIntegralOrEnumerationType());
  4052. if (LHSResult.Failed || RHSResult.Failed)
  4053. return false;
  4054. const APValue &LHSVal = LHSResult.Val;
  4055. const APValue &RHSVal = RHSResult.Val;
  4056. // Handle cases like (unsigned long)&a + 4.
  4057. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  4058. Result = LHSVal;
  4059. CharUnits AdditionalOffset = CharUnits::fromQuantity(
  4060. RHSVal.getInt().getZExtValue());
  4061. if (E->getOpcode() == BO_Add)
  4062. Result.getLValueOffset() += AdditionalOffset;
  4063. else
  4064. Result.getLValueOffset() -= AdditionalOffset;
  4065. return true;
  4066. }
  4067. // Handle cases like 4 + (unsigned long)&a
  4068. if (E->getOpcode() == BO_Add &&
  4069. RHSVal.isLValue() && LHSVal.isInt()) {
  4070. Result = RHSVal;
  4071. Result.getLValueOffset() += CharUnits::fromQuantity(
  4072. LHSVal.getInt().getZExtValue());
  4073. return true;
  4074. }
  4075. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  4076. // Handle (intptr_t)&&A - (intptr_t)&&B.
  4077. if (!LHSVal.getLValueOffset().isZero() ||
  4078. !RHSVal.getLValueOffset().isZero())
  4079. return false;
  4080. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  4081. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  4082. if (!LHSExpr || !RHSExpr)
  4083. return false;
  4084. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  4085. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  4086. if (!LHSAddrExpr || !RHSAddrExpr)
  4087. return false;
  4088. // Make sure both labels come from the same function.
  4089. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  4090. RHSAddrExpr->getLabel()->getDeclContext())
  4091. return false;
  4092. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  4093. return true;
  4094. }
  4095. // All the following cases expect both operands to be an integer
  4096. if (!LHSVal.isInt() || !RHSVal.isInt())
  4097. return Error(E);
  4098. const APSInt &LHS = LHSVal.getInt();
  4099. APSInt RHS = RHSVal.getInt();
  4100. switch (E->getOpcode()) {
  4101. default:
  4102. return Error(E);
  4103. case BO_Mul:
  4104. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4105. LHS.getBitWidth() * 2,
  4106. std::multiplies<APSInt>()), E,
  4107. Result);
  4108. case BO_Add:
  4109. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4110. LHS.getBitWidth() + 1,
  4111. std::plus<APSInt>()), E, Result);
  4112. case BO_Sub:
  4113. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4114. LHS.getBitWidth() + 1,
  4115. std::minus<APSInt>()), E, Result);
  4116. case BO_And: return Success(LHS & RHS, E, Result);
  4117. case BO_Xor: return Success(LHS ^ RHS, E, Result);
  4118. case BO_Or: return Success(LHS | RHS, E, Result);
  4119. case BO_Div:
  4120. case BO_Rem:
  4121. if (RHS == 0)
  4122. return Error(E, diag::note_expr_divide_by_zero);
  4123. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
  4124. // not actually undefined behavior in C++11 due to a language defect.
  4125. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  4126. LHS.isSigned() && LHS.isMinSignedValue())
  4127. HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
  4128. return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
  4129. Result);
  4130. case BO_Shl: {
  4131. if (Info.getLangOpts().OpenCL)
  4132. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  4133. RHS &= APSInt(llvm::APInt(LHS.getBitWidth(),
  4134. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  4135. RHS.isUnsigned());
  4136. else if (RHS.isSigned() && RHS.isNegative()) {
  4137. // During constant-folding, a negative shift is an opposite shift. Such
  4138. // a shift is not a constant expression.
  4139. CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  4140. RHS = -RHS;
  4141. goto shift_right;
  4142. }
  4143. shift_left:
  4144. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  4145. // the shifted type.
  4146. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  4147. if (SA != RHS) {
  4148. CCEDiag(E, diag::note_constexpr_large_shift)
  4149. << RHS << E->getType() << LHS.getBitWidth();
  4150. } else if (LHS.isSigned()) {
  4151. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  4152. // operand, and must not overflow the corresponding unsigned type.
  4153. if (LHS.isNegative())
  4154. CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  4155. else if (LHS.countLeadingZeros() < SA)
  4156. CCEDiag(E, diag::note_constexpr_lshift_discards);
  4157. }
  4158. return Success(LHS << SA, E, Result);
  4159. }
  4160. case BO_Shr: {
  4161. if (Info.getLangOpts().OpenCL)
  4162. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  4163. RHS &= APSInt(llvm::APInt(LHS.getBitWidth(),
  4164. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  4165. RHS.isUnsigned());
  4166. else if (RHS.isSigned() && RHS.isNegative()) {
  4167. // During constant-folding, a negative shift is an opposite shift. Such a
  4168. // shift is not a constant expression.
  4169. CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  4170. RHS = -RHS;
  4171. goto shift_left;
  4172. }
  4173. shift_right:
  4174. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  4175. // shifted type.
  4176. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  4177. if (SA != RHS)
  4178. CCEDiag(E, diag::note_constexpr_large_shift)
  4179. << RHS << E->getType() << LHS.getBitWidth();
  4180. return Success(LHS >> SA, E, Result);
  4181. }
  4182. case BO_LT: return Success(LHS < RHS, E, Result);
  4183. case BO_GT: return Success(LHS > RHS, E, Result);
  4184. case BO_LE: return Success(LHS <= RHS, E, Result);
  4185. case BO_GE: return Success(LHS >= RHS, E, Result);
  4186. case BO_EQ: return Success(LHS == RHS, E, Result);
  4187. case BO_NE: return Success(LHS != RHS, E, Result);
  4188. }
  4189. }
  4190. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  4191. Job &job = Queue.back();
  4192. switch (job.Kind) {
  4193. case Job::AnyExprKind: {
  4194. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  4195. if (shouldEnqueue(Bop)) {
  4196. job.Kind = Job::BinOpKind;
  4197. enqueue(Bop->getLHS());
  4198. return;
  4199. }
  4200. }
  4201. EvaluateExpr(job.E, Result);
  4202. Queue.pop_back();
  4203. return;
  4204. }
  4205. case Job::BinOpKind: {
  4206. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  4207. bool SuppressRHSDiags = false;
  4208. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  4209. Queue.pop_back();
  4210. return;
  4211. }
  4212. if (SuppressRHSDiags)
  4213. job.startSpeculativeEval(Info);
  4214. job.LHSResult.swap(Result);
  4215. job.Kind = Job::BinOpVisitedLHSKind;
  4216. enqueue(Bop->getRHS());
  4217. return;
  4218. }
  4219. case Job::BinOpVisitedLHSKind: {
  4220. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  4221. EvalResult RHS;
  4222. RHS.swap(Result);
  4223. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  4224. Queue.pop_back();
  4225. return;
  4226. }
  4227. }
  4228. llvm_unreachable("Invalid Job::Kind!");
  4229. }
  4230. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  4231. if (E->isAssignmentOp())
  4232. return Error(E);
  4233. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  4234. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  4235. QualType LHSTy = E->getLHS()->getType();
  4236. QualType RHSTy = E->getRHS()->getType();
  4237. if (LHSTy->isAnyComplexType()) {
  4238. assert(RHSTy->isAnyComplexType() && "Invalid comparison");
  4239. ComplexValue LHS, RHS;
  4240. bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  4241. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  4242. return false;
  4243. if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  4244. return false;
  4245. if (LHS.isComplexFloat()) {
  4246. APFloat::cmpResult CR_r =
  4247. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  4248. APFloat::cmpResult CR_i =
  4249. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  4250. if (E->getOpcode() == BO_EQ)
  4251. return Success((CR_r == APFloat::cmpEqual &&
  4252. CR_i == APFloat::cmpEqual), E);
  4253. else {
  4254. assert(E->getOpcode() == BO_NE &&
  4255. "Invalid complex comparison.");
  4256. return Success(((CR_r == APFloat::cmpGreaterThan ||
  4257. CR_r == APFloat::cmpLessThan ||
  4258. CR_r == APFloat::cmpUnordered) ||
  4259. (CR_i == APFloat::cmpGreaterThan ||
  4260. CR_i == APFloat::cmpLessThan ||
  4261. CR_i == APFloat::cmpUnordered)), E);
  4262. }
  4263. } else {
  4264. if (E->getOpcode() == BO_EQ)
  4265. return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  4266. LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
  4267. else {
  4268. assert(E->getOpcode() == BO_NE &&
  4269. "Invalid compex comparison.");
  4270. return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
  4271. LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
  4272. }
  4273. }
  4274. }
  4275. if (LHSTy->isRealFloatingType() &&
  4276. RHSTy->isRealFloatingType()) {
  4277. APFloat RHS(0.0), LHS(0.0);
  4278. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  4279. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  4280. return false;
  4281. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  4282. return false;
  4283. APFloat::cmpResult CR = LHS.compare(RHS);
  4284. switch (E->getOpcode()) {
  4285. default:
  4286. llvm_unreachable("Invalid binary operator!");
  4287. case BO_LT:
  4288. return Success(CR == APFloat::cmpLessThan, E);
  4289. case BO_GT:
  4290. return Success(CR == APFloat::cmpGreaterThan, E);
  4291. case BO_LE:
  4292. return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
  4293. case BO_GE:
  4294. return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
  4295. E);
  4296. case BO_EQ:
  4297. return Success(CR == APFloat::cmpEqual, E);
  4298. case BO_NE:
  4299. return Success(CR == APFloat::cmpGreaterThan
  4300. || CR == APFloat::cmpLessThan
  4301. || CR == APFloat::cmpUnordered, E);
  4302. }
  4303. }
  4304. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  4305. if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
  4306. LValue LHSValue, RHSValue;
  4307. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  4308. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  4309. return false;
  4310. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  4311. return false;
  4312. // Reject differing bases from the normal codepath; we special-case
  4313. // comparisons to null.
  4314. if (!HasSameBase(LHSValue, RHSValue)) {
  4315. if (E->getOpcode() == BO_Sub) {
  4316. // Handle &&A - &&B.
  4317. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  4318. return false;
  4319. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
  4320. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
  4321. if (!LHSExpr || !RHSExpr)
  4322. return false;
  4323. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  4324. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  4325. if (!LHSAddrExpr || !RHSAddrExpr)
  4326. return false;
  4327. // Make sure both labels come from the same function.
  4328. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  4329. RHSAddrExpr->getLabel()->getDeclContext())
  4330. return false;
  4331. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  4332. return true;
  4333. }
  4334. // Inequalities and subtractions between unrelated pointers have
  4335. // unspecified or undefined behavior.
  4336. if (!E->isEqualityOp())
  4337. return Error(E);
  4338. // A constant address may compare equal to the address of a symbol.
  4339. // The one exception is that address of an object cannot compare equal
  4340. // to a null pointer constant.
  4341. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  4342. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  4343. return Error(E);
  4344. // It's implementation-defined whether distinct literals will have
  4345. // distinct addresses. In clang, the result of such a comparison is
  4346. // unspecified, so it is not a constant expression. However, we do know
  4347. // that the address of a literal will be non-null.
  4348. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  4349. LHSValue.Base && RHSValue.Base)
  4350. return Error(E);
  4351. // We can't tell whether weak symbols will end up pointing to the same
  4352. // object.
  4353. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  4354. return Error(E);
  4355. // Pointers with different bases cannot represent the same object.
  4356. // (Note that clang defaults to -fmerge-all-constants, which can
  4357. // lead to inconsistent results for comparisons involving the address
  4358. // of a constant; this generally doesn't matter in practice.)
  4359. return Success(E->getOpcode() == BO_NE, E);
  4360. }
  4361. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  4362. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  4363. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  4364. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  4365. if (E->getOpcode() == BO_Sub) {
  4366. // C++11 [expr.add]p6:
  4367. // Unless both pointers point to elements of the same array object, or
  4368. // one past the last element of the array object, the behavior is
  4369. // undefined.
  4370. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  4371. !AreElementsOfSameArray(getType(LHSValue.Base),
  4372. LHSDesignator, RHSDesignator))
  4373. CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  4374. QualType Type = E->getLHS()->getType();
  4375. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  4376. CharUnits ElementSize;
  4377. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  4378. return false;
  4379. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  4380. // and produce incorrect results when it overflows. Such behavior
  4381. // appears to be non-conforming, but is common, so perhaps we should
  4382. // assume the standard intended for such cases to be undefined behavior
  4383. // and check for them.
  4384. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  4385. // overflow in the final conversion to ptrdiff_t.
  4386. APSInt LHS(
  4387. llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  4388. APSInt RHS(
  4389. llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  4390. APSInt ElemSize(
  4391. llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
  4392. APSInt TrueResult = (LHS - RHS) / ElemSize;
  4393. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  4394. if (Result.extend(65) != TrueResult)
  4395. HandleOverflow(Info, E, TrueResult, E->getType());
  4396. return Success(Result, E);
  4397. }
  4398. // C++11 [expr.rel]p3:
  4399. // Pointers to void (after pointer conversions) can be compared, with a
  4400. // result defined as follows: If both pointers represent the same
  4401. // address or are both the null pointer value, the result is true if the
  4402. // operator is <= or >= and false otherwise; otherwise the result is
  4403. // unspecified.
  4404. // We interpret this as applying to pointers to *cv* void.
  4405. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
  4406. E->isRelationalOp())
  4407. CCEDiag(E, diag::note_constexpr_void_comparison);
  4408. // C++11 [expr.rel]p2:
  4409. // - If two pointers point to non-static data members of the same object,
  4410. // or to subobjects or array elements fo such members, recursively, the
  4411. // pointer to the later declared member compares greater provided the
  4412. // two members have the same access control and provided their class is
  4413. // not a union.
  4414. // [...]
  4415. // - Otherwise pointer comparisons are unspecified.
  4416. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  4417. E->isRelationalOp()) {
  4418. bool WasArrayIndex;
  4419. unsigned Mismatch =
  4420. FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
  4421. RHSDesignator, WasArrayIndex);
  4422. // At the point where the designators diverge, the comparison has a
  4423. // specified value if:
  4424. // - we are comparing array indices
  4425. // - we are comparing fields of a union, or fields with the same access
  4426. // Otherwise, the result is unspecified and thus the comparison is not a
  4427. // constant expression.
  4428. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  4429. Mismatch < RHSDesignator.Entries.size()) {
  4430. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  4431. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  4432. if (!LF && !RF)
  4433. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  4434. else if (!LF)
  4435. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  4436. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  4437. << RF->getParent() << RF;
  4438. else if (!RF)
  4439. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  4440. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  4441. << LF->getParent() << LF;
  4442. else if (!LF->getParent()->isUnion() &&
  4443. LF->getAccess() != RF->getAccess())
  4444. CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
  4445. << LF << LF->getAccess() << RF << RF->getAccess()
  4446. << LF->getParent();
  4447. }
  4448. }
  4449. // The comparison here must be unsigned, and performed with the same
  4450. // width as the pointer.
  4451. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  4452. uint64_t CompareLHS = LHSOffset.getQuantity();
  4453. uint64_t CompareRHS = RHSOffset.getQuantity();
  4454. assert(PtrSize <= 64 && "Unexpected pointer width");
  4455. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  4456. CompareLHS &= Mask;
  4457. CompareRHS &= Mask;
  4458. // If there is a base and this is a relational operator, we can only
  4459. // compare pointers within the object in question; otherwise, the result
  4460. // depends on where the object is located in memory.
  4461. if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
  4462. QualType BaseTy = getType(LHSValue.Base);
  4463. if (BaseTy->isIncompleteType())
  4464. return Error(E);
  4465. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  4466. uint64_t OffsetLimit = Size.getQuantity();
  4467. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  4468. return Error(E);
  4469. }
  4470. switch (E->getOpcode()) {
  4471. default: llvm_unreachable("missing comparison operator");
  4472. case BO_LT: return Success(CompareLHS < CompareRHS, E);
  4473. case BO_GT: return Success(CompareLHS > CompareRHS, E);
  4474. case BO_LE: return Success(CompareLHS <= CompareRHS, E);
  4475. case BO_GE: return Success(CompareLHS >= CompareRHS, E);
  4476. case BO_EQ: return Success(CompareLHS == CompareRHS, E);
  4477. case BO_NE: return Success(CompareLHS != CompareRHS, E);
  4478. }
  4479. }
  4480. }
  4481. if (LHSTy->isMemberPointerType()) {
  4482. assert(E->isEqualityOp() && "unexpected member pointer operation");
  4483. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  4484. MemberPtr LHSValue, RHSValue;
  4485. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  4486. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  4487. return false;
  4488. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  4489. return false;
  4490. // C++11 [expr.eq]p2:
  4491. // If both operands are null, they compare equal. Otherwise if only one is
  4492. // null, they compare unequal.
  4493. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  4494. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  4495. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  4496. }
  4497. // Otherwise if either is a pointer to a virtual member function, the
  4498. // result is unspecified.
  4499. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  4500. if (MD->isVirtual())
  4501. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  4502. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  4503. if (MD->isVirtual())
  4504. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  4505. // Otherwise they compare equal if and only if they would refer to the
  4506. // same member of the same most derived object or the same subobject if
  4507. // they were dereferenced with a hypothetical object of the associated
  4508. // class type.
  4509. bool Equal = LHSValue == RHSValue;
  4510. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  4511. }
  4512. if (LHSTy->isNullPtrType()) {
  4513. assert(E->isComparisonOp() && "unexpected nullptr operation");
  4514. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  4515. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  4516. // are compared, the result is true of the operator is <=, >= or ==, and
  4517. // false otherwise.
  4518. BinaryOperator::Opcode Opcode = E->getOpcode();
  4519. return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
  4520. }
  4521. assert((!LHSTy->isIntegralOrEnumerationType() ||
  4522. !RHSTy->isIntegralOrEnumerationType()) &&
  4523. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  4524. // We can't continue from here for non-integral types.
  4525. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4526. }
  4527. CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
  4528. // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
  4529. // result shall be the alignment of the referenced type."
  4530. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  4531. T = Ref->getPointeeType();
  4532. // __alignof is defined to return the preferred alignment.
  4533. return Info.Ctx.toCharUnitsFromBits(
  4534. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  4535. }
  4536. CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
  4537. E = E->IgnoreParens();
  4538. // alignof decl is always accepted, even if it doesn't make sense: we default
  4539. // to 1 in those cases.
  4540. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4541. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  4542. /*RefAsPointee*/true);
  4543. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  4544. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  4545. /*RefAsPointee*/true);
  4546. return GetAlignOfType(E->getType());
  4547. }
  4548. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  4549. /// a result as the expression's type.
  4550. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  4551. const UnaryExprOrTypeTraitExpr *E) {
  4552. switch(E->getKind()) {
  4553. case UETT_AlignOf: {
  4554. if (E->isArgumentType())
  4555. return Success(GetAlignOfType(E->getArgumentType()), E);
  4556. else
  4557. return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
  4558. }
  4559. case UETT_VecStep: {
  4560. QualType Ty = E->getTypeOfArgument();
  4561. if (Ty->isVectorType()) {
  4562. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  4563. // The vec_step built-in functions that take a 3-component
  4564. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  4565. if (n == 3)
  4566. n = 4;
  4567. return Success(n, E);
  4568. } else
  4569. return Success(1, E);
  4570. }
  4571. case UETT_SizeOf: {
  4572. QualType SrcTy = E->getTypeOfArgument();
  4573. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  4574. // the result is the size of the referenced type."
  4575. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  4576. SrcTy = Ref->getPointeeType();
  4577. CharUnits Sizeof;
  4578. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  4579. return false;
  4580. return Success(Sizeof, E);
  4581. }
  4582. }
  4583. llvm_unreachable("unknown expr/type trait");
  4584. }
  4585. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  4586. CharUnits Result;
  4587. unsigned n = OOE->getNumComponents();
  4588. if (n == 0)
  4589. return Error(OOE);
  4590. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  4591. for (unsigned i = 0; i != n; ++i) {
  4592. OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
  4593. switch (ON.getKind()) {
  4594. case OffsetOfExpr::OffsetOfNode::Array: {
  4595. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  4596. APSInt IdxResult;
  4597. if (!EvaluateInteger(Idx, IdxResult, Info))
  4598. return false;
  4599. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  4600. if (!AT)
  4601. return Error(OOE);
  4602. CurrentType = AT->getElementType();
  4603. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  4604. Result += IdxResult.getSExtValue() * ElementSize;
  4605. break;
  4606. }
  4607. case OffsetOfExpr::OffsetOfNode::Field: {
  4608. FieldDecl *MemberDecl = ON.getField();
  4609. const RecordType *RT = CurrentType->getAs<RecordType>();
  4610. if (!RT)
  4611. return Error(OOE);
  4612. RecordDecl *RD = RT->getDecl();
  4613. if (RD->isInvalidDecl()) return false;
  4614. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  4615. unsigned i = MemberDecl->getFieldIndex();
  4616. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  4617. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  4618. CurrentType = MemberDecl->getType().getNonReferenceType();
  4619. break;
  4620. }
  4621. case OffsetOfExpr::OffsetOfNode::Identifier:
  4622. llvm_unreachable("dependent __builtin_offsetof");
  4623. case OffsetOfExpr::OffsetOfNode::Base: {
  4624. CXXBaseSpecifier *BaseSpec = ON.getBase();
  4625. if (BaseSpec->isVirtual())
  4626. return Error(OOE);
  4627. // Find the layout of the class whose base we are looking into.
  4628. const RecordType *RT = CurrentType->getAs<RecordType>();
  4629. if (!RT)
  4630. return Error(OOE);
  4631. RecordDecl *RD = RT->getDecl();
  4632. if (RD->isInvalidDecl()) return false;
  4633. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  4634. // Find the base class itself.
  4635. CurrentType = BaseSpec->getType();
  4636. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  4637. if (!BaseRT)
  4638. return Error(OOE);
  4639. // Add the offset to the base.
  4640. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  4641. break;
  4642. }
  4643. }
  4644. }
  4645. return Success(Result, OOE);
  4646. }
  4647. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  4648. switch (E->getOpcode()) {
  4649. default:
  4650. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  4651. // See C99 6.6p3.
  4652. return Error(E);
  4653. case UO_Extension:
  4654. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  4655. // If so, we could clear the diagnostic ID.
  4656. return Visit(E->getSubExpr());
  4657. case UO_Plus:
  4658. // The result is just the value.
  4659. return Visit(E->getSubExpr());
  4660. case UO_Minus: {
  4661. if (!Visit(E->getSubExpr()))
  4662. return false;
  4663. if (!Result.isInt()) return Error(E);
  4664. const APSInt &Value = Result.getInt();
  4665. if (Value.isSigned() && Value.isMinSignedValue())
  4666. HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  4667. E->getType());
  4668. return Success(-Value, E);
  4669. }
  4670. case UO_Not: {
  4671. if (!Visit(E->getSubExpr()))
  4672. return false;
  4673. if (!Result.isInt()) return Error(E);
  4674. return Success(~Result.getInt(), E);
  4675. }
  4676. case UO_LNot: {
  4677. bool bres;
  4678. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  4679. return false;
  4680. return Success(!bres, E);
  4681. }
  4682. }
  4683. }
  4684. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  4685. /// result type is integer.
  4686. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4687. const Expr *SubExpr = E->getSubExpr();
  4688. QualType DestType = E->getType();
  4689. QualType SrcType = SubExpr->getType();
  4690. switch (E->getCastKind()) {
  4691. case CK_BaseToDerived:
  4692. case CK_DerivedToBase:
  4693. case CK_UncheckedDerivedToBase:
  4694. case CK_Dynamic:
  4695. case CK_ToUnion:
  4696. case CK_ArrayToPointerDecay:
  4697. case CK_FunctionToPointerDecay:
  4698. case CK_NullToPointer:
  4699. case CK_NullToMemberPointer:
  4700. case CK_BaseToDerivedMemberPointer:
  4701. case CK_DerivedToBaseMemberPointer:
  4702. case CK_ReinterpretMemberPointer:
  4703. case CK_ConstructorConversion:
  4704. case CK_IntegralToPointer:
  4705. case CK_ToVoid:
  4706. case CK_VectorSplat:
  4707. case CK_IntegralToFloating:
  4708. case CK_FloatingCast:
  4709. case CK_CPointerToObjCPointerCast:
  4710. case CK_BlockPointerToObjCPointerCast:
  4711. case CK_AnyPointerToBlockPointerCast:
  4712. case CK_ObjCObjectLValueCast:
  4713. case CK_FloatingRealToComplex:
  4714. case CK_FloatingComplexToReal:
  4715. case CK_FloatingComplexCast:
  4716. case CK_FloatingComplexToIntegralComplex:
  4717. case CK_IntegralRealToComplex:
  4718. case CK_IntegralComplexCast:
  4719. case CK_IntegralComplexToFloatingComplex:
  4720. case CK_BuiltinFnToFnPtr:
  4721. llvm_unreachable("invalid cast kind for integral value");
  4722. case CK_BitCast:
  4723. case CK_Dependent:
  4724. case CK_LValueBitCast:
  4725. case CK_ARCProduceObject:
  4726. case CK_ARCConsumeObject:
  4727. case CK_ARCReclaimReturnedObject:
  4728. case CK_ARCExtendBlockObject:
  4729. case CK_CopyAndAutoreleaseBlockObject:
  4730. return Error(E);
  4731. case CK_UserDefinedConversion:
  4732. case CK_LValueToRValue:
  4733. case CK_AtomicToNonAtomic:
  4734. case CK_NonAtomicToAtomic:
  4735. case CK_NoOp:
  4736. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4737. case CK_MemberPointerToBoolean:
  4738. case CK_PointerToBoolean:
  4739. case CK_IntegralToBoolean:
  4740. case CK_FloatingToBoolean:
  4741. case CK_FloatingComplexToBoolean:
  4742. case CK_IntegralComplexToBoolean: {
  4743. bool BoolResult;
  4744. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  4745. return false;
  4746. return Success(BoolResult, E);
  4747. }
  4748. case CK_IntegralCast: {
  4749. if (!Visit(SubExpr))
  4750. return false;
  4751. if (!Result.isInt()) {
  4752. // Allow casts of address-of-label differences if they are no-ops
  4753. // or narrowing. (The narrowing case isn't actually guaranteed to
  4754. // be constant-evaluatable except in some narrow cases which are hard
  4755. // to detect here. We let it through on the assumption the user knows
  4756. // what they are doing.)
  4757. if (Result.isAddrLabelDiff())
  4758. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  4759. // Only allow casts of lvalues if they are lossless.
  4760. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  4761. }
  4762. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  4763. Result.getInt()), E);
  4764. }
  4765. case CK_PointerToIntegral: {
  4766. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4767. LValue LV;
  4768. if (!EvaluatePointer(SubExpr, LV, Info))
  4769. return false;
  4770. if (LV.getLValueBase()) {
  4771. // Only allow based lvalue casts if they are lossless.
  4772. // FIXME: Allow a larger integer size than the pointer size, and allow
  4773. // narrowing back down to pointer width in subsequent integral casts.
  4774. // FIXME: Check integer type's active bits, not its type size.
  4775. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  4776. return Error(E);
  4777. LV.Designator.setInvalid();
  4778. LV.moveInto(Result);
  4779. return true;
  4780. }
  4781. APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
  4782. SrcType);
  4783. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  4784. }
  4785. case CK_IntegralComplexToReal: {
  4786. ComplexValue C;
  4787. if (!EvaluateComplex(SubExpr, C, Info))
  4788. return false;
  4789. return Success(C.getComplexIntReal(), E);
  4790. }
  4791. case CK_FloatingToIntegral: {
  4792. APFloat F(0.0);
  4793. if (!EvaluateFloat(SubExpr, F, Info))
  4794. return false;
  4795. APSInt Value;
  4796. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  4797. return false;
  4798. return Success(Value, E);
  4799. }
  4800. }
  4801. llvm_unreachable("unknown cast resulting in integral value");
  4802. }
  4803. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4804. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4805. ComplexValue LV;
  4806. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  4807. return false;
  4808. if (!LV.isComplexInt())
  4809. return Error(E);
  4810. return Success(LV.getComplexIntReal(), E);
  4811. }
  4812. return Visit(E->getSubExpr());
  4813. }
  4814. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4815. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  4816. ComplexValue LV;
  4817. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  4818. return false;
  4819. if (!LV.isComplexInt())
  4820. return Error(E);
  4821. return Success(LV.getComplexIntImag(), E);
  4822. }
  4823. VisitIgnoredValue(E->getSubExpr());
  4824. return Success(0, E);
  4825. }
  4826. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  4827. return Success(E->getPackLength(), E);
  4828. }
  4829. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  4830. return Success(E->getValue(), E);
  4831. }
  4832. //===----------------------------------------------------------------------===//
  4833. // Float Evaluation
  4834. //===----------------------------------------------------------------------===//
  4835. namespace {
  4836. class FloatExprEvaluator
  4837. : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
  4838. APFloat &Result;
  4839. public:
  4840. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  4841. : ExprEvaluatorBaseTy(info), Result(result) {}
  4842. bool Success(const APValue &V, const Expr *e) {
  4843. Result = V.getFloat();
  4844. return true;
  4845. }
  4846. bool ZeroInitialization(const Expr *E) {
  4847. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  4848. return true;
  4849. }
  4850. bool VisitCallExpr(const CallExpr *E);
  4851. bool VisitUnaryOperator(const UnaryOperator *E);
  4852. bool VisitBinaryOperator(const BinaryOperator *E);
  4853. bool VisitFloatingLiteral(const FloatingLiteral *E);
  4854. bool VisitCastExpr(const CastExpr *E);
  4855. bool VisitUnaryReal(const UnaryOperator *E);
  4856. bool VisitUnaryImag(const UnaryOperator *E);
  4857. // FIXME: Missing: array subscript of vector, member of vector
  4858. };
  4859. } // end anonymous namespace
  4860. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  4861. assert(E->isRValue() && E->getType()->isRealFloatingType());
  4862. return FloatExprEvaluator(Info, Result).Visit(E);
  4863. }
  4864. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  4865. QualType ResultTy,
  4866. const Expr *Arg,
  4867. bool SNaN,
  4868. llvm::APFloat &Result) {
  4869. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  4870. if (!S) return false;
  4871. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  4872. llvm::APInt fill;
  4873. // Treat empty strings as if they were zero.
  4874. if (S->getString().empty())
  4875. fill = llvm::APInt(32, 0);
  4876. else if (S->getString().getAsInteger(0, fill))
  4877. return false;
  4878. if (SNaN)
  4879. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  4880. else
  4881. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  4882. return true;
  4883. }
  4884. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  4885. switch (E->isBuiltinCall()) {
  4886. default:
  4887. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  4888. case Builtin::BI__builtin_huge_val:
  4889. case Builtin::BI__builtin_huge_valf:
  4890. case Builtin::BI__builtin_huge_vall:
  4891. case Builtin::BI__builtin_inf:
  4892. case Builtin::BI__builtin_inff:
  4893. case Builtin::BI__builtin_infl: {
  4894. const llvm::fltSemantics &Sem =
  4895. Info.Ctx.getFloatTypeSemantics(E->getType());
  4896. Result = llvm::APFloat::getInf(Sem);
  4897. return true;
  4898. }
  4899. case Builtin::BI__builtin_nans:
  4900. case Builtin::BI__builtin_nansf:
  4901. case Builtin::BI__builtin_nansl:
  4902. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  4903. true, Result))
  4904. return Error(E);
  4905. return true;
  4906. case Builtin::BI__builtin_nan:
  4907. case Builtin::BI__builtin_nanf:
  4908. case Builtin::BI__builtin_nanl:
  4909. // If this is __builtin_nan() turn this into a nan, otherwise we
  4910. // can't constant fold it.
  4911. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  4912. false, Result))
  4913. return Error(E);
  4914. return true;
  4915. case Builtin::BI__builtin_fabs:
  4916. case Builtin::BI__builtin_fabsf:
  4917. case Builtin::BI__builtin_fabsl:
  4918. if (!EvaluateFloat(E->getArg(0), Result, Info))
  4919. return false;
  4920. if (Result.isNegative())
  4921. Result.changeSign();
  4922. return true;
  4923. case Builtin::BI__builtin_copysign:
  4924. case Builtin::BI__builtin_copysignf:
  4925. case Builtin::BI__builtin_copysignl: {
  4926. APFloat RHS(0.);
  4927. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  4928. !EvaluateFloat(E->getArg(1), RHS, Info))
  4929. return false;
  4930. Result.copySign(RHS);
  4931. return true;
  4932. }
  4933. }
  4934. }
  4935. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4936. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4937. ComplexValue CV;
  4938. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  4939. return false;
  4940. Result = CV.FloatReal;
  4941. return true;
  4942. }
  4943. return Visit(E->getSubExpr());
  4944. }
  4945. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4946. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4947. ComplexValue CV;
  4948. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  4949. return false;
  4950. Result = CV.FloatImag;
  4951. return true;
  4952. }
  4953. VisitIgnoredValue(E->getSubExpr());
  4954. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  4955. Result = llvm::APFloat::getZero(Sem);
  4956. return true;
  4957. }
  4958. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  4959. switch (E->getOpcode()) {
  4960. default: return Error(E);
  4961. case UO_Plus:
  4962. return EvaluateFloat(E->getSubExpr(), Result, Info);
  4963. case UO_Minus:
  4964. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  4965. return false;
  4966. Result.changeSign();
  4967. return true;
  4968. }
  4969. }
  4970. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  4971. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  4972. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4973. APFloat RHS(0.0);
  4974. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  4975. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  4976. return false;
  4977. if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
  4978. return false;
  4979. switch (E->getOpcode()) {
  4980. default: return Error(E);
  4981. case BO_Mul:
  4982. Result.multiply(RHS, APFloat::rmNearestTiesToEven);
  4983. break;
  4984. case BO_Add:
  4985. Result.add(RHS, APFloat::rmNearestTiesToEven);
  4986. break;
  4987. case BO_Sub:
  4988. Result.subtract(RHS, APFloat::rmNearestTiesToEven);
  4989. break;
  4990. case BO_Div:
  4991. Result.divide(RHS, APFloat::rmNearestTiesToEven);
  4992. break;
  4993. }
  4994. if (Result.isInfinity() || Result.isNaN())
  4995. CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
  4996. return true;
  4997. }
  4998. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  4999. Result = E->getValue();
  5000. return true;
  5001. }
  5002. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5003. const Expr* SubExpr = E->getSubExpr();
  5004. switch (E->getCastKind()) {
  5005. default:
  5006. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5007. case CK_IntegralToFloating: {
  5008. APSInt IntResult;
  5009. return EvaluateInteger(SubExpr, IntResult, Info) &&
  5010. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  5011. E->getType(), Result);
  5012. }
  5013. case CK_FloatingCast: {
  5014. if (!Visit(SubExpr))
  5015. return false;
  5016. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  5017. Result);
  5018. }
  5019. case CK_FloatingComplexToReal: {
  5020. ComplexValue V;
  5021. if (!EvaluateComplex(SubExpr, V, Info))
  5022. return false;
  5023. Result = V.getComplexFloatReal();
  5024. return true;
  5025. }
  5026. }
  5027. }
  5028. //===----------------------------------------------------------------------===//
  5029. // Complex Evaluation (for float and integer)
  5030. //===----------------------------------------------------------------------===//
  5031. namespace {
  5032. class ComplexExprEvaluator
  5033. : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
  5034. ComplexValue &Result;
  5035. public:
  5036. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  5037. : ExprEvaluatorBaseTy(info), Result(Result) {}
  5038. bool Success(const APValue &V, const Expr *e) {
  5039. Result.setFrom(V);
  5040. return true;
  5041. }
  5042. bool ZeroInitialization(const Expr *E);
  5043. //===--------------------------------------------------------------------===//
  5044. // Visitor Methods
  5045. //===--------------------------------------------------------------------===//
  5046. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  5047. bool VisitCastExpr(const CastExpr *E);
  5048. bool VisitBinaryOperator(const BinaryOperator *E);
  5049. bool VisitUnaryOperator(const UnaryOperator *E);
  5050. bool VisitInitListExpr(const InitListExpr *E);
  5051. };
  5052. } // end anonymous namespace
  5053. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  5054. EvalInfo &Info) {
  5055. assert(E->isRValue() && E->getType()->isAnyComplexType());
  5056. return ComplexExprEvaluator(Info, Result).Visit(E);
  5057. }
  5058. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  5059. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  5060. if (ElemTy->isRealFloatingType()) {
  5061. Result.makeComplexFloat();
  5062. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  5063. Result.FloatReal = Zero;
  5064. Result.FloatImag = Zero;
  5065. } else {
  5066. Result.makeComplexInt();
  5067. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  5068. Result.IntReal = Zero;
  5069. Result.IntImag = Zero;
  5070. }
  5071. return true;
  5072. }
  5073. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  5074. const Expr* SubExpr = E->getSubExpr();
  5075. if (SubExpr->getType()->isRealFloatingType()) {
  5076. Result.makeComplexFloat();
  5077. APFloat &Imag = Result.FloatImag;
  5078. if (!EvaluateFloat(SubExpr, Imag, Info))
  5079. return false;
  5080. Result.FloatReal = APFloat(Imag.getSemantics());
  5081. return true;
  5082. } else {
  5083. assert(SubExpr->getType()->isIntegerType() &&
  5084. "Unexpected imaginary literal.");
  5085. Result.makeComplexInt();
  5086. APSInt &Imag = Result.IntImag;
  5087. if (!EvaluateInteger(SubExpr, Imag, Info))
  5088. return false;
  5089. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  5090. return true;
  5091. }
  5092. }
  5093. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5094. switch (E->getCastKind()) {
  5095. case CK_BitCast:
  5096. case CK_BaseToDerived:
  5097. case CK_DerivedToBase:
  5098. case CK_UncheckedDerivedToBase:
  5099. case CK_Dynamic:
  5100. case CK_ToUnion:
  5101. case CK_ArrayToPointerDecay:
  5102. case CK_FunctionToPointerDecay:
  5103. case CK_NullToPointer:
  5104. case CK_NullToMemberPointer:
  5105. case CK_BaseToDerivedMemberPointer:
  5106. case CK_DerivedToBaseMemberPointer:
  5107. case CK_MemberPointerToBoolean:
  5108. case CK_ReinterpretMemberPointer:
  5109. case CK_ConstructorConversion:
  5110. case CK_IntegralToPointer:
  5111. case CK_PointerToIntegral:
  5112. case CK_PointerToBoolean:
  5113. case CK_ToVoid:
  5114. case CK_VectorSplat:
  5115. case CK_IntegralCast:
  5116. case CK_IntegralToBoolean:
  5117. case CK_IntegralToFloating:
  5118. case CK_FloatingToIntegral:
  5119. case CK_FloatingToBoolean:
  5120. case CK_FloatingCast:
  5121. case CK_CPointerToObjCPointerCast:
  5122. case CK_BlockPointerToObjCPointerCast:
  5123. case CK_AnyPointerToBlockPointerCast:
  5124. case CK_ObjCObjectLValueCast:
  5125. case CK_FloatingComplexToReal:
  5126. case CK_FloatingComplexToBoolean:
  5127. case CK_IntegralComplexToReal:
  5128. case CK_IntegralComplexToBoolean:
  5129. case CK_ARCProduceObject:
  5130. case CK_ARCConsumeObject:
  5131. case CK_ARCReclaimReturnedObject:
  5132. case CK_ARCExtendBlockObject:
  5133. case CK_CopyAndAutoreleaseBlockObject:
  5134. case CK_BuiltinFnToFnPtr:
  5135. llvm_unreachable("invalid cast kind for complex value");
  5136. case CK_LValueToRValue:
  5137. case CK_AtomicToNonAtomic:
  5138. case CK_NonAtomicToAtomic:
  5139. case CK_NoOp:
  5140. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5141. case CK_Dependent:
  5142. case CK_LValueBitCast:
  5143. case CK_UserDefinedConversion:
  5144. return Error(E);
  5145. case CK_FloatingRealToComplex: {
  5146. APFloat &Real = Result.FloatReal;
  5147. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  5148. return false;
  5149. Result.makeComplexFloat();
  5150. Result.FloatImag = APFloat(Real.getSemantics());
  5151. return true;
  5152. }
  5153. case CK_FloatingComplexCast: {
  5154. if (!Visit(E->getSubExpr()))
  5155. return false;
  5156. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  5157. QualType From
  5158. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  5159. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  5160. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  5161. }
  5162. case CK_FloatingComplexToIntegralComplex: {
  5163. if (!Visit(E->getSubExpr()))
  5164. return false;
  5165. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  5166. QualType From
  5167. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  5168. Result.makeComplexInt();
  5169. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  5170. To, Result.IntReal) &&
  5171. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  5172. To, Result.IntImag);
  5173. }
  5174. case CK_IntegralRealToComplex: {
  5175. APSInt &Real = Result.IntReal;
  5176. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  5177. return false;
  5178. Result.makeComplexInt();
  5179. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  5180. return true;
  5181. }
  5182. case CK_IntegralComplexCast: {
  5183. if (!Visit(E->getSubExpr()))
  5184. return false;
  5185. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  5186. QualType From
  5187. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  5188. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  5189. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  5190. return true;
  5191. }
  5192. case CK_IntegralComplexToFloatingComplex: {
  5193. if (!Visit(E->getSubExpr()))
  5194. return false;
  5195. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  5196. QualType From
  5197. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  5198. Result.makeComplexFloat();
  5199. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  5200. To, Result.FloatReal) &&
  5201. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  5202. To, Result.FloatImag);
  5203. }
  5204. }
  5205. llvm_unreachable("unknown cast resulting in complex value");
  5206. }
  5207. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5208. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  5209. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5210. bool LHSOK = Visit(E->getLHS());
  5211. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  5212. return false;
  5213. ComplexValue RHS;
  5214. if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  5215. return false;
  5216. assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
  5217. "Invalid operands to binary operator.");
  5218. switch (E->getOpcode()) {
  5219. default: return Error(E);
  5220. case BO_Add:
  5221. if (Result.isComplexFloat()) {
  5222. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  5223. APFloat::rmNearestTiesToEven);
  5224. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  5225. APFloat::rmNearestTiesToEven);
  5226. } else {
  5227. Result.getComplexIntReal() += RHS.getComplexIntReal();
  5228. Result.getComplexIntImag() += RHS.getComplexIntImag();
  5229. }
  5230. break;
  5231. case BO_Sub:
  5232. if (Result.isComplexFloat()) {
  5233. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  5234. APFloat::rmNearestTiesToEven);
  5235. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  5236. APFloat::rmNearestTiesToEven);
  5237. } else {
  5238. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  5239. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  5240. }
  5241. break;
  5242. case BO_Mul:
  5243. if (Result.isComplexFloat()) {
  5244. ComplexValue LHS = Result;
  5245. APFloat &LHS_r = LHS.getComplexFloatReal();
  5246. APFloat &LHS_i = LHS.getComplexFloatImag();
  5247. APFloat &RHS_r = RHS.getComplexFloatReal();
  5248. APFloat &RHS_i = RHS.getComplexFloatImag();
  5249. APFloat Tmp = LHS_r;
  5250. Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5251. Result.getComplexFloatReal() = Tmp;
  5252. Tmp = LHS_i;
  5253. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5254. Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
  5255. Tmp = LHS_r;
  5256. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5257. Result.getComplexFloatImag() = Tmp;
  5258. Tmp = LHS_i;
  5259. Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5260. Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
  5261. } else {
  5262. ComplexValue LHS = Result;
  5263. Result.getComplexIntReal() =
  5264. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  5265. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  5266. Result.getComplexIntImag() =
  5267. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  5268. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  5269. }
  5270. break;
  5271. case BO_Div:
  5272. if (Result.isComplexFloat()) {
  5273. ComplexValue LHS = Result;
  5274. APFloat &LHS_r = LHS.getComplexFloatReal();
  5275. APFloat &LHS_i = LHS.getComplexFloatImag();
  5276. APFloat &RHS_r = RHS.getComplexFloatReal();
  5277. APFloat &RHS_i = RHS.getComplexFloatImag();
  5278. APFloat &Res_r = Result.getComplexFloatReal();
  5279. APFloat &Res_i = Result.getComplexFloatImag();
  5280. APFloat Den = RHS_r;
  5281. Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5282. APFloat Tmp = RHS_i;
  5283. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5284. Den.add(Tmp, APFloat::rmNearestTiesToEven);
  5285. Res_r = LHS_r;
  5286. Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5287. Tmp = LHS_i;
  5288. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5289. Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
  5290. Res_r.divide(Den, APFloat::rmNearestTiesToEven);
  5291. Res_i = LHS_i;
  5292. Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5293. Tmp = LHS_r;
  5294. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5295. Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
  5296. Res_i.divide(Den, APFloat::rmNearestTiesToEven);
  5297. } else {
  5298. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  5299. return Error(E, diag::note_expr_divide_by_zero);
  5300. ComplexValue LHS = Result;
  5301. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  5302. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  5303. Result.getComplexIntReal() =
  5304. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  5305. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  5306. Result.getComplexIntImag() =
  5307. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  5308. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  5309. }
  5310. break;
  5311. }
  5312. return true;
  5313. }
  5314. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  5315. // Get the operand value into 'Result'.
  5316. if (!Visit(E->getSubExpr()))
  5317. return false;
  5318. switch (E->getOpcode()) {
  5319. default:
  5320. return Error(E);
  5321. case UO_Extension:
  5322. return true;
  5323. case UO_Plus:
  5324. // The result is always just the subexpr.
  5325. return true;
  5326. case UO_Minus:
  5327. if (Result.isComplexFloat()) {
  5328. Result.getComplexFloatReal().changeSign();
  5329. Result.getComplexFloatImag().changeSign();
  5330. }
  5331. else {
  5332. Result.getComplexIntReal() = -Result.getComplexIntReal();
  5333. Result.getComplexIntImag() = -Result.getComplexIntImag();
  5334. }
  5335. return true;
  5336. case UO_Not:
  5337. if (Result.isComplexFloat())
  5338. Result.getComplexFloatImag().changeSign();
  5339. else
  5340. Result.getComplexIntImag() = -Result.getComplexIntImag();
  5341. return true;
  5342. }
  5343. }
  5344. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5345. if (E->getNumInits() == 2) {
  5346. if (E->getType()->isComplexType()) {
  5347. Result.makeComplexFloat();
  5348. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  5349. return false;
  5350. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  5351. return false;
  5352. } else {
  5353. Result.makeComplexInt();
  5354. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  5355. return false;
  5356. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  5357. return false;
  5358. }
  5359. return true;
  5360. }
  5361. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  5362. }
  5363. //===----------------------------------------------------------------------===//
  5364. // Void expression evaluation, primarily for a cast to void on the LHS of a
  5365. // comma operator
  5366. //===----------------------------------------------------------------------===//
  5367. namespace {
  5368. class VoidExprEvaluator
  5369. : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
  5370. public:
  5371. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  5372. bool Success(const APValue &V, const Expr *e) { return true; }
  5373. bool VisitCastExpr(const CastExpr *E) {
  5374. switch (E->getCastKind()) {
  5375. default:
  5376. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5377. case CK_ToVoid:
  5378. VisitIgnoredValue(E->getSubExpr());
  5379. return true;
  5380. }
  5381. }
  5382. };
  5383. } // end anonymous namespace
  5384. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  5385. assert(E->isRValue() && E->getType()->isVoidType());
  5386. return VoidExprEvaluator(Info).Visit(E);
  5387. }
  5388. //===----------------------------------------------------------------------===//
  5389. // Top level Expr::EvaluateAsRValue method.
  5390. //===----------------------------------------------------------------------===//
  5391. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  5392. // In C, function designators are not lvalues, but we evaluate them as if they
  5393. // are.
  5394. if (E->isGLValue() || E->getType()->isFunctionType()) {
  5395. LValue LV;
  5396. if (!EvaluateLValue(E, LV, Info))
  5397. return false;
  5398. LV.moveInto(Result);
  5399. } else if (E->getType()->isVectorType()) {
  5400. if (!EvaluateVector(E, Result, Info))
  5401. return false;
  5402. } else if (E->getType()->isIntegralOrEnumerationType()) {
  5403. if (!IntExprEvaluator(Info, Result).Visit(E))
  5404. return false;
  5405. } else if (E->getType()->hasPointerRepresentation()) {
  5406. LValue LV;
  5407. if (!EvaluatePointer(E, LV, Info))
  5408. return false;
  5409. LV.moveInto(Result);
  5410. } else if (E->getType()->isRealFloatingType()) {
  5411. llvm::APFloat F(0.0);
  5412. if (!EvaluateFloat(E, F, Info))
  5413. return false;
  5414. Result = APValue(F);
  5415. } else if (E->getType()->isAnyComplexType()) {
  5416. ComplexValue C;
  5417. if (!EvaluateComplex(E, C, Info))
  5418. return false;
  5419. C.moveInto(Result);
  5420. } else if (E->getType()->isMemberPointerType()) {
  5421. MemberPtr P;
  5422. if (!EvaluateMemberPointer(E, P, Info))
  5423. return false;
  5424. P.moveInto(Result);
  5425. return true;
  5426. } else if (E->getType()->isArrayType()) {
  5427. LValue LV;
  5428. LV.set(E, Info.CurrentCall->Index);
  5429. if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
  5430. return false;
  5431. Result = Info.CurrentCall->Temporaries[E];
  5432. } else if (E->getType()->isRecordType()) {
  5433. LValue LV;
  5434. LV.set(E, Info.CurrentCall->Index);
  5435. if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
  5436. return false;
  5437. Result = Info.CurrentCall->Temporaries[E];
  5438. } else if (E->getType()->isVoidType()) {
  5439. if (!Info.getLangOpts().CPlusPlus11)
  5440. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  5441. << E->getType();
  5442. if (!EvaluateVoid(E, Info))
  5443. return false;
  5444. } else if (Info.getLangOpts().CPlusPlus11) {
  5445. Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
  5446. return false;
  5447. } else {
  5448. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  5449. return false;
  5450. }
  5451. return true;
  5452. }
  5453. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  5454. /// cases, the in-place evaluation is essential, since later initializers for
  5455. /// an object can indirectly refer to subobjects which were initialized earlier.
  5456. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  5457. const Expr *E, CheckConstantExpressionKind CCEK,
  5458. bool AllowNonLiteralTypes) {
  5459. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
  5460. return false;
  5461. if (E->isRValue()) {
  5462. // Evaluate arrays and record types in-place, so that later initializers can
  5463. // refer to earlier-initialized members of the object.
  5464. if (E->getType()->isArrayType())
  5465. return EvaluateArray(E, This, Result, Info);
  5466. else if (E->getType()->isRecordType())
  5467. return EvaluateRecord(E, This, Result, Info);
  5468. }
  5469. // For any other type, in-place evaluation is unimportant.
  5470. return Evaluate(Result, Info, E);
  5471. }
  5472. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  5473. /// lvalue-to-rvalue cast if it is an lvalue.
  5474. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  5475. if (!CheckLiteralType(Info, E))
  5476. return false;
  5477. if (!::Evaluate(Result, Info, E))
  5478. return false;
  5479. if (E->isGLValue()) {
  5480. LValue LV;
  5481. LV.setFrom(Info.Ctx, Result);
  5482. if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  5483. return false;
  5484. }
  5485. // Check this core constant expression is a constant expression.
  5486. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  5487. }
  5488. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  5489. /// any crazy technique (that has nothing to do with language standards) that
  5490. /// we want to. If this function returns true, it returns the folded constant
  5491. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  5492. /// will be applied to the result.
  5493. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  5494. // Fast-path evaluations of integer literals, since we sometimes see files
  5495. // containing vast quantities of these.
  5496. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
  5497. Result.Val = APValue(APSInt(L->getValue(),
  5498. L->getType()->isUnsignedIntegerType()));
  5499. return true;
  5500. }
  5501. // FIXME: Evaluating values of large array and record types can cause
  5502. // performance problems. Only do so in C++11 for now.
  5503. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  5504. !Ctx.getLangOpts().CPlusPlus11)
  5505. return false;
  5506. EvalInfo Info(Ctx, Result);
  5507. return ::EvaluateAsRValue(Info, this, Result.Val);
  5508. }
  5509. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  5510. const ASTContext &Ctx) const {
  5511. EvalResult Scratch;
  5512. return EvaluateAsRValue(Scratch, Ctx) &&
  5513. HandleConversionToBool(Scratch.Val, Result);
  5514. }
  5515. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  5516. SideEffectsKind AllowSideEffects) const {
  5517. if (!getType()->isIntegralOrEnumerationType())
  5518. return false;
  5519. EvalResult ExprResult;
  5520. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  5521. (!AllowSideEffects && ExprResult.HasSideEffects))
  5522. return false;
  5523. Result = ExprResult.Val.getInt();
  5524. return true;
  5525. }
  5526. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  5527. EvalInfo Info(Ctx, Result);
  5528. LValue LV;
  5529. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  5530. !CheckLValueConstantExpression(Info, getExprLoc(),
  5531. Ctx.getLValueReferenceType(getType()), LV))
  5532. return false;
  5533. LV.moveInto(Result.Val);
  5534. return true;
  5535. }
  5536. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  5537. const VarDecl *VD,
  5538. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  5539. // FIXME: Evaluating initializers for large array and record types can cause
  5540. // performance problems. Only do so in C++11 for now.
  5541. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  5542. !Ctx.getLangOpts().CPlusPlus11)
  5543. return false;
  5544. Expr::EvalStatus EStatus;
  5545. EStatus.Diag = &Notes;
  5546. EvalInfo InitInfo(Ctx, EStatus);
  5547. InitInfo.setEvaluatingDecl(VD, Value);
  5548. LValue LVal;
  5549. LVal.set(VD);
  5550. // C++11 [basic.start.init]p2:
  5551. // Variables with static storage duration or thread storage duration shall be
  5552. // zero-initialized before any other initialization takes place.
  5553. // This behavior is not present in C.
  5554. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  5555. !VD->getType()->isReferenceType()) {
  5556. ImplicitValueInitExpr VIE(VD->getType());
  5557. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
  5558. /*AllowNonLiteralTypes=*/true))
  5559. return false;
  5560. }
  5561. if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
  5562. /*AllowNonLiteralTypes=*/true) ||
  5563. EStatus.HasSideEffects)
  5564. return false;
  5565. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  5566. Value);
  5567. }
  5568. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  5569. /// constant folded, but discard the result.
  5570. bool Expr::isEvaluatable(const ASTContext &Ctx) const {
  5571. EvalResult Result;
  5572. return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
  5573. }
  5574. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  5575. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  5576. EvalResult EvalResult;
  5577. EvalResult.Diag = Diag;
  5578. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  5579. (void)Result;
  5580. assert(Result && "Could not evaluate expression");
  5581. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  5582. return EvalResult.Val.getInt();
  5583. }
  5584. bool Expr::EvalResult::isGlobalLValue() const {
  5585. assert(Val.isLValue());
  5586. return IsGlobalLValue(Val.getLValueBase());
  5587. }
  5588. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  5589. /// an integer constant expression.
  5590. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  5591. /// comma, etc
  5592. // CheckICE - This function does the fundamental ICE checking: the returned
  5593. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  5594. // and a (possibly null) SourceLocation indicating the location of the problem.
  5595. //
  5596. // Note that to reduce code duplication, this helper does no evaluation
  5597. // itself; the caller checks whether the expression is evaluatable, and
  5598. // in the rare cases where CheckICE actually cares about the evaluated
  5599. // value, it calls into Evalute.
  5600. namespace {
  5601. enum ICEKind {
  5602. /// This expression is an ICE.
  5603. IK_ICE,
  5604. /// This expression is not an ICE, but if it isn't evaluated, it's
  5605. /// a legal subexpression for an ICE. This return value is used to handle
  5606. /// the comma operator in C99 mode, and non-constant subexpressions.
  5607. IK_ICEIfUnevaluated,
  5608. /// This expression is not an ICE, and is not a legal subexpression for one.
  5609. IK_NotICE
  5610. };
  5611. struct ICEDiag {
  5612. ICEKind Kind;
  5613. SourceLocation Loc;
  5614. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  5615. };
  5616. }
  5617. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  5618. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  5619. static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
  5620. Expr::EvalResult EVResult;
  5621. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  5622. !EVResult.Val.isInt())
  5623. return ICEDiag(IK_NotICE, E->getLocStart());
  5624. return NoDiag();
  5625. }
  5626. static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
  5627. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  5628. if (!E->getType()->isIntegralOrEnumerationType())
  5629. return ICEDiag(IK_NotICE, E->getLocStart());
  5630. switch (E->getStmtClass()) {
  5631. #define ABSTRACT_STMT(Node)
  5632. #define STMT(Node, Base) case Expr::Node##Class:
  5633. #define EXPR(Node, Base)
  5634. #include "clang/AST/StmtNodes.inc"
  5635. case Expr::PredefinedExprClass:
  5636. case Expr::FloatingLiteralClass:
  5637. case Expr::ImaginaryLiteralClass:
  5638. case Expr::StringLiteralClass:
  5639. case Expr::ArraySubscriptExprClass:
  5640. case Expr::MemberExprClass:
  5641. case Expr::CompoundAssignOperatorClass:
  5642. case Expr::CompoundLiteralExprClass:
  5643. case Expr::ExtVectorElementExprClass:
  5644. case Expr::DesignatedInitExprClass:
  5645. case Expr::ImplicitValueInitExprClass:
  5646. case Expr::ParenListExprClass:
  5647. case Expr::VAArgExprClass:
  5648. case Expr::AddrLabelExprClass:
  5649. case Expr::StmtExprClass:
  5650. case Expr::CXXMemberCallExprClass:
  5651. case Expr::CUDAKernelCallExprClass:
  5652. case Expr::CXXDynamicCastExprClass:
  5653. case Expr::CXXTypeidExprClass:
  5654. case Expr::CXXUuidofExprClass:
  5655. case Expr::CXXNullPtrLiteralExprClass:
  5656. case Expr::UserDefinedLiteralClass:
  5657. case Expr::CXXThisExprClass:
  5658. case Expr::CXXThrowExprClass:
  5659. case Expr::CXXNewExprClass:
  5660. case Expr::CXXDeleteExprClass:
  5661. case Expr::CXXPseudoDestructorExprClass:
  5662. case Expr::UnresolvedLookupExprClass:
  5663. case Expr::DependentScopeDeclRefExprClass:
  5664. case Expr::CXXConstructExprClass:
  5665. case Expr::CXXBindTemporaryExprClass:
  5666. case Expr::ExprWithCleanupsClass:
  5667. case Expr::CXXTemporaryObjectExprClass:
  5668. case Expr::CXXUnresolvedConstructExprClass:
  5669. case Expr::CXXDependentScopeMemberExprClass:
  5670. case Expr::UnresolvedMemberExprClass:
  5671. case Expr::ObjCStringLiteralClass:
  5672. case Expr::ObjCBoxedExprClass:
  5673. case Expr::ObjCArrayLiteralClass:
  5674. case Expr::ObjCDictionaryLiteralClass:
  5675. case Expr::ObjCEncodeExprClass:
  5676. case Expr::ObjCMessageExprClass:
  5677. case Expr::ObjCSelectorExprClass:
  5678. case Expr::ObjCProtocolExprClass:
  5679. case Expr::ObjCIvarRefExprClass:
  5680. case Expr::ObjCPropertyRefExprClass:
  5681. case Expr::ObjCSubscriptRefExprClass:
  5682. case Expr::ObjCIsaExprClass:
  5683. case Expr::ShuffleVectorExprClass:
  5684. case Expr::BlockExprClass:
  5685. case Expr::NoStmtClass:
  5686. case Expr::OpaqueValueExprClass:
  5687. case Expr::PackExpansionExprClass:
  5688. case Expr::SubstNonTypeTemplateParmPackExprClass:
  5689. case Expr::FunctionParmPackExprClass:
  5690. case Expr::AsTypeExprClass:
  5691. case Expr::ObjCIndirectCopyRestoreExprClass:
  5692. case Expr::MaterializeTemporaryExprClass:
  5693. case Expr::PseudoObjectExprClass:
  5694. case Expr::AtomicExprClass:
  5695. case Expr::InitListExprClass:
  5696. case Expr::LambdaExprClass:
  5697. return ICEDiag(IK_NotICE, E->getLocStart());
  5698. case Expr::SizeOfPackExprClass:
  5699. case Expr::GNUNullExprClass:
  5700. // GCC considers the GNU __null value to be an integral constant expression.
  5701. return NoDiag();
  5702. case Expr::SubstNonTypeTemplateParmExprClass:
  5703. return
  5704. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  5705. case Expr::ParenExprClass:
  5706. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  5707. case Expr::GenericSelectionExprClass:
  5708. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  5709. case Expr::IntegerLiteralClass:
  5710. case Expr::CharacterLiteralClass:
  5711. case Expr::ObjCBoolLiteralExprClass:
  5712. case Expr::CXXBoolLiteralExprClass:
  5713. case Expr::CXXScalarValueInitExprClass:
  5714. case Expr::UnaryTypeTraitExprClass:
  5715. case Expr::BinaryTypeTraitExprClass:
  5716. case Expr::TypeTraitExprClass:
  5717. case Expr::ArrayTypeTraitExprClass:
  5718. case Expr::ExpressionTraitExprClass:
  5719. case Expr::CXXNoexceptExprClass:
  5720. return NoDiag();
  5721. case Expr::CallExprClass:
  5722. case Expr::CXXOperatorCallExprClass: {
  5723. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  5724. // constant expressions, but they can never be ICEs because an ICE cannot
  5725. // contain an operand of (pointer to) function type.
  5726. const CallExpr *CE = cast<CallExpr>(E);
  5727. if (CE->isBuiltinCall())
  5728. return CheckEvalInICE(E, Ctx);
  5729. return ICEDiag(IK_NotICE, E->getLocStart());
  5730. }
  5731. case Expr::DeclRefExprClass: {
  5732. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  5733. return NoDiag();
  5734. const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
  5735. if (Ctx.getLangOpts().CPlusPlus &&
  5736. D && IsConstNonVolatile(D->getType())) {
  5737. // Parameter variables are never constants. Without this check,
  5738. // getAnyInitializer() can find a default argument, which leads
  5739. // to chaos.
  5740. if (isa<ParmVarDecl>(D))
  5741. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  5742. // C++ 7.1.5.1p2
  5743. // A variable of non-volatile const-qualified integral or enumeration
  5744. // type initialized by an ICE can be used in ICEs.
  5745. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  5746. if (!Dcl->getType()->isIntegralOrEnumerationType())
  5747. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  5748. const VarDecl *VD;
  5749. // Look for a declaration of this variable that has an initializer, and
  5750. // check whether it is an ICE.
  5751. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  5752. return NoDiag();
  5753. else
  5754. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  5755. }
  5756. }
  5757. return ICEDiag(IK_NotICE, E->getLocStart());
  5758. }
  5759. case Expr::UnaryOperatorClass: {
  5760. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  5761. switch (Exp->getOpcode()) {
  5762. case UO_PostInc:
  5763. case UO_PostDec:
  5764. case UO_PreInc:
  5765. case UO_PreDec:
  5766. case UO_AddrOf:
  5767. case UO_Deref:
  5768. // C99 6.6/3 allows increment and decrement within unevaluated
  5769. // subexpressions of constant expressions, but they can never be ICEs
  5770. // because an ICE cannot contain an lvalue operand.
  5771. return ICEDiag(IK_NotICE, E->getLocStart());
  5772. case UO_Extension:
  5773. case UO_LNot:
  5774. case UO_Plus:
  5775. case UO_Minus:
  5776. case UO_Not:
  5777. case UO_Real:
  5778. case UO_Imag:
  5779. return CheckICE(Exp->getSubExpr(), Ctx);
  5780. }
  5781. // OffsetOf falls through here.
  5782. }
  5783. case Expr::OffsetOfExprClass: {
  5784. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  5785. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  5786. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  5787. // compliance: we should warn earlier for offsetof expressions with
  5788. // array subscripts that aren't ICEs, and if the array subscripts
  5789. // are ICEs, the value of the offsetof must be an integer constant.
  5790. return CheckEvalInICE(E, Ctx);
  5791. }
  5792. case Expr::UnaryExprOrTypeTraitExprClass: {
  5793. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  5794. if ((Exp->getKind() == UETT_SizeOf) &&
  5795. Exp->getTypeOfArgument()->isVariableArrayType())
  5796. return ICEDiag(IK_NotICE, E->getLocStart());
  5797. return NoDiag();
  5798. }
  5799. case Expr::BinaryOperatorClass: {
  5800. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  5801. switch (Exp->getOpcode()) {
  5802. case BO_PtrMemD:
  5803. case BO_PtrMemI:
  5804. case BO_Assign:
  5805. case BO_MulAssign:
  5806. case BO_DivAssign:
  5807. case BO_RemAssign:
  5808. case BO_AddAssign:
  5809. case BO_SubAssign:
  5810. case BO_ShlAssign:
  5811. case BO_ShrAssign:
  5812. case BO_AndAssign:
  5813. case BO_XorAssign:
  5814. case BO_OrAssign:
  5815. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  5816. // constant expressions, but they can never be ICEs because an ICE cannot
  5817. // contain an lvalue operand.
  5818. return ICEDiag(IK_NotICE, E->getLocStart());
  5819. case BO_Mul:
  5820. case BO_Div:
  5821. case BO_Rem:
  5822. case BO_Add:
  5823. case BO_Sub:
  5824. case BO_Shl:
  5825. case BO_Shr:
  5826. case BO_LT:
  5827. case BO_GT:
  5828. case BO_LE:
  5829. case BO_GE:
  5830. case BO_EQ:
  5831. case BO_NE:
  5832. case BO_And:
  5833. case BO_Xor:
  5834. case BO_Or:
  5835. case BO_Comma: {
  5836. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  5837. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  5838. if (Exp->getOpcode() == BO_Div ||
  5839. Exp->getOpcode() == BO_Rem) {
  5840. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  5841. // we don't evaluate one.
  5842. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  5843. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  5844. if (REval == 0)
  5845. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  5846. if (REval.isSigned() && REval.isAllOnesValue()) {
  5847. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  5848. if (LEval.isMinSignedValue())
  5849. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  5850. }
  5851. }
  5852. }
  5853. if (Exp->getOpcode() == BO_Comma) {
  5854. if (Ctx.getLangOpts().C99) {
  5855. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  5856. // if it isn't evaluated.
  5857. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  5858. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  5859. } else {
  5860. // In both C89 and C++, commas in ICEs are illegal.
  5861. return ICEDiag(IK_NotICE, E->getLocStart());
  5862. }
  5863. }
  5864. return Worst(LHSResult, RHSResult);
  5865. }
  5866. case BO_LAnd:
  5867. case BO_LOr: {
  5868. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  5869. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  5870. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  5871. // Rare case where the RHS has a comma "side-effect"; we need
  5872. // to actually check the condition to see whether the side
  5873. // with the comma is evaluated.
  5874. if ((Exp->getOpcode() == BO_LAnd) !=
  5875. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  5876. return RHSResult;
  5877. return NoDiag();
  5878. }
  5879. return Worst(LHSResult, RHSResult);
  5880. }
  5881. }
  5882. }
  5883. case Expr::ImplicitCastExprClass:
  5884. case Expr::CStyleCastExprClass:
  5885. case Expr::CXXFunctionalCastExprClass:
  5886. case Expr::CXXStaticCastExprClass:
  5887. case Expr::CXXReinterpretCastExprClass:
  5888. case Expr::CXXConstCastExprClass:
  5889. case Expr::ObjCBridgedCastExprClass: {
  5890. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  5891. if (isa<ExplicitCastExpr>(E)) {
  5892. if (const FloatingLiteral *FL
  5893. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  5894. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  5895. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  5896. APSInt IgnoredVal(DestWidth, !DestSigned);
  5897. bool Ignored;
  5898. // If the value does not fit in the destination type, the behavior is
  5899. // undefined, so we are not required to treat it as a constant
  5900. // expression.
  5901. if (FL->getValue().convertToInteger(IgnoredVal,
  5902. llvm::APFloat::rmTowardZero,
  5903. &Ignored) & APFloat::opInvalidOp)
  5904. return ICEDiag(IK_NotICE, E->getLocStart());
  5905. return NoDiag();
  5906. }
  5907. }
  5908. switch (cast<CastExpr>(E)->getCastKind()) {
  5909. case CK_LValueToRValue:
  5910. case CK_AtomicToNonAtomic:
  5911. case CK_NonAtomicToAtomic:
  5912. case CK_NoOp:
  5913. case CK_IntegralToBoolean:
  5914. case CK_IntegralCast:
  5915. return CheckICE(SubExpr, Ctx);
  5916. default:
  5917. return ICEDiag(IK_NotICE, E->getLocStart());
  5918. }
  5919. }
  5920. case Expr::BinaryConditionalOperatorClass: {
  5921. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  5922. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  5923. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  5924. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  5925. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  5926. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  5927. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  5928. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  5929. return FalseResult;
  5930. }
  5931. case Expr::ConditionalOperatorClass: {
  5932. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  5933. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5934. // then only the true side is actually considered in an integer constant
  5935. // expression, and it is fully evaluated. This is an important GNU
  5936. // extension. See GCC PR38377 for discussion.
  5937. if (const CallExpr *CallCE
  5938. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  5939. if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
  5940. return CheckEvalInICE(E, Ctx);
  5941. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  5942. if (CondResult.Kind == IK_NotICE)
  5943. return CondResult;
  5944. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  5945. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  5946. if (TrueResult.Kind == IK_NotICE)
  5947. return TrueResult;
  5948. if (FalseResult.Kind == IK_NotICE)
  5949. return FalseResult;
  5950. if (CondResult.Kind == IK_ICEIfUnevaluated)
  5951. return CondResult;
  5952. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  5953. return NoDiag();
  5954. // Rare case where the diagnostics depend on which side is evaluated
  5955. // Note that if we get here, CondResult is 0, and at least one of
  5956. // TrueResult and FalseResult is non-zero.
  5957. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  5958. return FalseResult;
  5959. return TrueResult;
  5960. }
  5961. case Expr::CXXDefaultArgExprClass:
  5962. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  5963. case Expr::ChooseExprClass: {
  5964. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
  5965. }
  5966. }
  5967. llvm_unreachable("Invalid StmtClass!");
  5968. }
  5969. /// Evaluate an expression as a C++11 integral constant expression.
  5970. static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
  5971. const Expr *E,
  5972. llvm::APSInt *Value,
  5973. SourceLocation *Loc) {
  5974. if (!E->getType()->isIntegralOrEnumerationType()) {
  5975. if (Loc) *Loc = E->getExprLoc();
  5976. return false;
  5977. }
  5978. APValue Result;
  5979. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  5980. return false;
  5981. assert(Result.isInt() && "pointer cast to int is not an ICE");
  5982. if (Value) *Value = Result.getInt();
  5983. return true;
  5984. }
  5985. bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
  5986. if (Ctx.getLangOpts().CPlusPlus11)
  5987. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
  5988. ICEDiag D = CheckICE(this, Ctx);
  5989. if (D.Kind != IK_ICE) {
  5990. if (Loc) *Loc = D.Loc;
  5991. return false;
  5992. }
  5993. return true;
  5994. }
  5995. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
  5996. SourceLocation *Loc, bool isEvaluated) const {
  5997. if (Ctx.getLangOpts().CPlusPlus11)
  5998. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  5999. if (!isIntegerConstantExpr(Ctx, Loc))
  6000. return false;
  6001. if (!EvaluateAsInt(Value, Ctx))
  6002. llvm_unreachable("ICE cannot be evaluated!");
  6003. return true;
  6004. }
  6005. bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
  6006. return CheckICE(this, Ctx).Kind == IK_ICE;
  6007. }
  6008. bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
  6009. SourceLocation *Loc) const {
  6010. // We support this checking in C++98 mode in order to diagnose compatibility
  6011. // issues.
  6012. assert(Ctx.getLangOpts().CPlusPlus);
  6013. // Build evaluation settings.
  6014. Expr::EvalStatus Status;
  6015. SmallVector<PartialDiagnosticAt, 8> Diags;
  6016. Status.Diag = &Diags;
  6017. EvalInfo Info(Ctx, Status);
  6018. APValue Scratch;
  6019. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  6020. if (!Diags.empty()) {
  6021. IsConstExpr = false;
  6022. if (Loc) *Loc = Diags[0].first;
  6023. } else if (!IsConstExpr) {
  6024. // FIXME: This shouldn't happen.
  6025. if (Loc) *Loc = getExprLoc();
  6026. }
  6027. return IsConstExpr;
  6028. }
  6029. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  6030. SmallVectorImpl<
  6031. PartialDiagnosticAt> &Diags) {
  6032. // FIXME: It would be useful to check constexpr function templates, but at the
  6033. // moment the constant expression evaluator cannot cope with the non-rigorous
  6034. // ASTs which we build for dependent expressions.
  6035. if (FD->isDependentContext())
  6036. return true;
  6037. Expr::EvalStatus Status;
  6038. Status.Diag = &Diags;
  6039. EvalInfo Info(FD->getASTContext(), Status);
  6040. Info.CheckingPotentialConstantExpression = true;
  6041. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6042. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
  6043. // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
  6044. // is a temporary being used as the 'this' pointer.
  6045. LValue This;
  6046. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  6047. This.set(&VIE, Info.CurrentCall->Index);
  6048. ArrayRef<const Expr*> Args;
  6049. SourceLocation Loc = FD->getLocation();
  6050. APValue Scratch;
  6051. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  6052. HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
  6053. else
  6054. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
  6055. Args, FD->getBody(), Info, Scratch);
  6056. return Diags.empty();
  6057. }