ExprConstant.cpp 329 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Expr constant evaluator.
  11. //
  12. // Constant expression evaluation produces four main results:
  13. //
  14. // * A success/failure flag indicating whether constant folding was successful.
  15. // This is the 'bool' return value used by most of the code in this file. A
  16. // 'false' return value indicates that constant folding has failed, and any
  17. // appropriate diagnostic has already been produced.
  18. //
  19. // * An evaluated result, valid only if constant folding has not failed.
  20. //
  21. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  22. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  23. // where it is possible to determine the evaluated result regardless.
  24. //
  25. // * A set of notes indicating why the evaluation was not a constant expression
  26. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  27. // too, why the expression could not be folded.
  28. //
  29. // If we are checking for a potential constant expression, failure to constant
  30. // fold a potential constant sub-expression will be indicated by a 'false'
  31. // return value (the expression could not be folded) and no diagnostic (the
  32. // expression is not necessarily non-constant).
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #include "clang/AST/APValue.h"
  36. #include "clang/AST/ASTContext.h"
  37. #include "clang/AST/ASTDiagnostic.h"
  38. #include "clang/AST/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. #include "llvm/Support/OacrIgnoreCond.h" // HLSL Change - constant evaluator is language-dependant
  50. #include "dxc/HlslIntrinsicOp.h" // HLSL Change
  51. using namespace clang;
  52. using llvm::APSInt;
  53. using llvm::APFloat;
  54. static bool IsGlobalLValue(APValue::LValueBase B);
  55. // HLSL Change Starts - reuse code from CallExpr::getBuiltinCallee
  56. static const FunctionDecl *GetCallExprFunction(const CallExpr *CE) {
  57. const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE->getCallee());
  58. if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
  59. return 0;
  60. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
  61. if (!DRE)
  62. return 0;
  63. const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
  64. if (!FDecl)
  65. return 0;
  66. if (!FDecl->getIdentifier())
  67. return 0;
  68. return FDecl;
  69. }
  70. // Returns true if the given InitListExpr is for constructing a HLSL vector
  71. // with the matching number of initializers and each initializer has the
  72. // matching element type.
  73. static bool IsHLSLVecInitList(const Expr* expr) {
  74. if (const auto* initExpr = dyn_cast<InitListExpr>(expr)) {
  75. const QualType vecType = initExpr->getType();
  76. if (!hlsl::IsHLSLVecType(vecType))
  77. return false;
  78. const uint32_t size = hlsl::GetHLSLVecSize(vecType);
  79. const QualType elemType = hlsl::GetHLSLVecElementType(vecType).getCanonicalType();
  80. if (initExpr->getNumInits() != size)
  81. return false;
  82. for (uint32_t i = 0; i < size; ++i)
  83. if (initExpr->getInit(i)->getType().getCanonicalType() != elemType)
  84. return false;
  85. return true;
  86. }
  87. return false;
  88. }
  89. // HLSL Change Ends
  90. namespace {
  91. struct LValue;
  92. struct CallStackFrame;
  93. struct EvalInfo;
  94. static QualType getType(APValue::LValueBase B) {
  95. if (!B) return QualType();
  96. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
  97. return D->getType();
  98. const Expr *Base = B.get<const Expr*>();
  99. // For a materialized temporary, the type of the temporary we materialized
  100. // may not be the type of the expression.
  101. if (const MaterializeTemporaryExpr *MTE =
  102. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  103. SmallVector<const Expr *, 2> CommaLHSs;
  104. SmallVector<SubobjectAdjustment, 2> Adjustments;
  105. const Expr *Temp = MTE->GetTemporaryExpr();
  106. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  107. Adjustments);
  108. // Keep any cv-qualifiers from the reference if we generated a temporary
  109. // for it.
  110. if (Inner != Temp)
  111. return Inner->getType();
  112. }
  113. return Base->getType();
  114. }
  115. /// Get an LValue path entry, which is known to not be an array index, as a
  116. /// field or base class.
  117. static
  118. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  119. APValue::BaseOrMemberType Value;
  120. Value.setFromOpaqueValue(E.BaseOrMember);
  121. return Value;
  122. }
  123. /// Get an LValue path entry, which is known to not be an array index, as a
  124. /// field declaration.
  125. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  126. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  127. }
  128. /// Get an LValue path entry, which is known to not be an array index, as a
  129. /// base class declaration.
  130. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  131. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  132. }
  133. /// Determine whether this LValue path entry for a base class names a virtual
  134. /// base class.
  135. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  136. return getAsBaseOrMember(E).getInt();
  137. }
  138. /// Find the path length and type of the most-derived subobject in the given
  139. /// path, and find the size of the containing array, if any.
  140. static
  141. unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
  142. ArrayRef<APValue::LValuePathEntry> Path,
  143. uint64_t &ArraySize, QualType &Type) {
  144. unsigned MostDerivedLength = 0;
  145. Type = Base;
  146. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  147. if (Type->isArrayType()) {
  148. const ConstantArrayType *CAT =
  149. cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
  150. Type = CAT->getElementType();
  151. ArraySize = CAT->getSize().getZExtValue();
  152. MostDerivedLength = I + 1;
  153. } else if (Type->isAnyComplexType()) {
  154. const ComplexType *CT = Type->castAs<ComplexType>();
  155. Type = CT->getElementType();
  156. ArraySize = 2;
  157. MostDerivedLength = I + 1;
  158. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  159. Type = FD->getType();
  160. ArraySize = 0;
  161. MostDerivedLength = I + 1;
  162. } else {
  163. // Path[I] describes a base class.
  164. ArraySize = 0;
  165. }
  166. }
  167. return MostDerivedLength;
  168. }
  169. // The order of this enum is important for diagnostics.
  170. enum CheckSubobjectKind {
  171. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  172. CSK_This, CSK_Real, CSK_Imag
  173. };
  174. /// A path from a glvalue to a subobject of that glvalue.
  175. struct SubobjectDesignator {
  176. /// True if the subobject was named in a manner not supported by C++11. Such
  177. /// lvalues can still be folded, but they are not core constant expressions
  178. /// and we cannot perform lvalue-to-rvalue conversions on them.
  179. bool Invalid : 1;
  180. /// Is this a pointer one past the end of an object?
  181. bool IsOnePastTheEnd : 1;
  182. /// The length of the path to the most-derived object of which this is a
  183. /// subobject.
  184. unsigned MostDerivedPathLength : 30;
  185. /// The size of the array of which the most-derived object is an element, or
  186. /// 0 if the most-derived object is not an array element.
  187. uint64_t MostDerivedArraySize;
  188. /// The type of the most derived object referred to by this address.
  189. QualType MostDerivedType;
  190. typedef APValue::LValuePathEntry PathEntry;
  191. /// The entries on the path from the glvalue to the designated subobject.
  192. SmallVector<PathEntry, 8> Entries;
  193. SubobjectDesignator() : Invalid(true) {}
  194. explicit SubobjectDesignator(QualType T)
  195. : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
  196. MostDerivedArraySize(0), MostDerivedType(T) {}
  197. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  198. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  199. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  200. if (!Invalid) {
  201. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  202. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  203. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  204. if (V.getLValueBase())
  205. MostDerivedPathLength =
  206. findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
  207. V.getLValuePath(), MostDerivedArraySize,
  208. MostDerivedType);
  209. }
  210. }
  211. void setInvalid() {
  212. Invalid = true;
  213. Entries.clear();
  214. }
  215. /// Determine whether this is a one-past-the-end pointer.
  216. bool isOnePastTheEnd() const {
  217. assert(!Invalid);
  218. if (IsOnePastTheEnd)
  219. return true;
  220. if (MostDerivedArraySize &&
  221. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  222. return true;
  223. return false;
  224. }
  225. /// Check that this refers to a valid subobject.
  226. bool isValidSubobject() const {
  227. if (Invalid)
  228. return false;
  229. return !isOnePastTheEnd();
  230. }
  231. /// Check that this refers to a valid subobject, and if not, produce a
  232. /// relevant diagnostic and set the designator as invalid.
  233. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  234. /// Update this designator to refer to the first element within this array.
  235. void addArrayUnchecked(const ConstantArrayType *CAT) {
  236. PathEntry Entry;
  237. Entry.ArrayIndex = 0;
  238. Entries.push_back(Entry);
  239. // This is a most-derived object.
  240. MostDerivedType = CAT->getElementType();
  241. MostDerivedArraySize = CAT->getSize().getZExtValue();
  242. MostDerivedPathLength = Entries.size();
  243. }
  244. /// Update this designator to refer to the given base or member of this
  245. /// object.
  246. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  247. PathEntry Entry;
  248. APValue::BaseOrMemberType Value(D, Virtual);
  249. Entry.BaseOrMember = Value.getOpaqueValue();
  250. Entries.push_back(Entry);
  251. // If this isn't a base class, it's a new most-derived object.
  252. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  253. MostDerivedType = FD->getType();
  254. MostDerivedArraySize = 0;
  255. MostDerivedPathLength = Entries.size();
  256. }
  257. }
  258. /// Update this designator to refer to the given complex component.
  259. void addComplexUnchecked(QualType EltTy, bool Imag) {
  260. PathEntry Entry;
  261. Entry.ArrayIndex = Imag;
  262. Entries.push_back(Entry);
  263. // This is technically a most-derived object, though in practice this
  264. // is unlikely to matter.
  265. MostDerivedType = EltTy;
  266. MostDerivedArraySize = 2;
  267. MostDerivedPathLength = Entries.size();
  268. }
  269. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
  270. /// Add N to the address of this subobject.
  271. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  272. if (Invalid) return;
  273. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
  274. Entries.back().ArrayIndex += N;
  275. if (Entries.back().ArrayIndex > MostDerivedArraySize) {
  276. diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
  277. setInvalid();
  278. }
  279. return;
  280. }
  281. // [expr.add]p4: For the purposes of these operators, a pointer to a
  282. // nonarray object behaves the same as a pointer to the first element of
  283. // an array of length one with the type of the object as its element type.
  284. if (IsOnePastTheEnd && N == (uint64_t)-1)
  285. IsOnePastTheEnd = false;
  286. else if (!IsOnePastTheEnd && N == 1)
  287. IsOnePastTheEnd = true;
  288. else if (N != 0) {
  289. diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
  290. setInvalid();
  291. }
  292. }
  293. };
  294. /// A stack frame in the constexpr call stack.
  295. struct CallStackFrame {
  296. EvalInfo &Info;
  297. /// Parent - The caller of this stack frame.
  298. CallStackFrame *Caller;
  299. /// CallLoc - The location of the call expression for this call.
  300. SourceLocation CallLoc;
  301. /// Callee - The function which was called.
  302. const FunctionDecl *Callee;
  303. /// Index - The call index of this call.
  304. unsigned Index;
  305. /// This - The binding for the this pointer in this call, if any.
  306. const LValue *This;
  307. /// Arguments - Parameter bindings for this function call, indexed by
  308. /// parameters' function scope indices.
  309. APValue *Arguments;
  310. // Note that we intentionally use std::map here so that references to
  311. // values are stable.
  312. typedef std::map<const void*, APValue> MapTy;
  313. typedef MapTy::const_iterator temp_iterator;
  314. /// Temporaries - Temporary lvalues materialized within this stack frame.
  315. MapTy Temporaries;
  316. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  317. const FunctionDecl *Callee, const LValue *This,
  318. APValue *Arguments);
  319. ~CallStackFrame();
  320. APValue *getTemporary(const void *Key) {
  321. MapTy::iterator I = Temporaries.find(Key);
  322. return I == Temporaries.end() ? nullptr : &I->second;
  323. }
  324. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  325. };
  326. /// Temporarily override 'this'.
  327. class ThisOverrideRAII {
  328. public:
  329. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  330. : Frame(Frame), OldThis(Frame.This) {
  331. if (Enable)
  332. Frame.This = NewThis;
  333. }
  334. ~ThisOverrideRAII() {
  335. Frame.This = OldThis;
  336. }
  337. private:
  338. CallStackFrame &Frame;
  339. const LValue *OldThis;
  340. };
  341. /// A partial diagnostic which we might know in advance that we are not going
  342. /// to emit.
  343. class OptionalDiagnostic {
  344. PartialDiagnostic *Diag;
  345. public:
  346. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  347. : Diag(Diag) {}
  348. template<typename T>
  349. OptionalDiagnostic &operator<<(const T &v) {
  350. if (Diag)
  351. *Diag << v;
  352. return *this;
  353. }
  354. OptionalDiagnostic &operator<<(const APSInt &I) {
  355. if (Diag) {
  356. SmallVector<char, 32> Buffer;
  357. I.toString(Buffer);
  358. *Diag << StringRef(Buffer.data(), Buffer.size());
  359. }
  360. return *this;
  361. }
  362. OptionalDiagnostic &operator<<(const APFloat &F) {
  363. if (Diag) {
  364. // FIXME: Force the precision of the source value down so we don't
  365. // print digits which are usually useless (we don't really care here if
  366. // we truncate a digit by accident in edge cases). Ideally,
  367. // APFloat::toString would automatically print the shortest
  368. // representation which rounds to the correct value, but it's a bit
  369. // tricky to implement.
  370. unsigned precision =
  371. llvm::APFloat::semanticsPrecision(F.getSemantics());
  372. precision = (precision * 59 + 195) / 196;
  373. SmallVector<char, 32> Buffer;
  374. F.toString(Buffer, precision);
  375. *Diag << StringRef(Buffer.data(), Buffer.size());
  376. }
  377. return *this;
  378. }
  379. };
  380. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  381. class Cleanup {
  382. llvm::PointerIntPair<APValue*, 1, bool> Value;
  383. public:
  384. Cleanup(APValue *Val, bool IsLifetimeExtended)
  385. : Value(Val, IsLifetimeExtended) {}
  386. bool isLifetimeExtended() const { return Value.getInt(); }
  387. void endLifetime() {
  388. *Value.getPointer() = APValue();
  389. }
  390. };
  391. /// EvalInfo - This is a private struct used by the evaluator to capture
  392. /// information about a subexpression as it is folded. It retains information
  393. /// about the AST context, but also maintains information about the folded
  394. /// expression.
  395. ///
  396. /// If an expression could be evaluated, it is still possible it is not a C
  397. /// "integer constant expression" or constant expression. If not, this struct
  398. /// captures information about how and why not.
  399. ///
  400. /// One bit of information passed *into* the request for constant folding
  401. /// indicates whether the subexpression is "evaluated" or not according to C
  402. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  403. /// evaluate the expression regardless of what the RHS is, but C only allows
  404. /// certain things in certain situations.
  405. struct EvalInfo {
  406. ASTContext &Ctx;
  407. /// EvalStatus - Contains information about the evaluation.
  408. Expr::EvalStatus &EvalStatus;
  409. /// CurrentCall - The top of the constexpr call stack.
  410. CallStackFrame *CurrentCall;
  411. /// CallStackDepth - The number of calls in the call stack right now.
  412. unsigned CallStackDepth;
  413. /// NextCallIndex - The next call index to assign.
  414. unsigned NextCallIndex;
  415. /// StepsLeft - The remaining number of evaluation steps we're permitted
  416. /// to perform. This is essentially a limit for the number of statements
  417. /// we will evaluate.
  418. unsigned StepsLeft;
  419. /// BottomFrame - The frame in which evaluation started. This must be
  420. /// initialized after CurrentCall and CallStackDepth.
  421. CallStackFrame BottomFrame;
  422. /// A stack of values whose lifetimes end at the end of some surrounding
  423. /// evaluation frame.
  424. llvm::SmallVector<Cleanup, 16> CleanupStack;
  425. /// EvaluatingDecl - This is the declaration whose initializer is being
  426. /// evaluated, if any.
  427. APValue::LValueBase EvaluatingDecl;
  428. /// EvaluatingDeclValue - This is the value being constructed for the
  429. /// declaration whose initializer is being evaluated, if any.
  430. APValue *EvaluatingDeclValue;
  431. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  432. /// notes attached to it will also be stored, otherwise they will not be.
  433. bool HasActiveDiagnostic;
  434. enum EvaluationMode {
  435. /// Evaluate as a constant expression. Stop if we find that the expression
  436. /// is not a constant expression.
  437. EM_ConstantExpression,
  438. /// Evaluate as a potential constant expression. Keep going if we hit a
  439. /// construct that we can't evaluate yet (because we don't yet know the
  440. /// value of something) but stop if we hit something that could never be
  441. /// a constant expression.
  442. EM_PotentialConstantExpression,
  443. /// Fold the expression to a constant. Stop if we hit a side-effect that
  444. /// we can't model.
  445. EM_ConstantFold,
  446. /// Evaluate the expression looking for integer overflow and similar
  447. /// issues. Don't worry about side-effects, and try to visit all
  448. /// subexpressions.
  449. EM_EvaluateForOverflow,
  450. /// Evaluate in any way we know how. Don't worry about side-effects that
  451. /// can't be modeled.
  452. EM_IgnoreSideEffects,
  453. /// Evaluate as a constant expression. Stop if we find that the expression
  454. /// is not a constant expression. Some expressions can be retried in the
  455. /// optimizer if we don't constant fold them here, but in an unevaluated
  456. /// context we try to fold them immediately since the optimizer never
  457. /// gets a chance to look at it.
  458. EM_ConstantExpressionUnevaluated,
  459. /// Evaluate as a potential constant expression. Keep going if we hit a
  460. /// construct that we can't evaluate yet (because we don't yet know the
  461. /// value of something) but stop if we hit something that could never be
  462. /// a constant expression. Some expressions can be retried in the
  463. /// optimizer if we don't constant fold them here, but in an unevaluated
  464. /// context we try to fold them immediately since the optimizer never
  465. /// gets a chance to look at it.
  466. EM_PotentialConstantExpressionUnevaluated
  467. } EvalMode;
  468. /// Are we checking whether the expression is a potential constant
  469. /// expression?
  470. bool checkingPotentialConstantExpression() const {
  471. return EvalMode == EM_PotentialConstantExpression ||
  472. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  473. }
  474. /// Are we checking an expression for overflow?
  475. // FIXME: We should check for any kind of undefined or suspicious behavior
  476. // in such constructs, not just overflow.
  477. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  478. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  479. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  480. CallStackDepth(0), NextCallIndex(1),
  481. StepsLeft(getLangOpts().ConstexprStepLimit),
  482. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  483. EvaluatingDecl((const ValueDecl *)nullptr),
  484. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  485. EvalMode(Mode) {}
  486. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  487. EvaluatingDecl = Base;
  488. EvaluatingDeclValue = &Value;
  489. }
  490. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  491. bool CheckCallLimit(SourceLocation Loc) {
  492. // Don't perform any constexpr calls (other than the call we're checking)
  493. // when checking a potential constant expression.
  494. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  495. return false;
  496. if (NextCallIndex == 0) {
  497. // NextCallIndex has wrapped around.
  498. Diag(Loc, diag::note_constexpr_call_limit_exceeded);
  499. return false;
  500. }
  501. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  502. return true;
  503. Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
  504. << getLangOpts().ConstexprCallDepth;
  505. return false;
  506. }
  507. CallStackFrame *getCallFrame(unsigned CallIndex) {
  508. assert(CallIndex && "no call index in getCallFrame");
  509. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  510. // be null in this loop.
  511. CallStackFrame *Frame = CurrentCall;
  512. while (Frame->Index > CallIndex)
  513. Frame = Frame->Caller;
  514. return (Frame->Index == CallIndex) ? Frame : nullptr;
  515. }
  516. bool nextStep(const Stmt *S) {
  517. if (!StepsLeft) {
  518. Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
  519. return false;
  520. }
  521. --StepsLeft;
  522. return true;
  523. }
  524. private:
  525. /// Add a diagnostic to the diagnostics list.
  526. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  527. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  528. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  529. return EvalStatus.Diag->back().second;
  530. }
  531. /// Add notes containing a call stack to the current point of evaluation.
  532. void addCallStack(unsigned Limit);
  533. public:
  534. /// Diagnose that the evaluation cannot be folded.
  535. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
  536. = diag::note_invalid_subexpr_in_const_expr,
  537. unsigned ExtraNotes = 0) {
  538. if (EvalStatus.Diag) {
  539. // If we have a prior diagnostic, it will be noting that the expression
  540. // isn't a constant expression. This diagnostic is more important,
  541. // unless we require this evaluation to produce a constant expression.
  542. //
  543. // FIXME: We might want to show both diagnostics to the user in
  544. // EM_ConstantFold mode.
  545. if (!EvalStatus.Diag->empty()) {
  546. switch (EvalMode) {
  547. case EM_ConstantFold:
  548. case EM_IgnoreSideEffects:
  549. case EM_EvaluateForOverflow:
  550. if (!EvalStatus.HasSideEffects)
  551. break;
  552. // We've had side-effects; we want the diagnostic from them, not
  553. // some later problem.
  554. case EM_ConstantExpression:
  555. case EM_PotentialConstantExpression:
  556. case EM_ConstantExpressionUnevaluated:
  557. case EM_PotentialConstantExpressionUnevaluated:
  558. HasActiveDiagnostic = false;
  559. return OptionalDiagnostic();
  560. }
  561. }
  562. unsigned CallStackNotes = CallStackDepth - 1;
  563. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  564. if (Limit)
  565. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  566. if (checkingPotentialConstantExpression())
  567. CallStackNotes = 0;
  568. HasActiveDiagnostic = true;
  569. EvalStatus.Diag->clear();
  570. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  571. addDiag(Loc, DiagId);
  572. if (!checkingPotentialConstantExpression())
  573. addCallStack(Limit);
  574. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  575. }
  576. HasActiveDiagnostic = false;
  577. return OptionalDiagnostic();
  578. }
  579. OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
  580. = diag::note_invalid_subexpr_in_const_expr,
  581. unsigned ExtraNotes = 0) {
  582. if (EvalStatus.Diag)
  583. return Diag(E->getExprLoc(), DiagId, ExtraNotes);
  584. HasActiveDiagnostic = false;
  585. return OptionalDiagnostic();
  586. }
  587. /// Diagnose that the evaluation does not produce a C++11 core constant
  588. /// expression.
  589. ///
  590. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  591. /// EM_PotentialConstantExpression mode and we produce one of these.
  592. template<typename LocArg>
  593. OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
  594. = diag::note_invalid_subexpr_in_const_expr,
  595. unsigned ExtraNotes = 0) {
  596. // Don't override a previous diagnostic. Don't bother collecting
  597. // diagnostics if we're evaluating for overflow.
  598. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  599. HasActiveDiagnostic = false;
  600. return OptionalDiagnostic();
  601. }
  602. return Diag(Loc, DiagId, ExtraNotes);
  603. }
  604. /// Add a note to a prior diagnostic.
  605. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  606. if (!HasActiveDiagnostic)
  607. return OptionalDiagnostic();
  608. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  609. }
  610. /// Add a stack of notes to a prior diagnostic.
  611. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  612. if (HasActiveDiagnostic) {
  613. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  614. Diags.begin(), Diags.end());
  615. }
  616. }
  617. /// Should we continue evaluation after encountering a side-effect that we
  618. /// couldn't model?
  619. bool keepEvaluatingAfterSideEffect() {
  620. switch (EvalMode) {
  621. case EM_PotentialConstantExpression:
  622. case EM_PotentialConstantExpressionUnevaluated:
  623. case EM_EvaluateForOverflow:
  624. case EM_IgnoreSideEffects:
  625. return true;
  626. case EM_ConstantExpression:
  627. case EM_ConstantExpressionUnevaluated:
  628. case EM_ConstantFold:
  629. return false;
  630. }
  631. llvm_unreachable("Missed EvalMode case");
  632. }
  633. /// Note that we have had a side-effect, and determine whether we should
  634. /// keep evaluating.
  635. bool noteSideEffect() {
  636. EvalStatus.HasSideEffects = true;
  637. return keepEvaluatingAfterSideEffect();
  638. }
  639. /// Should we continue evaluation as much as possible after encountering a
  640. /// construct which can't be reduced to a value?
  641. bool keepEvaluatingAfterFailure() {
  642. if (!StepsLeft)
  643. return false;
  644. switch (EvalMode) {
  645. case EM_PotentialConstantExpression:
  646. case EM_PotentialConstantExpressionUnevaluated:
  647. case EM_EvaluateForOverflow:
  648. return true;
  649. case EM_ConstantExpression:
  650. case EM_ConstantExpressionUnevaluated:
  651. case EM_ConstantFold:
  652. case EM_IgnoreSideEffects:
  653. return false;
  654. }
  655. llvm_unreachable("Missed EvalMode case");
  656. }
  657. };
  658. /// Object used to treat all foldable expressions as constant expressions.
  659. struct FoldConstant {
  660. EvalInfo &Info;
  661. bool Enabled;
  662. bool HadNoPriorDiags;
  663. EvalInfo::EvaluationMode OldMode;
  664. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  665. : Info(Info),
  666. Enabled(Enabled),
  667. HadNoPriorDiags(Info.EvalStatus.Diag &&
  668. Info.EvalStatus.Diag->empty() &&
  669. !Info.EvalStatus.HasSideEffects),
  670. OldMode(Info.EvalMode) {
  671. if (Enabled &&
  672. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  673. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  674. Info.EvalMode = EvalInfo::EM_ConstantFold;
  675. }
  676. void keepDiagnostics() { Enabled = false; }
  677. ~FoldConstant() {
  678. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  679. !Info.EvalStatus.HasSideEffects)
  680. Info.EvalStatus.Diag->clear();
  681. Info.EvalMode = OldMode;
  682. }
  683. };
  684. /// RAII object used to suppress diagnostics and side-effects from a
  685. /// speculative evaluation.
  686. class SpeculativeEvaluationRAII {
  687. EvalInfo &Info;
  688. Expr::EvalStatus Old;
  689. public:
  690. SpeculativeEvaluationRAII(EvalInfo &Info,
  691. SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  692. : Info(Info), Old(Info.EvalStatus) {
  693. Info.EvalStatus.Diag = NewDiag;
  694. // If we're speculatively evaluating, we may have skipped over some
  695. // evaluations and missed out a side effect.
  696. Info.EvalStatus.HasSideEffects = true;
  697. }
  698. ~SpeculativeEvaluationRAII() {
  699. Info.EvalStatus = Old;
  700. }
  701. };
  702. /// RAII object wrapping a full-expression or block scope, and handling
  703. /// the ending of the lifetime of temporaries created within it.
  704. template<bool IsFullExpression>
  705. class ScopeRAII {
  706. EvalInfo &Info;
  707. unsigned OldStackSize;
  708. public:
  709. ScopeRAII(EvalInfo &Info)
  710. : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
  711. ~ScopeRAII() {
  712. // Body moved to a static method to encourage the compiler to inline away
  713. // instances of this class.
  714. cleanup(Info, OldStackSize);
  715. }
  716. private:
  717. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  718. unsigned NewEnd = OldStackSize;
  719. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  720. I != N; ++I) {
  721. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  722. // Full-expression cleanup of a lifetime-extended temporary: nothing
  723. // to do, just move this cleanup to the right place in the stack.
  724. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  725. ++NewEnd;
  726. } else {
  727. // End the lifetime of the object.
  728. Info.CleanupStack[I].endLifetime();
  729. }
  730. }
  731. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  732. Info.CleanupStack.end());
  733. }
  734. };
  735. typedef ScopeRAII<false> BlockScopeRAII;
  736. typedef ScopeRAII<true> FullExpressionRAII;
  737. }
  738. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  739. CheckSubobjectKind CSK) {
  740. if (Invalid)
  741. return false;
  742. if (isOnePastTheEnd()) {
  743. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  744. << CSK;
  745. setInvalid();
  746. return false;
  747. }
  748. return true;
  749. }
  750. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  751. const Expr *E, uint64_t N) {
  752. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
  753. Info.CCEDiag(E, diag::note_constexpr_array_index)
  754. << static_cast<int>(N) << /*array*/ 0
  755. << static_cast<unsigned>(MostDerivedArraySize);
  756. else
  757. Info.CCEDiag(E, diag::note_constexpr_array_index)
  758. << static_cast<int>(N) << /*non-array*/ 1;
  759. setInvalid();
  760. }
  761. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  762. const FunctionDecl *Callee, const LValue *This,
  763. APValue *Arguments)
  764. : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
  765. Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
  766. Info.CurrentCall = this;
  767. ++Info.CallStackDepth;
  768. }
  769. CallStackFrame::~CallStackFrame() {
  770. assert(Info.CurrentCall == this && "calls retired out of order");
  771. --Info.CallStackDepth;
  772. Info.CurrentCall = Caller;
  773. }
  774. APValue &CallStackFrame::createTemporary(const void *Key,
  775. bool IsLifetimeExtended) {
  776. APValue &Result = Temporaries[Key];
  777. assert(Result.isUninit() && "temporary created multiple times");
  778. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  779. return Result;
  780. }
  781. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  782. void EvalInfo::addCallStack(unsigned Limit) {
  783. // Determine which calls to skip, if any.
  784. unsigned ActiveCalls = CallStackDepth - 1;
  785. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  786. if (Limit && Limit < ActiveCalls) {
  787. SkipStart = Limit / 2 + Limit % 2;
  788. SkipEnd = ActiveCalls - Limit / 2;
  789. }
  790. // Walk the call stack and add the diagnostics.
  791. unsigned CallIdx = 0;
  792. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  793. Frame = Frame->Caller, ++CallIdx) {
  794. // Skip this call?
  795. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  796. if (CallIdx == SkipStart) {
  797. // Note that we're skipping calls.
  798. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  799. << unsigned(ActiveCalls - Limit);
  800. }
  801. continue;
  802. }
  803. SmallVector<char, 128> Buffer;
  804. llvm::raw_svector_ostream Out(Buffer);
  805. describeCall(Frame, Out);
  806. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  807. }
  808. }
  809. namespace {
  810. struct ComplexValue {
  811. private:
  812. bool IsInt;
  813. public:
  814. APSInt IntReal, IntImag;
  815. APFloat FloatReal, FloatImag;
  816. ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
  817. void makeComplexFloat() { IsInt = false; }
  818. bool isComplexFloat() const { return !IsInt; }
  819. APFloat &getComplexFloatReal() { return FloatReal; }
  820. APFloat &getComplexFloatImag() { return FloatImag; }
  821. void makeComplexInt() { IsInt = true; }
  822. bool isComplexInt() const { return IsInt; }
  823. APSInt &getComplexIntReal() { return IntReal; }
  824. APSInt &getComplexIntImag() { return IntImag; }
  825. void moveInto(APValue &v) const {
  826. if (isComplexFloat())
  827. v = APValue(FloatReal, FloatImag);
  828. else
  829. v = APValue(IntReal, IntImag);
  830. }
  831. void setFrom(const APValue &v) {
  832. assert(v.isComplexFloat() || v.isComplexInt());
  833. if (v.isComplexFloat()) {
  834. makeComplexFloat();
  835. FloatReal = v.getComplexFloatReal();
  836. FloatImag = v.getComplexFloatImag();
  837. } else {
  838. makeComplexInt();
  839. IntReal = v.getComplexIntReal();
  840. IntImag = v.getComplexIntImag();
  841. }
  842. }
  843. };
  844. struct LValue {
  845. APValue::LValueBase Base;
  846. CharUnits Offset;
  847. unsigned CallIndex;
  848. SubobjectDesignator Designator;
  849. const APValue::LValueBase getLValueBase() const { return Base; }
  850. CharUnits &getLValueOffset() { return Offset; }
  851. const CharUnits &getLValueOffset() const { return Offset; }
  852. unsigned getLValueCallIndex() const { return CallIndex; }
  853. SubobjectDesignator &getLValueDesignator() { return Designator; }
  854. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  855. void moveInto(APValue &V) const {
  856. if (Designator.Invalid)
  857. V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
  858. else
  859. V = APValue(Base, Offset, Designator.Entries,
  860. Designator.IsOnePastTheEnd, CallIndex);
  861. }
  862. void setFrom(ASTContext &Ctx, const APValue &V) {
  863. assert(V.isLValue());
  864. Base = V.getLValueBase();
  865. Offset = V.getLValueOffset();
  866. CallIndex = V.getLValueCallIndex();
  867. Designator = SubobjectDesignator(Ctx, V);
  868. }
  869. void set(APValue::LValueBase B, unsigned I = 0) {
  870. Base = B;
  871. Offset = CharUnits::Zero();
  872. CallIndex = I;
  873. Designator = SubobjectDesignator(getType(B));
  874. }
  875. // Check that this LValue is not based on a null pointer. If it is, produce
  876. // a diagnostic and mark the designator as invalid.
  877. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  878. CheckSubobjectKind CSK) {
  879. if (Designator.Invalid)
  880. return false;
  881. if (!Base) {
  882. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  883. << CSK;
  884. Designator.setInvalid();
  885. return false;
  886. }
  887. return true;
  888. }
  889. // Check this LValue refers to an object. If not, set the designator to be
  890. // invalid and emit a diagnostic.
  891. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  892. // Outside C++11, do not build a designator referring to a subobject of
  893. // any object: we won't use such a designator for anything.
  894. if (!Info.getLangOpts().CPlusPlus11)
  895. Designator.setInvalid();
  896. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  897. Designator.checkSubobject(Info, E, CSK);
  898. }
  899. void addDecl(EvalInfo &Info, const Expr *E,
  900. const Decl *D, bool Virtual = false) {
  901. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  902. Designator.addDeclUnchecked(D, Virtual);
  903. }
  904. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  905. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  906. Designator.addArrayUnchecked(CAT);
  907. }
  908. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  909. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  910. Designator.addComplexUnchecked(EltTy, Imag);
  911. }
  912. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  913. if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
  914. Designator.adjustIndex(Info, E, N);
  915. }
  916. };
  917. struct MemberPtr {
  918. MemberPtr() {}
  919. explicit MemberPtr(const ValueDecl *Decl) :
  920. DeclAndIsDerivedMember(Decl, false), Path() {}
  921. /// The member or (direct or indirect) field referred to by this member
  922. /// pointer, or 0 if this is a null member pointer.
  923. const ValueDecl *getDecl() const {
  924. return DeclAndIsDerivedMember.getPointer();
  925. }
  926. /// Is this actually a member of some type derived from the relevant class?
  927. bool isDerivedMember() const {
  928. return DeclAndIsDerivedMember.getInt();
  929. }
  930. /// Get the class which the declaration actually lives in.
  931. const CXXRecordDecl *getContainingRecord() const {
  932. return cast<CXXRecordDecl>(
  933. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  934. }
  935. void moveInto(APValue &V) const {
  936. V = APValue(getDecl(), isDerivedMember(), Path);
  937. }
  938. void setFrom(const APValue &V) {
  939. assert(V.isMemberPointer());
  940. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  941. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  942. Path.clear();
  943. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  944. Path.insert(Path.end(), P.begin(), P.end());
  945. }
  946. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  947. /// whether the member is a member of some class derived from the class type
  948. /// of the member pointer.
  949. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  950. /// Path - The path of base/derived classes from the member declaration's
  951. /// class (exclusive) to the class type of the member pointer (inclusive).
  952. SmallVector<const CXXRecordDecl*, 4> Path;
  953. /// Perform a cast towards the class of the Decl (either up or down the
  954. /// hierarchy).
  955. bool castBack(const CXXRecordDecl *Class) {
  956. assert(!Path.empty());
  957. const CXXRecordDecl *Expected;
  958. if (Path.size() >= 2)
  959. Expected = Path[Path.size() - 2];
  960. else
  961. Expected = getContainingRecord();
  962. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  963. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  964. // if B does not contain the original member and is not a base or
  965. // derived class of the class containing the original member, the result
  966. // of the cast is undefined.
  967. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  968. // (D::*). We consider that to be a language defect.
  969. return false;
  970. }
  971. Path.pop_back();
  972. return true;
  973. }
  974. /// Perform a base-to-derived member pointer cast.
  975. bool castToDerived(const CXXRecordDecl *Derived) {
  976. if (!getDecl())
  977. return true;
  978. if (!isDerivedMember()) {
  979. Path.push_back(Derived);
  980. return true;
  981. }
  982. if (!castBack(Derived))
  983. return false;
  984. if (Path.empty())
  985. DeclAndIsDerivedMember.setInt(false);
  986. return true;
  987. }
  988. /// Perform a derived-to-base member pointer cast.
  989. bool castToBase(const CXXRecordDecl *Base) {
  990. if (!getDecl())
  991. return true;
  992. if (Path.empty())
  993. DeclAndIsDerivedMember.setInt(true);
  994. if (isDerivedMember()) {
  995. Path.push_back(Base);
  996. return true;
  997. }
  998. return castBack(Base);
  999. }
  1000. };
  1001. /// Compare two member pointers, which are assumed to be of the same type.
  1002. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1003. if (!LHS.getDecl() || !RHS.getDecl())
  1004. return !LHS.getDecl() && !RHS.getDecl();
  1005. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1006. return false;
  1007. return LHS.Path == RHS.Path;
  1008. }
  1009. }
  1010. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1011. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1012. const LValue &This, const Expr *E,
  1013. bool AllowNonLiteralTypes = false);
  1014. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
  1015. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
  1016. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1017. EvalInfo &Info);
  1018. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1019. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1020. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1021. EvalInfo &Info);
  1022. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1023. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1024. static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
  1025. //===----------------------------------------------------------------------===//
  1026. // Misc utilities
  1027. //===----------------------------------------------------------------------===//
  1028. /// Produce a string describing the given constexpr call.
  1029. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1030. unsigned ArgIndex = 0;
  1031. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1032. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1033. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1034. if (!IsMemberCall)
  1035. Out << *Frame->Callee << '(';
  1036. if (Frame->This && IsMemberCall) {
  1037. APValue Val;
  1038. Frame->This->moveInto(Val);
  1039. Val.printPretty(Out, Frame->Info.Ctx,
  1040. Frame->This->Designator.MostDerivedType);
  1041. // FIXME: Add parens around Val if needed.
  1042. Out << "->" << *Frame->Callee << '(';
  1043. IsMemberCall = false;
  1044. }
  1045. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1046. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1047. if (ArgIndex > (unsigned)IsMemberCall)
  1048. Out << ", ";
  1049. const ParmVarDecl *Param = *I;
  1050. const APValue &Arg = Frame->Arguments[ArgIndex];
  1051. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1052. if (ArgIndex == 0 && IsMemberCall)
  1053. Out << "->" << *Frame->Callee << '(';
  1054. }
  1055. Out << ')';
  1056. }
  1057. /// Evaluate an expression to see if it had side-effects, and discard its
  1058. /// result.
  1059. /// \return \c true if the caller should keep evaluating.
  1060. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1061. APValue Scratch;
  1062. if (!Evaluate(Scratch, Info, E))
  1063. // We don't need the value, but we might have skipped a side effect here.
  1064. return Info.noteSideEffect();
  1065. return true;
  1066. }
  1067. /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
  1068. /// return its existing value.
  1069. static int64_t getExtValue(const APSInt &Value) {
  1070. return Value.isSigned() ? Value.getSExtValue()
  1071. : static_cast<int64_t>(Value.getZExtValue());
  1072. }
  1073. /// Should this call expression be treated as a string literal?
  1074. static bool IsStringLiteralCall(const CallExpr *E) {
  1075. unsigned Builtin = E->getBuiltinCallee();
  1076. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1077. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1078. }
  1079. static bool IsGlobalLValue(APValue::LValueBase B) {
  1080. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1081. // constant expression of pointer type that evaluates to...
  1082. // ... a null pointer value, or a prvalue core constant expression of type
  1083. // std::nullptr_t.
  1084. if (!B) return true;
  1085. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1086. // ... the address of an object with static storage duration,
  1087. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1088. return VD->hasGlobalStorage();
  1089. // ... the address of a function,
  1090. return isa<FunctionDecl>(D);
  1091. }
  1092. const Expr *E = B.get<const Expr*>();
  1093. switch (E->getStmtClass()) {
  1094. default:
  1095. return false;
  1096. case Expr::CompoundLiteralExprClass: {
  1097. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1098. return CLE->isFileScope() && CLE->isLValue();
  1099. }
  1100. case Expr::MaterializeTemporaryExprClass:
  1101. // A materialized temporary might have been lifetime-extended to static
  1102. // storage duration.
  1103. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1104. // A string literal has static storage duration.
  1105. case Expr::StringLiteralClass:
  1106. case Expr::PredefinedExprClass:
  1107. case Expr::ObjCStringLiteralClass:
  1108. case Expr::ObjCEncodeExprClass:
  1109. case Expr::CXXTypeidExprClass:
  1110. case Expr::CXXUuidofExprClass:
  1111. return true;
  1112. case Expr::CallExprClass:
  1113. return IsStringLiteralCall(cast<CallExpr>(E));
  1114. // For GCC compatibility, &&label has static storage duration.
  1115. case Expr::AddrLabelExprClass:
  1116. return true;
  1117. // A Block literal expression may be used as the initialization value for
  1118. // Block variables at global or local static scope.
  1119. case Expr::BlockExprClass:
  1120. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1121. case Expr::ImplicitValueInitExprClass:
  1122. // FIXME:
  1123. // We can never form an lvalue with an implicit value initialization as its
  1124. // base through expression evaluation, so these only appear in one case: the
  1125. // implicit variable declaration we invent when checking whether a constexpr
  1126. // constructor can produce a constant expression. We must assume that such
  1127. // an expression might be a global lvalue.
  1128. return true;
  1129. }
  1130. }
  1131. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1132. assert(Base && "no location for a null lvalue");
  1133. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1134. if (VD)
  1135. Info.Note(VD->getLocation(), diag::note_declared_at);
  1136. else
  1137. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1138. diag::note_constexpr_temporary_here);
  1139. }
  1140. /// Check that this reference or pointer core constant expression is a valid
  1141. /// value for an address or reference constant expression. Return true if we
  1142. /// can fold this expression, whether or not it's a constant expression.
  1143. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1144. QualType Type, const LValue &LVal) {
  1145. bool IsReferenceType = Type->isReferenceType();
  1146. APValue::LValueBase Base = LVal.getLValueBase();
  1147. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1148. // Check that the object is a global. Note that the fake 'this' object we
  1149. // manufacture when checking potential constant expressions is conservatively
  1150. // assumed to be global here.
  1151. if (!IsGlobalLValue(Base)) {
  1152. if (Info.getLangOpts().CPlusPlus11) {
  1153. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1154. Info.Diag(Loc, diag::note_constexpr_non_global, 1)
  1155. << IsReferenceType << !Designator.Entries.empty()
  1156. << !!VD << VD;
  1157. NoteLValueLocation(Info, Base);
  1158. } else {
  1159. Info.Diag(Loc);
  1160. }
  1161. // Don't allow references to temporaries to escape.
  1162. return false;
  1163. }
  1164. assert((Info.checkingPotentialConstantExpression() ||
  1165. LVal.getLValueCallIndex() == 0) &&
  1166. "have call index for global lvalue");
  1167. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1168. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1169. // Check if this is a thread-local variable.
  1170. if (Var->getTLSKind())
  1171. return false;
  1172. // A dllimport variable never acts like a constant.
  1173. if (Var->hasAttr<DLLImportAttr>())
  1174. return false;
  1175. }
  1176. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1177. // __declspec(dllimport) must be handled very carefully:
  1178. // We must never initialize an expression with the thunk in C++.
  1179. // Doing otherwise would allow the same id-expression to yield
  1180. // different addresses for the same function in different translation
  1181. // units. However, this means that we must dynamically initialize the
  1182. // expression with the contents of the import address table at runtime.
  1183. //
  1184. // The C language has no notion of ODR; furthermore, it has no notion of
  1185. // dynamic initialization. This means that we are permitted to
  1186. // perform initialization with the address of the thunk.
  1187. if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
  1188. return false;
  1189. }
  1190. }
  1191. // Allow address constant expressions to be past-the-end pointers. This is
  1192. // an extension: the standard requires them to point to an object.
  1193. if (!IsReferenceType)
  1194. return true;
  1195. // A reference constant expression must refer to an object.
  1196. if (!Base) {
  1197. // FIXME: diagnostic
  1198. Info.CCEDiag(Loc);
  1199. return true;
  1200. }
  1201. // Does this refer one past the end of some object?
  1202. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1203. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1204. Info.Diag(Loc, diag::note_constexpr_past_end, 1)
  1205. << !Designator.Entries.empty() << !!VD << VD;
  1206. NoteLValueLocation(Info, Base);
  1207. }
  1208. return true;
  1209. }
  1210. /// Check that this core constant expression is of literal type, and if not,
  1211. /// produce an appropriate diagnostic.
  1212. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1213. const LValue *This = nullptr) {
  1214. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1215. return true;
  1216. // C++1y: A constant initializer for an object o [...] may also invoke
  1217. // constexpr constructors for o and its subobjects even if those objects
  1218. // are of non-literal class types.
  1219. if (Info.getLangOpts().CPlusPlus14 && This &&
  1220. Info.EvaluatingDecl == This->getLValueBase())
  1221. return true;
  1222. // Prvalue constant expressions must be of literal types.
  1223. if (Info.getLangOpts().CPlusPlus11)
  1224. Info.Diag(E, diag::note_constexpr_nonliteral)
  1225. << E->getType();
  1226. else
  1227. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1228. return false;
  1229. }
  1230. /// Check that this core constant expression value is a valid value for a
  1231. /// constant expression. If not, report an appropriate diagnostic. Does not
  1232. /// check that the expression is of literal type.
  1233. static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
  1234. QualType Type, const APValue &Value) {
  1235. if (Value.isUninit()) {
  1236. Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
  1237. << true << Type;
  1238. return false;
  1239. }
  1240. // We allow _Atomic(T) to be initialized from anything that T can be
  1241. // initialized from.
  1242. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1243. Type = AT->getValueType();
  1244. // Core issue 1454: For a literal constant expression of array or class type,
  1245. // each subobject of its value shall have been initialized by a constant
  1246. // expression.
  1247. if (Value.isArray()) {
  1248. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1249. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1250. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1251. Value.getArrayInitializedElt(I)))
  1252. return false;
  1253. }
  1254. if (!Value.hasArrayFiller())
  1255. return true;
  1256. return CheckConstantExpression(Info, DiagLoc, EltTy,
  1257. Value.getArrayFiller());
  1258. }
  1259. if (Value.isUnion() && Value.getUnionField()) {
  1260. return CheckConstantExpression(Info, DiagLoc,
  1261. Value.getUnionField()->getType(),
  1262. Value.getUnionValue());
  1263. }
  1264. if (Value.isStruct()) {
  1265. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1266. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1267. unsigned BaseIndex = 0;
  1268. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  1269. End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
  1270. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1271. Value.getStructBase(BaseIndex)))
  1272. return false;
  1273. }
  1274. }
  1275. for (const auto *I : RD->fields()) {
  1276. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1277. Value.getStructField(I->getFieldIndex())))
  1278. return false;
  1279. }
  1280. }
  1281. if (Value.isLValue()) {
  1282. LValue LVal;
  1283. LVal.setFrom(Info.Ctx, Value);
  1284. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
  1285. }
  1286. // Everything else is fine.
  1287. return true;
  1288. }
  1289. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1290. return LVal.Base.dyn_cast<const ValueDecl*>();
  1291. }
  1292. static bool IsLiteralLValue(const LValue &Value) {
  1293. if (Value.CallIndex)
  1294. return false;
  1295. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1296. return E && !isa<MaterializeTemporaryExpr>(E);
  1297. }
  1298. static bool IsWeakLValue(const LValue &Value) {
  1299. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1300. return Decl && Decl->isWeak();
  1301. }
  1302. static bool isZeroSized(const LValue &Value) {
  1303. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1304. if (Decl && isa<VarDecl>(Decl)) {
  1305. QualType Ty = Decl->getType();
  1306. if (Ty->isArrayType())
  1307. return Ty->isIncompleteType() ||
  1308. Decl->getASTContext().getTypeSize(Ty) == 0;
  1309. }
  1310. return false;
  1311. }
  1312. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1313. // A null base expression indicates a null pointer. These are always
  1314. // evaluatable, and they are false unless the offset is zero.
  1315. if (!Value.getLValueBase()) {
  1316. Result = !Value.getLValueOffset().isZero();
  1317. return true;
  1318. }
  1319. // We have a non-null base. These are generally known to be true, but if it's
  1320. // a weak declaration it can be null at runtime.
  1321. Result = true;
  1322. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1323. return !Decl || !Decl->isWeak();
  1324. }
  1325. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1326. switch (Val.getKind()) {
  1327. case APValue::Uninitialized:
  1328. return false;
  1329. case APValue::Int:
  1330. Result = Val.getInt().getBoolValue();
  1331. return true;
  1332. case APValue::Float:
  1333. Result = !Val.getFloat().isZero();
  1334. return true;
  1335. case APValue::ComplexInt:
  1336. Result = Val.getComplexIntReal().getBoolValue() ||
  1337. Val.getComplexIntImag().getBoolValue();
  1338. return true;
  1339. case APValue::ComplexFloat:
  1340. Result = !Val.getComplexFloatReal().isZero() ||
  1341. !Val.getComplexFloatImag().isZero();
  1342. return true;
  1343. case APValue::LValue:
  1344. return EvalPointerValueAsBool(Val, Result);
  1345. case APValue::MemberPointer:
  1346. Result = Val.getMemberPointerDecl();
  1347. return true;
  1348. case APValue::Vector:
  1349. case APValue::Array:
  1350. case APValue::Struct:
  1351. case APValue::Union:
  1352. case APValue::AddrLabelDiff:
  1353. return false;
  1354. }
  1355. llvm_unreachable("unknown APValue kind");
  1356. }
  1357. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1358. EvalInfo &Info) {
  1359. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1360. APValue Val;
  1361. if (!Evaluate(Val, Info, E))
  1362. return false;
  1363. return HandleConversionToBool(Val, Result);
  1364. }
  1365. template<typename T>
  1366. static void HandleOverflow(EvalInfo &Info, const Expr *E,
  1367. const T &SrcValue, QualType DestType) {
  1368. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1369. << SrcValue << DestType;
  1370. }
  1371. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1372. QualType SrcType, const APFloat &Value,
  1373. QualType DestType, APSInt &Result) {
  1374. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1375. // Determine whether we are converting to unsigned or signed.
  1376. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1377. Result = APSInt(DestWidth, !DestSigned);
  1378. bool ignored;
  1379. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1380. & APFloat::opInvalidOp)
  1381. HandleOverflow(Info, E, Value, DestType);
  1382. return true;
  1383. }
  1384. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1385. QualType SrcType, QualType DestType,
  1386. APFloat &Result) {
  1387. APFloat Value = Result;
  1388. bool ignored;
  1389. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1390. APFloat::rmNearestTiesToEven, &ignored)
  1391. & APFloat::opOverflow)
  1392. HandleOverflow(Info, E, Value, DestType);
  1393. return true;
  1394. }
  1395. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1396. QualType DestType, QualType SrcType,
  1397. APSInt &Value) {
  1398. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1399. APSInt Result = Value;
  1400. // Figure out if this is a truncate, extend or noop cast.
  1401. // If the input is signed, do a sign extend, noop, or truncate.
  1402. Result = Result.extOrTrunc(DestWidth);
  1403. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1404. return Result;
  1405. }
  1406. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1407. QualType SrcType, const APSInt &Value,
  1408. QualType DestType, APFloat &Result) {
  1409. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1410. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1411. APFloat::rmNearestTiesToEven)
  1412. & APFloat::opOverflow)
  1413. HandleOverflow(Info, E, Value, DestType);
  1414. return true;
  1415. }
  1416. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1417. APValue &Value, const FieldDecl *FD) {
  1418. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1419. if (!Value.isInt()) {
  1420. // Trying to store a pointer-cast-to-integer into a bitfield.
  1421. // FIXME: In this case, we should provide the diagnostic for casting
  1422. // a pointer to an integer.
  1423. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1424. Info.Diag(E);
  1425. return false;
  1426. }
  1427. APSInt &Int = Value.getInt();
  1428. unsigned OldBitWidth = Int.getBitWidth();
  1429. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1430. if (NewBitWidth < OldBitWidth)
  1431. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1432. return true;
  1433. }
  1434. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1435. llvm::APInt &Res) {
  1436. APValue SVal;
  1437. if (!Evaluate(SVal, Info, E))
  1438. return false;
  1439. if (SVal.isInt()) {
  1440. Res = SVal.getInt();
  1441. return true;
  1442. }
  1443. if (SVal.isFloat()) {
  1444. Res = SVal.getFloat().bitcastToAPInt();
  1445. return true;
  1446. }
  1447. if (SVal.isVector()) {
  1448. QualType VecTy = E->getType();
  1449. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1450. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1451. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1452. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1453. Res = llvm::APInt::getNullValue(VecSize);
  1454. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1455. APValue &Elt = SVal.getVectorElt(i);
  1456. llvm::APInt EltAsInt;
  1457. if (Elt.isInt()) {
  1458. EltAsInt = Elt.getInt();
  1459. } else if (Elt.isFloat()) {
  1460. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1461. } else {
  1462. // Don't try to handle vectors of anything other than int or float
  1463. // (not sure if it's possible to hit this case).
  1464. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1465. return false;
  1466. }
  1467. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1468. if (BigEndian)
  1469. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1470. else
  1471. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1472. }
  1473. return true;
  1474. }
  1475. // Give up if the input isn't an int, float, or vector. For example, we
  1476. // reject "(v4i16)(intptr_t)&a".
  1477. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1478. return false;
  1479. }
  1480. /// Perform the given integer operation, which is known to need at most BitWidth
  1481. /// bits, and check for overflow in the original type (if that type was not an
  1482. /// unsigned type).
  1483. template<typename Operation>
  1484. static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1485. const APSInt &LHS, const APSInt &RHS,
  1486. unsigned BitWidth, Operation Op) {
  1487. if (LHS.isUnsigned())
  1488. return Op(LHS, RHS);
  1489. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1490. APSInt Result = Value.trunc(LHS.getBitWidth());
  1491. if (Result.extend(BitWidth) != Value) {
  1492. if (Info.checkingForOverflow())
  1493. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1494. diag::warn_integer_constant_overflow)
  1495. << Result.toString(10) << E->getType();
  1496. else
  1497. HandleOverflow(Info, E, Value, E->getType());
  1498. }
  1499. return Result;
  1500. }
  1501. /// Perform the given binary integer operation.
  1502. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1503. BinaryOperatorKind Opcode, APSInt RHS,
  1504. APSInt &Result) {
  1505. switch (Opcode) {
  1506. default:
  1507. Info.Diag(E);
  1508. return false;
  1509. case BO_Mul:
  1510. Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1511. std::multiplies<APSInt>());
  1512. return true;
  1513. case BO_Add:
  1514. Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1515. std::plus<APSInt>());
  1516. return true;
  1517. case BO_Sub:
  1518. Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1519. std::minus<APSInt>());
  1520. return true;
  1521. case BO_And: Result = LHS & RHS; return true;
  1522. case BO_Xor: Result = LHS ^ RHS; return true;
  1523. case BO_Or: Result = LHS | RHS; return true;
  1524. case BO_Div:
  1525. case BO_Rem:
  1526. if (RHS == 0) {
  1527. Info.Diag(E, diag::note_expr_divide_by_zero);
  1528. return false;
  1529. }
  1530. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
  1531. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1532. LHS.isSigned() && LHS.isMinSignedValue())
  1533. HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
  1534. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1535. return true;
  1536. case BO_Shl: {
  1537. if (Info.getLangOpts().OpenCL)
  1538. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1539. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1540. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1541. RHS.isUnsigned());
  1542. else if (RHS.isSigned() && RHS.isNegative()) {
  1543. // During constant-folding, a negative shift is an opposite shift. Such
  1544. // a shift is not a constant expression.
  1545. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1546. RHS = -RHS;
  1547. goto shift_right;
  1548. }
  1549. shift_left:
  1550. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  1551. // the shifted type.
  1552. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1553. if (SA != RHS) {
  1554. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1555. << RHS << E->getType() << LHS.getBitWidth();
  1556. } else if (LHS.isSigned()) {
  1557. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  1558. // operand, and must not overflow the corresponding unsigned type.
  1559. if (LHS.isNegative())
  1560. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  1561. else if (LHS.countLeadingZeros() < SA)
  1562. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  1563. }
  1564. Result = LHS << SA;
  1565. return true;
  1566. }
  1567. case BO_Shr: {
  1568. if (Info.getLangOpts().OpenCL)
  1569. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1570. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1571. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1572. RHS.isUnsigned());
  1573. else if (RHS.isSigned() && RHS.isNegative()) {
  1574. // During constant-folding, a negative shift is an opposite shift. Such a
  1575. // shift is not a constant expression.
  1576. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1577. RHS = -RHS;
  1578. goto shift_left;
  1579. }
  1580. shift_right:
  1581. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  1582. // shifted type.
  1583. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1584. if (SA != RHS)
  1585. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1586. << RHS << E->getType() << LHS.getBitWidth();
  1587. Result = LHS >> SA;
  1588. return true;
  1589. }
  1590. case BO_LT: Result = LHS < RHS; return true;
  1591. case BO_GT: Result = LHS > RHS; return true;
  1592. case BO_LE: Result = LHS <= RHS; return true;
  1593. case BO_GE: Result = LHS >= RHS; return true;
  1594. case BO_EQ: Result = LHS == RHS; return true;
  1595. case BO_NE: Result = LHS != RHS; return true;
  1596. }
  1597. }
  1598. /// Perform the given binary floating-point operation, in-place, on LHS.
  1599. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  1600. APFloat &LHS, BinaryOperatorKind Opcode,
  1601. const APFloat &RHS) {
  1602. switch (Opcode) {
  1603. default:
  1604. Info.Diag(E);
  1605. return false;
  1606. case BO_Mul:
  1607. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  1608. break;
  1609. case BO_Add:
  1610. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  1611. break;
  1612. case BO_Sub:
  1613. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  1614. break;
  1615. case BO_Div:
  1616. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  1617. break;
  1618. }
  1619. if (LHS.isInfinity() || LHS.isNaN())
  1620. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  1621. return true;
  1622. }
  1623. /// Cast an lvalue referring to a base subobject to a derived class, by
  1624. /// truncating the lvalue's path to the given length.
  1625. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  1626. const RecordDecl *TruncatedType,
  1627. unsigned TruncatedElements) {
  1628. SubobjectDesignator &D = Result.Designator;
  1629. // Check we actually point to a derived class object.
  1630. if (TruncatedElements == D.Entries.size())
  1631. return true;
  1632. assert(TruncatedElements >= D.MostDerivedPathLength &&
  1633. "not casting to a derived class");
  1634. if (!Result.checkSubobject(Info, E, CSK_Derived))
  1635. return false;
  1636. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  1637. const RecordDecl *RD = TruncatedType;
  1638. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  1639. if (RD->isInvalidDecl()) return false;
  1640. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1641. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  1642. if (isVirtualBaseClass(D.Entries[I]))
  1643. Result.Offset -= Layout.getVBaseClassOffset(Base);
  1644. else
  1645. Result.Offset -= Layout.getBaseClassOffset(Base);
  1646. RD = Base;
  1647. }
  1648. D.Entries.resize(TruncatedElements);
  1649. return true;
  1650. }
  1651. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1652. const CXXRecordDecl *Derived,
  1653. const CXXRecordDecl *Base,
  1654. const ASTRecordLayout *RL = nullptr) {
  1655. if (!RL) {
  1656. if (Derived->isInvalidDecl()) return false;
  1657. RL = &Info.Ctx.getASTRecordLayout(Derived);
  1658. }
  1659. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  1660. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  1661. return true;
  1662. }
  1663. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1664. const CXXRecordDecl *DerivedDecl,
  1665. const CXXBaseSpecifier *Base) {
  1666. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  1667. if (!Base->isVirtual())
  1668. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  1669. SubobjectDesignator &D = Obj.Designator;
  1670. if (D.Invalid)
  1671. return false;
  1672. // Extract most-derived object and corresponding type.
  1673. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  1674. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  1675. return false;
  1676. // Find the virtual base class.
  1677. if (DerivedDecl->isInvalidDecl()) return false;
  1678. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  1679. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  1680. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  1681. return true;
  1682. }
  1683. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  1684. QualType Type, LValue &Result) {
  1685. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  1686. PathE = E->path_end();
  1687. PathI != PathE; ++PathI) {
  1688. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  1689. *PathI))
  1690. return false;
  1691. Type = (*PathI)->getType();
  1692. }
  1693. return true;
  1694. }
  1695. /// Update LVal to refer to the given field, which must be a member of the type
  1696. /// currently described by LVal.
  1697. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  1698. const FieldDecl *FD,
  1699. const ASTRecordLayout *RL = nullptr) {
  1700. if (!RL) {
  1701. if (FD->getParent()->isInvalidDecl()) return false;
  1702. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  1703. }
  1704. unsigned I = FD->getFieldIndex();
  1705. LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
  1706. LVal.addDecl(Info, E, FD);
  1707. return true;
  1708. }
  1709. /// Update LVal to refer to the given indirect field.
  1710. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  1711. LValue &LVal,
  1712. const IndirectFieldDecl *IFD) {
  1713. for (const auto *C : IFD->chain())
  1714. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  1715. return false;
  1716. return true;
  1717. }
  1718. /// Get the size of the given type in char units.
  1719. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  1720. QualType Type, CharUnits &Size) {
  1721. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  1722. // extension.
  1723. if (Type->isVoidType() || Type->isFunctionType()) {
  1724. Size = CharUnits::One();
  1725. return true;
  1726. }
  1727. if (!Type->isConstantSizeType()) {
  1728. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  1729. // FIXME: Better diagnostic.
  1730. Info.Diag(Loc);
  1731. return false;
  1732. }
  1733. Size = Info.Ctx.getTypeSizeInChars(Type);
  1734. return true;
  1735. }
  1736. /// Update a pointer value to model pointer arithmetic.
  1737. /// \param Info - Information about the ongoing evaluation.
  1738. /// \param E - The expression being evaluated, for diagnostic purposes.
  1739. /// \param LVal - The pointer value to be updated.
  1740. /// \param EltTy - The pointee type represented by LVal.
  1741. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  1742. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  1743. LValue &LVal, QualType EltTy,
  1744. int64_t Adjustment) {
  1745. CharUnits SizeOfPointee;
  1746. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  1747. return false;
  1748. // Compute the new offset in the appropriate width.
  1749. LVal.Offset += Adjustment * SizeOfPointee;
  1750. LVal.adjustIndex(Info, E, Adjustment);
  1751. return true;
  1752. }
  1753. /// Update an lvalue to refer to a component of a complex number.
  1754. /// \param Info - Information about the ongoing evaluation.
  1755. /// \param LVal - The lvalue to be updated.
  1756. /// \param EltTy - The complex number's component type.
  1757. /// \param Imag - False for the real component, true for the imaginary.
  1758. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  1759. LValue &LVal, QualType EltTy,
  1760. bool Imag) {
  1761. if (Imag) {
  1762. CharUnits SizeOfComponent;
  1763. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  1764. return false;
  1765. LVal.Offset += SizeOfComponent;
  1766. }
  1767. LVal.addComplex(Info, E, EltTy, Imag);
  1768. return true;
  1769. }
  1770. /// Try to evaluate the initializer for a variable declaration.
  1771. ///
  1772. /// \param Info Information about the ongoing evaluation.
  1773. /// \param E An expression to be used when printing diagnostics.
  1774. /// \param VD The variable whose initializer should be obtained.
  1775. /// \param Frame The frame in which the variable was created. Must be null
  1776. /// if this variable is not local to the evaluation.
  1777. /// \param Result Filled in with a pointer to the value of the variable.
  1778. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  1779. const VarDecl *VD, CallStackFrame *Frame,
  1780. APValue *&Result) {
  1781. // If this is a parameter to an active constexpr function call, perform
  1782. // argument substitution.
  1783. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  1784. // Assume arguments of a potential constant expression are unknown
  1785. // constant expressions.
  1786. if (Info.checkingPotentialConstantExpression())
  1787. return false;
  1788. if (!Frame || !Frame->Arguments) {
  1789. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1790. return false;
  1791. }
  1792. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  1793. return true;
  1794. }
  1795. // If this is a local variable, dig out its value.
  1796. if (Frame) {
  1797. Result = Frame->getTemporary(VD);
  1798. assert(Result && "missing value for local variable");
  1799. return true;
  1800. }
  1801. // Dig out the initializer, and use the declaration which it's attached to.
  1802. const Expr *Init = VD->getAnyInitializer(VD);
  1803. if (!Init || Init->isValueDependent()) {
  1804. // If we're checking a potential constant expression, the variable could be
  1805. // initialized later.
  1806. if (!Info.checkingPotentialConstantExpression())
  1807. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1808. return false;
  1809. }
  1810. // If we're currently evaluating the initializer of this declaration, use that
  1811. // in-flight value.
  1812. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  1813. Result = Info.EvaluatingDeclValue;
  1814. return true;
  1815. }
  1816. // Never evaluate the initializer of a weak variable. We can't be sure that
  1817. // this is the definition which will be used.
  1818. if (VD->isWeak()) {
  1819. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  1820. return false;
  1821. }
  1822. // HLSL Change Begin - External variable is in cbuffer, cannot use as immediate.
  1823. if (VD->hasExternalFormalLinkage() &&
  1824. !isa<EnumConstantDecl>(VD))
  1825. return false;
  1826. // HLSL Change End.
  1827. // Check that we can fold the initializer. In C++, we will have already done
  1828. // this in the cases where it matters for conformance.
  1829. SmallVector<PartialDiagnosticAt, 8> Notes;
  1830. if (!VD->evaluateValue(Notes)) {
  1831. Info.Diag(E, diag::note_constexpr_var_init_non_constant,
  1832. Notes.size() + 1) << VD;
  1833. Info.Note(VD->getLocation(), diag::note_declared_at);
  1834. Info.addNotes(Notes);
  1835. return false;
  1836. } else if (!VD->checkInitIsICE()) {
  1837. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  1838. Notes.size() + 1) << VD;
  1839. Info.Note(VD->getLocation(), diag::note_declared_at);
  1840. Info.addNotes(Notes);
  1841. }
  1842. Result = VD->getEvaluatedValue();
  1843. return true;
  1844. }
  1845. static bool IsConstNonVolatile(QualType T) {
  1846. Qualifiers Quals = T.getQualifiers();
  1847. return Quals.hasConst() && !Quals.hasVolatile();
  1848. }
  1849. /// Get the base index of the given base class within an APValue representing
  1850. /// the given derived class.
  1851. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  1852. const CXXRecordDecl *Base) {
  1853. Base = Base->getCanonicalDecl();
  1854. unsigned Index = 0;
  1855. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  1856. E = Derived->bases_end(); I != E; ++I, ++Index) {
  1857. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  1858. return Index;
  1859. }
  1860. llvm_unreachable("base class missing from derived class's bases list");
  1861. }
  1862. /// Extract the value of a character from a string literal.
  1863. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  1864. uint64_t Index) {
  1865. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  1866. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  1867. Lit = PE->getFunctionName();
  1868. const StringLiteral *S = cast<StringLiteral>(Lit);
  1869. const ConstantArrayType *CAT =
  1870. Info.Ctx.getAsConstantArrayType(S->getType());
  1871. assert(CAT && "string literal isn't an array");
  1872. QualType CharType = CAT->getElementType();
  1873. assert(CharType->isIntegerType() && "unexpected character type");
  1874. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  1875. CharType->isUnsignedIntegerType());
  1876. if (Index < S->getLength())
  1877. Value = S->getCodeUnit(Index);
  1878. return Value;
  1879. }
  1880. // Expand a string literal into an array of characters.
  1881. static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
  1882. APValue &Result) {
  1883. const StringLiteral *S = cast<StringLiteral>(Lit);
  1884. const ConstantArrayType *CAT =
  1885. Info.Ctx.getAsConstantArrayType(S->getType());
  1886. assert(CAT && "string literal isn't an array");
  1887. QualType CharType = CAT->getElementType();
  1888. assert(CharType->isIntegerType() && "unexpected character type");
  1889. unsigned Elts = CAT->getSize().getZExtValue();
  1890. Result = APValue(APValue::UninitArray(),
  1891. std::min(S->getLength(), Elts), Elts);
  1892. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  1893. CharType->isUnsignedIntegerType());
  1894. if (Result.hasArrayFiller())
  1895. Result.getArrayFiller() = APValue(Value);
  1896. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  1897. Value = S->getCodeUnit(I);
  1898. Result.getArrayInitializedElt(I) = APValue(Value);
  1899. }
  1900. }
  1901. // Expand an array so that it has more than Index filled elements.
  1902. static void expandArray(APValue &Array, unsigned Index) {
  1903. unsigned Size = Array.getArraySize();
  1904. assert(Index < Size);
  1905. // Always at least double the number of elements for which we store a value.
  1906. unsigned OldElts = Array.getArrayInitializedElts();
  1907. unsigned NewElts = std::max(Index+1, OldElts * 2);
  1908. NewElts = std::min(Size, std::max(NewElts, 8u));
  1909. // Copy the data across.
  1910. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  1911. for (unsigned I = 0; I != OldElts; ++I)
  1912. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  1913. for (unsigned I = OldElts; I != NewElts; ++I)
  1914. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  1915. if (NewValue.hasArrayFiller())
  1916. NewValue.getArrayFiller() = Array.getArrayFiller();
  1917. Array.swap(NewValue);
  1918. }
  1919. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  1920. /// conversion. If it's of class type, we may assume that the copy operation
  1921. /// is trivial. Note that this is never true for a union type with fields
  1922. /// (because the copy always "reads" the active member) and always true for
  1923. /// a non-class type.
  1924. static bool isReadByLvalueToRvalueConversion(QualType T) {
  1925. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1926. if (!RD || (RD->isUnion() && !RD->field_empty()))
  1927. return true;
  1928. if (RD->isEmpty())
  1929. return false;
  1930. for (auto *Field : RD->fields())
  1931. if (isReadByLvalueToRvalueConversion(Field->getType()))
  1932. return true;
  1933. for (auto &BaseSpec : RD->bases())
  1934. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  1935. return true;
  1936. return false;
  1937. }
  1938. /// Diagnose an attempt to read from any unreadable field within the specified
  1939. /// type, which might be a class type.
  1940. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  1941. QualType T) {
  1942. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1943. if (!RD)
  1944. return false;
  1945. if (!RD->hasMutableFields())
  1946. return false;
  1947. for (auto *Field : RD->fields()) {
  1948. // If we're actually going to read this field in some way, then it can't
  1949. // be mutable. If we're in a union, then assigning to a mutable field
  1950. // (even an empty one) can change the active member, so that's not OK.
  1951. // FIXME: Add core issue number for the union case.
  1952. if (Field->isMutable() &&
  1953. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  1954. Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  1955. Info.Note(Field->getLocation(), diag::note_declared_at);
  1956. return true;
  1957. }
  1958. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  1959. return true;
  1960. }
  1961. for (auto &BaseSpec : RD->bases())
  1962. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  1963. return true;
  1964. // All mutable fields were empty, and thus not actually read.
  1965. return false;
  1966. }
  1967. /// Kinds of access we can perform on an object, for diagnostics.
  1968. enum AccessKinds {
  1969. AK_Read,
  1970. AK_Assign,
  1971. AK_Increment,
  1972. AK_Decrement
  1973. };
  1974. /// A handle to a complete object (an object that is not a subobject of
  1975. /// another object).
  1976. struct CompleteObject {
  1977. /// The value of the complete object.
  1978. APValue *Value;
  1979. /// The type of the complete object.
  1980. QualType Type;
  1981. CompleteObject() : Value(nullptr) {}
  1982. CompleteObject(APValue *Value, QualType Type)
  1983. : Value(Value), Type(Type) {
  1984. assert(Value && "missing value for complete object");
  1985. }
  1986. explicit operator bool() const { return Value; }
  1987. };
  1988. /// Find the designated sub-object of an rvalue.
  1989. template<typename SubobjectHandler>
  1990. typename SubobjectHandler::result_type
  1991. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  1992. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  1993. if (Sub.Invalid)
  1994. // A diagnostic will have already been produced.
  1995. return handler.failed();
  1996. if (Sub.isOnePastTheEnd()) {
  1997. if (Info.getLangOpts().CPlusPlus11)
  1998. Info.Diag(E, diag::note_constexpr_access_past_end)
  1999. << handler.AccessKind;
  2000. else
  2001. Info.Diag(E);
  2002. return handler.failed();
  2003. }
  2004. APValue *O = Obj.Value;
  2005. QualType ObjType = Obj.Type;
  2006. const FieldDecl *LastField = nullptr;
  2007. // Walk the designator's path to find the subobject.
  2008. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2009. if (O->isUninit()) {
  2010. if (!Info.checkingPotentialConstantExpression())
  2011. Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
  2012. return handler.failed();
  2013. }
  2014. if (I == N) {
  2015. // If we are reading an object of class type, there may still be more
  2016. // things we need to check: if there are any mutable subobjects, we
  2017. // cannot perform this read. (This only happens when performing a trivial
  2018. // copy or assignment.)
  2019. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2020. diagnoseUnreadableFields(Info, E, ObjType))
  2021. return handler.failed();
  2022. if (!handler.found(*O, ObjType))
  2023. return false;
  2024. // If we modified a bit-field, truncate it to the right width.
  2025. if (handler.AccessKind != AK_Read &&
  2026. LastField && LastField->isBitField() &&
  2027. !truncateBitfieldValue(Info, E, *O, LastField))
  2028. return false;
  2029. return true;
  2030. }
  2031. LastField = nullptr;
  2032. if (ObjType->isArrayType()) {
  2033. // Next subobject is an array element.
  2034. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2035. assert(CAT && "vla in literal type?");
  2036. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2037. if (CAT->getSize().ule(Index)) {
  2038. // Note, it should not be possible to form a pointer with a valid
  2039. // designator which points more than one past the end of the array.
  2040. if (Info.getLangOpts().CPlusPlus11)
  2041. Info.Diag(E, diag::note_constexpr_access_past_end)
  2042. << handler.AccessKind;
  2043. else
  2044. Info.Diag(E);
  2045. return handler.failed();
  2046. }
  2047. ObjType = CAT->getElementType();
  2048. // An array object is represented as either an Array APValue or as an
  2049. // LValue which refers to a string literal.
  2050. if (O->isLValue()) {
  2051. assert(I == N - 1 && "extracting subobject of character?");
  2052. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  2053. if (handler.AccessKind != AK_Read)
  2054. expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
  2055. *O);
  2056. else
  2057. return handler.foundString(*O, ObjType, Index);
  2058. }
  2059. if (O->getArrayInitializedElts() > Index)
  2060. O = &O->getArrayInitializedElt(Index);
  2061. else if (handler.AccessKind != AK_Read) {
  2062. expandArray(*O, Index);
  2063. O = &O->getArrayInitializedElt(Index);
  2064. } else
  2065. O = &O->getArrayFiller();
  2066. } else if (ObjType->isAnyComplexType()) {
  2067. // Next subobject is a complex number.
  2068. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2069. if (Index > 1) {
  2070. if (Info.getLangOpts().CPlusPlus11)
  2071. Info.Diag(E, diag::note_constexpr_access_past_end)
  2072. << handler.AccessKind;
  2073. else
  2074. Info.Diag(E);
  2075. return handler.failed();
  2076. }
  2077. bool WasConstQualified = ObjType.isConstQualified();
  2078. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2079. if (WasConstQualified)
  2080. ObjType.addConst();
  2081. assert(I == N - 1 && "extracting subobject of scalar?");
  2082. if (O->isComplexInt()) {
  2083. return handler.found(Index ? O->getComplexIntImag()
  2084. : O->getComplexIntReal(), ObjType);
  2085. } else {
  2086. assert(O->isComplexFloat());
  2087. return handler.found(Index ? O->getComplexFloatImag()
  2088. : O->getComplexFloatReal(), ObjType);
  2089. }
  2090. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2091. if (Field->isMutable() && handler.AccessKind == AK_Read) {
  2092. Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
  2093. << Field;
  2094. Info.Note(Field->getLocation(), diag::note_declared_at);
  2095. return handler.failed();
  2096. }
  2097. // Next subobject is a class, struct or union field.
  2098. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2099. if (RD->isUnion()) {
  2100. const FieldDecl *UnionField = O->getUnionField();
  2101. if (!UnionField ||
  2102. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2103. Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
  2104. << handler.AccessKind << Field << !UnionField << UnionField;
  2105. return handler.failed();
  2106. }
  2107. O = &O->getUnionValue();
  2108. } else
  2109. O = &O->getStructField(Field->getFieldIndex());
  2110. bool WasConstQualified = ObjType.isConstQualified();
  2111. ObjType = Field->getType();
  2112. if (WasConstQualified && !Field->isMutable())
  2113. ObjType.addConst();
  2114. if (ObjType.isVolatileQualified()) {
  2115. if (Info.getLangOpts().CPlusPlus) {
  2116. // FIXME: Include a description of the path to the volatile subobject.
  2117. Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
  2118. << handler.AccessKind << 2 << Field;
  2119. Info.Note(Field->getLocation(), diag::note_declared_at);
  2120. } else {
  2121. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  2122. }
  2123. return handler.failed();
  2124. }
  2125. LastField = Field;
  2126. } else {
  2127. // Next subobject is a base class.
  2128. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2129. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2130. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2131. bool WasConstQualified = ObjType.isConstQualified();
  2132. ObjType = Info.Ctx.getRecordType(Base);
  2133. if (WasConstQualified)
  2134. ObjType.addConst();
  2135. }
  2136. }
  2137. }
  2138. namespace {
  2139. struct ExtractSubobjectHandler {
  2140. EvalInfo &Info;
  2141. APValue &Result;
  2142. static const AccessKinds AccessKind = AK_Read;
  2143. typedef bool result_type;
  2144. bool failed() { return false; }
  2145. bool found(APValue &Subobj, QualType SubobjType) {
  2146. Result = Subobj;
  2147. return true;
  2148. }
  2149. bool found(APSInt &Value, QualType SubobjType) {
  2150. Result = APValue(Value);
  2151. return true;
  2152. }
  2153. bool found(APFloat &Value, QualType SubobjType) {
  2154. Result = APValue(Value);
  2155. return true;
  2156. }
  2157. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2158. Result = APValue(extractStringLiteralCharacter(
  2159. Info, Subobj.getLValueBase().get<const Expr *>(), Character));
  2160. return true;
  2161. }
  2162. };
  2163. } // end anonymous namespace
  2164. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2165. /// Extract the designated sub-object of an rvalue.
  2166. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2167. const CompleteObject &Obj,
  2168. const SubobjectDesignator &Sub,
  2169. APValue &Result) {
  2170. ExtractSubobjectHandler Handler = { Info, Result };
  2171. return findSubobject(Info, E, Obj, Sub, Handler);
  2172. }
  2173. namespace {
  2174. struct ModifySubobjectHandler {
  2175. EvalInfo &Info;
  2176. APValue &NewVal;
  2177. const Expr *E;
  2178. typedef bool result_type;
  2179. static const AccessKinds AccessKind = AK_Assign;
  2180. bool checkConst(QualType QT) {
  2181. // Assigning to a const object has undefined behavior.
  2182. if (QT.isConstQualified()) {
  2183. Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
  2184. return false;
  2185. }
  2186. return true;
  2187. }
  2188. bool failed() { return false; }
  2189. bool found(APValue &Subobj, QualType SubobjType) {
  2190. if (!checkConst(SubobjType))
  2191. return false;
  2192. // We've been given ownership of NewVal, so just swap it in.
  2193. Subobj.swap(NewVal);
  2194. return true;
  2195. }
  2196. bool found(APSInt &Value, QualType SubobjType) {
  2197. if (!checkConst(SubobjType))
  2198. return false;
  2199. if (!NewVal.isInt()) {
  2200. // Maybe trying to write a cast pointer value into a complex?
  2201. Info.Diag(E);
  2202. return false;
  2203. }
  2204. Value = NewVal.getInt();
  2205. return true;
  2206. }
  2207. bool found(APFloat &Value, QualType SubobjType) {
  2208. if (!checkConst(SubobjType))
  2209. return false;
  2210. Value = NewVal.getFloat();
  2211. return true;
  2212. }
  2213. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2214. llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
  2215. }
  2216. };
  2217. } // end anonymous namespace
  2218. const AccessKinds ModifySubobjectHandler::AccessKind;
  2219. /// Update the designated sub-object of an rvalue to the given value.
  2220. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2221. const CompleteObject &Obj,
  2222. const SubobjectDesignator &Sub,
  2223. APValue &NewVal) {
  2224. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2225. return findSubobject(Info, E, Obj, Sub, Handler);
  2226. }
  2227. /// Find the position where two subobject designators diverge, or equivalently
  2228. /// the length of the common initial subsequence.
  2229. static unsigned FindDesignatorMismatch(QualType ObjType,
  2230. const SubobjectDesignator &A,
  2231. const SubobjectDesignator &B,
  2232. bool &WasArrayIndex) {
  2233. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2234. for (/**/; I != N; ++I) {
  2235. if (!ObjType.isNull() &&
  2236. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2237. // Next subobject is an array element.
  2238. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  2239. WasArrayIndex = true;
  2240. return I;
  2241. }
  2242. if (ObjType->isAnyComplexType())
  2243. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2244. else
  2245. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2246. } else {
  2247. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  2248. WasArrayIndex = false;
  2249. return I;
  2250. }
  2251. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2252. // Next subobject is a field.
  2253. ObjType = FD->getType();
  2254. else
  2255. // Next subobject is a base class.
  2256. ObjType = QualType();
  2257. }
  2258. }
  2259. WasArrayIndex = false;
  2260. return I;
  2261. }
  2262. /// Determine whether the given subobject designators refer to elements of the
  2263. /// same array object.
  2264. static bool AreElementsOfSameArray(QualType ObjType,
  2265. const SubobjectDesignator &A,
  2266. const SubobjectDesignator &B) {
  2267. if (A.Entries.size() != B.Entries.size())
  2268. return false;
  2269. bool IsArray = A.MostDerivedArraySize != 0;
  2270. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2271. // A is a subobject of the array element.
  2272. return false;
  2273. // If A (and B) designates an array element, the last entry will be the array
  2274. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2275. // of length 1' case, and the entire path must match.
  2276. bool WasArrayIndex;
  2277. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2278. return CommonLength >= A.Entries.size() - IsArray;
  2279. }
  2280. /// Find the complete object to which an LValue refers.
  2281. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2282. AccessKinds AK, const LValue &LVal,
  2283. QualType LValType) {
  2284. if (!LVal.Base) {
  2285. Info.Diag(E, diag::note_constexpr_access_null) << AK;
  2286. return CompleteObject();
  2287. }
  2288. CallStackFrame *Frame = nullptr;
  2289. if (LVal.CallIndex) {
  2290. Frame = Info.getCallFrame(LVal.CallIndex);
  2291. if (!Frame) {
  2292. Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
  2293. << AK << LVal.Base.is<const ValueDecl*>();
  2294. NoteLValueLocation(Info, LVal.Base);
  2295. return CompleteObject();
  2296. }
  2297. }
  2298. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2299. // is not a constant expression (even if the object is non-volatile). We also
  2300. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2301. // semantics.
  2302. if (LValType.isVolatileQualified()) {
  2303. if (Info.getLangOpts().CPlusPlus)
  2304. Info.Diag(E, diag::note_constexpr_access_volatile_type)
  2305. << AK << LValType;
  2306. else
  2307. Info.Diag(E);
  2308. return CompleteObject();
  2309. }
  2310. // Compute value storage location and type of base object.
  2311. APValue *BaseVal = nullptr;
  2312. QualType BaseType = getType(LVal.Base);
  2313. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2314. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2315. // In C++11, constexpr, non-volatile variables initialized with constant
  2316. // expressions are constant expressions too. Inside constexpr functions,
  2317. // parameters are constant expressions even if they're non-const.
  2318. // In C++1y, objects local to a constant expression (those with a Frame) are
  2319. // both readable and writable inside constant expressions.
  2320. // In C, such things can also be folded, although they are not ICEs.
  2321. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2322. if (VD) {
  2323. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2324. VD = VDef;
  2325. }
  2326. if (!VD || VD->isInvalidDecl()) {
  2327. Info.Diag(E);
  2328. return CompleteObject();
  2329. }
  2330. // Accesses of volatile-qualified objects are not allowed.
  2331. if (BaseType.isVolatileQualified()) {
  2332. if (Info.getLangOpts().CPlusPlus) {
  2333. Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
  2334. << AK << 1 << VD;
  2335. Info.Note(VD->getLocation(), diag::note_declared_at);
  2336. } else {
  2337. Info.Diag(E);
  2338. }
  2339. return CompleteObject();
  2340. }
  2341. // Unless we're looking at a local variable or argument in a constexpr call,
  2342. // the variable we're reading must be const.
  2343. if (!Frame) {
  2344. if (Info.getLangOpts().CPlusPlus14 &&
  2345. VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
  2346. // OK, we can read and modify an object if we're in the process of
  2347. // evaluating its initializer, because its lifetime began in this
  2348. // evaluation.
  2349. } else if (AK != AK_Read) {
  2350. // All the remaining cases only permit reading.
  2351. Info.Diag(E, diag::note_constexpr_modify_global);
  2352. return CompleteObject();
  2353. } else if (VD->isConstexpr()) {
  2354. // OK, we can read this variable.
  2355. } else if (BaseType->isIntegralOrEnumerationType()) {
  2356. if (!BaseType.isConstQualified()) {
  2357. if (Info.getLangOpts().CPlusPlus) {
  2358. Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2359. Info.Note(VD->getLocation(), diag::note_declared_at);
  2360. } else {
  2361. Info.Diag(E);
  2362. }
  2363. return CompleteObject();
  2364. }
  2365. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2366. // We support folding of const floating-point types, in order to make
  2367. // static const data members of such types (supported as an extension)
  2368. // more useful.
  2369. if (Info.getLangOpts().CPlusPlus11) {
  2370. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2371. Info.Note(VD->getLocation(), diag::note_declared_at);
  2372. } else {
  2373. Info.CCEDiag(E);
  2374. }
  2375. } else {
  2376. // FIXME: Allow folding of values of any literal type in all languages.
  2377. if (Info.getLangOpts().CPlusPlus11) {
  2378. Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2379. Info.Note(VD->getLocation(), diag::note_declared_at);
  2380. } else {
  2381. Info.Diag(E);
  2382. }
  2383. return CompleteObject();
  2384. }
  2385. }
  2386. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
  2387. return CompleteObject();
  2388. } else {
  2389. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2390. if (!Frame) {
  2391. if (const MaterializeTemporaryExpr *MTE =
  2392. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  2393. assert(MTE->getStorageDuration() == SD_Static &&
  2394. "should have a frame for a non-global materialized temporary");
  2395. // Per C++1y [expr.const]p2:
  2396. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2397. // - a [...] glvalue of integral or enumeration type that refers to
  2398. // a non-volatile const object [...]
  2399. // [...]
  2400. // - a [...] glvalue of literal type that refers to a non-volatile
  2401. // object whose lifetime began within the evaluation of e.
  2402. //
  2403. // C++11 misses the 'began within the evaluation of e' check and
  2404. // instead allows all temporaries, including things like:
  2405. // int &&r = 1;
  2406. // int x = ++r;
  2407. // constexpr int k = r;
  2408. // Therefore we use the C++1y rules in C++11 too.
  2409. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2410. const ValueDecl *ED = MTE->getExtendingDecl();
  2411. if (!(BaseType.isConstQualified() &&
  2412. BaseType->isIntegralOrEnumerationType()) &&
  2413. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2414. Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2415. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2416. return CompleteObject();
  2417. }
  2418. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2419. assert(BaseVal && "got reference to unevaluated temporary");
  2420. } else {
  2421. Info.Diag(E);
  2422. return CompleteObject();
  2423. }
  2424. } else {
  2425. BaseVal = Frame->getTemporary(Base);
  2426. assert(BaseVal && "missing value for temporary");
  2427. }
  2428. // Volatile temporary objects cannot be accessed in constant expressions.
  2429. if (BaseType.isVolatileQualified()) {
  2430. if (Info.getLangOpts().CPlusPlus) {
  2431. Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
  2432. << AK << 0;
  2433. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  2434. } else {
  2435. Info.Diag(E);
  2436. }
  2437. return CompleteObject();
  2438. }
  2439. }
  2440. // During the construction of an object, it is not yet 'const'.
  2441. // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
  2442. // and this doesn't do quite the right thing for const subobjects of the
  2443. // object under construction.
  2444. if (LVal.getLValueBase() == Info.EvaluatingDecl) {
  2445. BaseType = Info.Ctx.getCanonicalType(BaseType);
  2446. BaseType.removeLocalConst();
  2447. }
  2448. // In C++1y, we can't safely access any mutable state when we might be
  2449. // evaluating after an unmodeled side effect or an evaluation failure.
  2450. //
  2451. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2452. // to be read here (but take care with 'mutable' fields).
  2453. if (Frame && Info.getLangOpts().CPlusPlus14 &&
  2454. (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
  2455. return CompleteObject();
  2456. return CompleteObject(BaseVal, BaseType);
  2457. }
  2458. /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2459. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2460. /// glvalue referred to by an entity of reference type.
  2461. ///
  2462. /// \param Info - Information about the ongoing evaluation.
  2463. /// \param Conv - The expression for which we are performing the conversion.
  2464. /// Used for diagnostics.
  2465. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  2466. /// case of a non-class type).
  2467. /// \param LVal - The glvalue on which we are attempting to perform this action.
  2468. /// \param RVal - The produced value will be placed here.
  2469. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2470. QualType Type,
  2471. const LValue &LVal, APValue &RVal) {
  2472. if (LVal.Designator.Invalid)
  2473. return false;
  2474. // Check for special cases where there is no existing APValue to look at.
  2475. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2476. if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
  2477. !Type.isVolatileQualified()) {
  2478. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  2479. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  2480. // initializer until now for such expressions. Such an expression can't be
  2481. // an ICE in C, so this only matters for fold.
  2482. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  2483. if (Type.isVolatileQualified()) {
  2484. Info.Diag(Conv);
  2485. return false;
  2486. }
  2487. APValue Lit;
  2488. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  2489. return false;
  2490. CompleteObject LitObj(&Lit, Base->getType());
  2491. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  2492. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  2493. // We represent a string literal array as an lvalue pointing at the
  2494. // corresponding expression, rather than building an array of chars.
  2495. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  2496. APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  2497. CompleteObject StrObj(&Str, Base->getType());
  2498. return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
  2499. }
  2500. }
  2501. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  2502. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  2503. }
  2504. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  2505. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  2506. QualType LValType, APValue &Val) {
  2507. if (LVal.Designator.Invalid)
  2508. return false;
  2509. if (!Info.getLangOpts().CPlusPlus14) {
  2510. Info.Diag(E);
  2511. return false;
  2512. }
  2513. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  2514. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  2515. }
  2516. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  2517. return T->isSignedIntegerType() &&
  2518. Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  2519. }
  2520. namespace {
  2521. struct CompoundAssignSubobjectHandler {
  2522. EvalInfo &Info;
  2523. const Expr *E;
  2524. QualType PromotedLHSType;
  2525. BinaryOperatorKind Opcode;
  2526. const APValue &RHS;
  2527. static const AccessKinds AccessKind = AK_Assign;
  2528. typedef bool result_type;
  2529. bool checkConst(QualType QT) {
  2530. // Assigning to a const object has undefined behavior.
  2531. if (QT.isConstQualified()) {
  2532. Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
  2533. return false;
  2534. }
  2535. return true;
  2536. }
  2537. bool failed() { return false; }
  2538. bool found(APValue &Subobj, QualType SubobjType) {
  2539. switch (Subobj.getKind()) {
  2540. case APValue::Int:
  2541. return found(Subobj.getInt(), SubobjType);
  2542. case APValue::Float:
  2543. return found(Subobj.getFloat(), SubobjType);
  2544. case APValue::ComplexInt:
  2545. case APValue::ComplexFloat:
  2546. // FIXME: Implement complex compound assignment.
  2547. Info.Diag(E);
  2548. return false;
  2549. case APValue::LValue:
  2550. return foundPointer(Subobj, SubobjType);
  2551. default:
  2552. // FIXME: can this happen?
  2553. Info.Diag(E);
  2554. return false;
  2555. }
  2556. }
  2557. bool found(APSInt &Value, QualType SubobjType) {
  2558. if (!checkConst(SubobjType))
  2559. return false;
  2560. if (!SubobjType->isIntegerType() || !RHS.isInt()) {
  2561. // We don't support compound assignment on integer-cast-to-pointer
  2562. // values.
  2563. Info.Diag(E);
  2564. return false;
  2565. }
  2566. APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
  2567. SubobjType, Value);
  2568. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  2569. return false;
  2570. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  2571. return true;
  2572. }
  2573. bool found(APFloat &Value, QualType SubobjType) {
  2574. return checkConst(SubobjType) &&
  2575. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  2576. Value) &&
  2577. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  2578. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  2579. }
  2580. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  2581. if (!checkConst(SubobjType))
  2582. return false;
  2583. QualType PointeeType;
  2584. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  2585. PointeeType = PT->getPointeeType();
  2586. if (PointeeType.isNull() || !RHS.isInt() ||
  2587. (Opcode != BO_Add && Opcode != BO_Sub)) {
  2588. Info.Diag(E);
  2589. return false;
  2590. }
  2591. int64_t Offset = getExtValue(RHS.getInt());
  2592. if (Opcode == BO_Sub)
  2593. Offset = -Offset;
  2594. LValue LVal;
  2595. LVal.setFrom(Info.Ctx, Subobj);
  2596. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  2597. return false;
  2598. LVal.moveInto(Subobj);
  2599. return true;
  2600. }
  2601. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2602. llvm_unreachable("shouldn't encounter string elements here");
  2603. }
  2604. };
  2605. } // end anonymous namespace
  2606. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  2607. /// Perform a compound assignment of LVal <op>= RVal.
  2608. static bool handleCompoundAssignment(
  2609. EvalInfo &Info, const Expr *E,
  2610. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  2611. BinaryOperatorKind Opcode, const APValue &RVal) {
  2612. if (LVal.Designator.Invalid)
  2613. return false;
  2614. if (!Info.getLangOpts().CPlusPlus14) {
  2615. Info.Diag(E);
  2616. return false;
  2617. }
  2618. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  2619. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  2620. RVal };
  2621. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  2622. }
  2623. namespace {
  2624. struct IncDecSubobjectHandler {
  2625. EvalInfo &Info;
  2626. const Expr *E;
  2627. AccessKinds AccessKind;
  2628. APValue *Old;
  2629. typedef bool result_type;
  2630. bool checkConst(QualType QT) {
  2631. // Assigning to a const object has undefined behavior.
  2632. if (QT.isConstQualified()) {
  2633. Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
  2634. return false;
  2635. }
  2636. return true;
  2637. }
  2638. bool failed() { return false; }
  2639. bool found(APValue &Subobj, QualType SubobjType) {
  2640. // Stash the old value. Also clear Old, so we don't clobber it later
  2641. // if we're post-incrementing a complex.
  2642. if (Old) {
  2643. *Old = Subobj;
  2644. Old = nullptr;
  2645. }
  2646. switch (Subobj.getKind()) {
  2647. case APValue::Int:
  2648. return found(Subobj.getInt(), SubobjType);
  2649. case APValue::Float:
  2650. return found(Subobj.getFloat(), SubobjType);
  2651. case APValue::ComplexInt:
  2652. return found(Subobj.getComplexIntReal(),
  2653. SubobjType->castAs<ComplexType>()->getElementType()
  2654. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  2655. case APValue::ComplexFloat:
  2656. return found(Subobj.getComplexFloatReal(),
  2657. SubobjType->castAs<ComplexType>()->getElementType()
  2658. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  2659. case APValue::LValue:
  2660. return foundPointer(Subobj, SubobjType);
  2661. default:
  2662. // FIXME: can this happen?
  2663. Info.Diag(E);
  2664. return false;
  2665. }
  2666. }
  2667. bool found(APSInt &Value, QualType SubobjType) {
  2668. if (!checkConst(SubobjType))
  2669. return false;
  2670. if (!SubobjType->isIntegerType()) {
  2671. // We don't support increment / decrement on integer-cast-to-pointer
  2672. // values.
  2673. Info.Diag(E);
  2674. return false;
  2675. }
  2676. if (Old) *Old = APValue(Value);
  2677. // bool arithmetic promotes to int, and the conversion back to bool
  2678. // doesn't reduce mod 2^n, so special-case it.
  2679. if (SubobjType->isBooleanType()) {
  2680. if (AccessKind == AK_Increment)
  2681. Value = 1;
  2682. else
  2683. Value = !Value;
  2684. return true;
  2685. }
  2686. bool WasNegative = Value.isNegative();
  2687. if (AccessKind == AK_Increment) {
  2688. ++Value;
  2689. if (!WasNegative && Value.isNegative() &&
  2690. isOverflowingIntegerType(Info.Ctx, SubobjType)) {
  2691. APSInt ActualValue(Value, /*IsUnsigned*/true);
  2692. HandleOverflow(Info, E, ActualValue, SubobjType);
  2693. }
  2694. } else {
  2695. --Value;
  2696. if (WasNegative && !Value.isNegative() &&
  2697. isOverflowingIntegerType(Info.Ctx, SubobjType)) {
  2698. unsigned BitWidth = Value.getBitWidth();
  2699. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  2700. ActualValue.setBit(BitWidth);
  2701. HandleOverflow(Info, E, ActualValue, SubobjType);
  2702. }
  2703. }
  2704. return true;
  2705. }
  2706. bool found(APFloat &Value, QualType SubobjType) {
  2707. if (!checkConst(SubobjType))
  2708. return false;
  2709. if (Old) *Old = APValue(Value);
  2710. APFloat One(Value.getSemantics(), 1);
  2711. if (AccessKind == AK_Increment)
  2712. Value.add(One, APFloat::rmNearestTiesToEven);
  2713. else
  2714. Value.subtract(One, APFloat::rmNearestTiesToEven);
  2715. return true;
  2716. }
  2717. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  2718. if (!checkConst(SubobjType))
  2719. return false;
  2720. QualType PointeeType;
  2721. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  2722. PointeeType = PT->getPointeeType();
  2723. else {
  2724. Info.Diag(E);
  2725. return false;
  2726. }
  2727. LValue LVal;
  2728. LVal.setFrom(Info.Ctx, Subobj);
  2729. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  2730. AccessKind == AK_Increment ? 1 : -1))
  2731. return false;
  2732. LVal.moveInto(Subobj);
  2733. return true;
  2734. }
  2735. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2736. llvm_unreachable("shouldn't encounter string elements here");
  2737. }
  2738. };
  2739. } // end anonymous namespace
  2740. /// Perform an increment or decrement on LVal.
  2741. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  2742. QualType LValType, bool IsIncrement, APValue *Old) {
  2743. if (LVal.Designator.Invalid)
  2744. return false;
  2745. if (!Info.getLangOpts().CPlusPlus14) {
  2746. Info.Diag(E);
  2747. return false;
  2748. }
  2749. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  2750. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  2751. IncDecSubobjectHandler Handler = { Info, E, AK, Old };
  2752. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  2753. }
  2754. /// Build an lvalue for the object argument of a member function call.
  2755. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  2756. LValue &This) {
  2757. if (Object->getType()->isPointerType())
  2758. return EvaluatePointer(Object, This, Info);
  2759. if (Object->isGLValue())
  2760. return EvaluateLValue(Object, This, Info);
  2761. if (Object->getType()->isLiteralType(Info.Ctx))
  2762. return EvaluateTemporary(Object, This, Info);
  2763. Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  2764. return false;
  2765. }
  2766. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  2767. /// lvalue referring to the result.
  2768. ///
  2769. /// \param Info - Information about the ongoing evaluation.
  2770. /// \param LV - An lvalue referring to the base of the member pointer.
  2771. /// \param RHS - The member pointer expression.
  2772. /// \param IncludeMember - Specifies whether the member itself is included in
  2773. /// the resulting LValue subobject designator. This is not possible when
  2774. /// creating a bound member function.
  2775. /// \return The field or method declaration to which the member pointer refers,
  2776. /// or 0 if evaluation fails.
  2777. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  2778. QualType LVType,
  2779. LValue &LV,
  2780. const Expr *RHS,
  2781. bool IncludeMember = true) {
  2782. MemberPtr MemPtr;
  2783. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  2784. return nullptr;
  2785. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  2786. // member value, the behavior is undefined.
  2787. if (!MemPtr.getDecl()) {
  2788. // FIXME: Specific diagnostic.
  2789. Info.Diag(RHS);
  2790. return nullptr;
  2791. }
  2792. if (MemPtr.isDerivedMember()) {
  2793. // This is a member of some derived class. Truncate LV appropriately.
  2794. // The end of the derived-to-base path for the base object must match the
  2795. // derived-to-base path for the member pointer.
  2796. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  2797. LV.Designator.Entries.size()) {
  2798. Info.Diag(RHS);
  2799. return nullptr;
  2800. }
  2801. unsigned PathLengthToMember =
  2802. LV.Designator.Entries.size() - MemPtr.Path.size();
  2803. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  2804. const CXXRecordDecl *LVDecl = getAsBaseClass(
  2805. LV.Designator.Entries[PathLengthToMember + I]);
  2806. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  2807. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  2808. Info.Diag(RHS);
  2809. return nullptr;
  2810. }
  2811. }
  2812. // Truncate the lvalue to the appropriate derived class.
  2813. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  2814. PathLengthToMember))
  2815. return nullptr;
  2816. } else if (!MemPtr.Path.empty()) {
  2817. // Extend the LValue path with the member pointer's path.
  2818. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  2819. MemPtr.Path.size() + IncludeMember);
  2820. // Walk down to the appropriate base class.
  2821. if (const PointerType *PT = LVType->getAs<PointerType>())
  2822. LVType = PT->getPointeeType();
  2823. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  2824. assert(RD && "member pointer access on non-class-type expression");
  2825. // The first class in the path is that of the lvalue.
  2826. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  2827. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  2828. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  2829. return nullptr;
  2830. RD = Base;
  2831. }
  2832. // Finally cast to the class containing the member.
  2833. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  2834. MemPtr.getContainingRecord()))
  2835. return nullptr;
  2836. }
  2837. // Add the member. Note that we cannot build bound member functions here.
  2838. if (IncludeMember) {
  2839. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  2840. if (!HandleLValueMember(Info, RHS, LV, FD))
  2841. return nullptr;
  2842. } else if (const IndirectFieldDecl *IFD =
  2843. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  2844. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  2845. return nullptr;
  2846. } else {
  2847. llvm_unreachable("can't construct reference to bound member function");
  2848. }
  2849. }
  2850. return MemPtr.getDecl();
  2851. }
  2852. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  2853. const BinaryOperator *BO,
  2854. LValue &LV,
  2855. bool IncludeMember = true) {
  2856. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  2857. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  2858. if (Info.keepEvaluatingAfterFailure()) {
  2859. MemberPtr MemPtr;
  2860. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  2861. }
  2862. return nullptr;
  2863. }
  2864. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  2865. BO->getRHS(), IncludeMember);
  2866. }
  2867. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  2868. /// the provided lvalue, which currently refers to the base object.
  2869. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  2870. LValue &Result) {
  2871. SubobjectDesignator &D = Result.Designator;
  2872. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  2873. return false;
  2874. QualType TargetQT = E->getType();
  2875. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  2876. TargetQT = PT->getPointeeType();
  2877. // Check this cast lands within the final derived-to-base subobject path.
  2878. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  2879. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  2880. << D.MostDerivedType << TargetQT;
  2881. return false;
  2882. }
  2883. // Check the type of the final cast. We don't need to check the path,
  2884. // since a cast can only be formed if the path is unique.
  2885. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  2886. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  2887. const CXXRecordDecl *FinalType;
  2888. if (NewEntriesSize == D.MostDerivedPathLength)
  2889. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  2890. else
  2891. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  2892. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  2893. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  2894. << D.MostDerivedType << TargetQT;
  2895. return false;
  2896. }
  2897. // Truncate the lvalue to the appropriate derived class.
  2898. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  2899. }
  2900. namespace {
  2901. enum EvalStmtResult {
  2902. /// Evaluation failed.
  2903. ESR_Failed,
  2904. /// Hit a 'return' statement.
  2905. ESR_Returned,
  2906. /// Evaluation succeeded.
  2907. ESR_Succeeded,
  2908. /// Hit a 'continue' statement.
  2909. ESR_Continue,
  2910. /// Hit a 'break' statement.
  2911. ESR_Break,
  2912. /// Still scanning for 'case' or 'default' statement.
  2913. ESR_CaseNotFound
  2914. };
  2915. }
  2916. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  2917. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2918. // We don't need to evaluate the initializer for a static local.
  2919. if (!VD->hasLocalStorage())
  2920. return true;
  2921. LValue Result;
  2922. Result.set(VD, Info.CurrentCall->Index);
  2923. APValue &Val = Info.CurrentCall->createTemporary(VD, true);
  2924. const Expr *InitE = VD->getInit();
  2925. if (!InitE) {
  2926. Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
  2927. << false << VD->getType();
  2928. Val = APValue();
  2929. return false;
  2930. }
  2931. if (InitE->isValueDependent())
  2932. return false;
  2933. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  2934. // Wipe out any partially-computed value, to allow tracking that this
  2935. // evaluation failed.
  2936. Val = APValue();
  2937. return false;
  2938. }
  2939. }
  2940. return true;
  2941. }
  2942. /// Evaluate a condition (either a variable declaration or an expression).
  2943. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  2944. const Expr *Cond, bool &Result) {
  2945. FullExpressionRAII Scope(Info);
  2946. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  2947. return false;
  2948. return EvaluateAsBooleanCondition(Cond, Result, Info);
  2949. }
  2950. static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
  2951. const Stmt *S,
  2952. const SwitchCase *SC = nullptr);
  2953. /// Evaluate the body of a loop, and translate the result as appropriate.
  2954. static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
  2955. const Stmt *Body,
  2956. const SwitchCase *Case = nullptr) {
  2957. BlockScopeRAII Scope(Info);
  2958. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  2959. case ESR_Break:
  2960. return ESR_Succeeded;
  2961. case ESR_Succeeded:
  2962. case ESR_Continue:
  2963. return ESR_Continue;
  2964. case ESR_Failed:
  2965. case ESR_Returned:
  2966. case ESR_CaseNotFound:
  2967. return ESR;
  2968. }
  2969. llvm_unreachable("Invalid EvalStmtResult!");
  2970. }
  2971. /// Evaluate a switch statement.
  2972. static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
  2973. const SwitchStmt *SS) {
  2974. BlockScopeRAII Scope(Info);
  2975. // Evaluate the switch condition.
  2976. APSInt Value;
  2977. {
  2978. FullExpressionRAII Scope(Info);
  2979. if (SS->getConditionVariable() &&
  2980. !EvaluateDecl(Info, SS->getConditionVariable()))
  2981. return ESR_Failed;
  2982. if (!EvaluateInteger(SS->getCond(), Value, Info))
  2983. return ESR_Failed;
  2984. }
  2985. // Find the switch case corresponding to the value of the condition.
  2986. // FIXME: Cache this lookup.
  2987. const SwitchCase *Found = nullptr;
  2988. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  2989. SC = SC->getNextSwitchCase()) {
  2990. if (isa<DefaultStmt>(SC)) {
  2991. Found = SC;
  2992. continue;
  2993. }
  2994. const CaseStmt *CS = cast<CaseStmt>(SC);
  2995. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  2996. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  2997. : LHS;
  2998. if (LHS <= Value && Value <= RHS) {
  2999. Found = SC;
  3000. break;
  3001. }
  3002. }
  3003. if (!Found)
  3004. return ESR_Succeeded;
  3005. // Search the switch body for the switch case and evaluate it from there.
  3006. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3007. case ESR_Break:
  3008. return ESR_Succeeded;
  3009. case ESR_Succeeded:
  3010. case ESR_Continue:
  3011. case ESR_Failed:
  3012. case ESR_Returned:
  3013. return ESR;
  3014. case ESR_CaseNotFound:
  3015. // This can only happen if the switch case is nested within a statement
  3016. // expression. We have no intention of supporting that.
  3017. Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
  3018. return ESR_Failed;
  3019. }
  3020. llvm_unreachable("Invalid EvalStmtResult!");
  3021. }
  3022. // Evaluate a statement.
  3023. static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
  3024. const Stmt *S, const SwitchCase *Case) {
  3025. if (!Info.nextStep(S))
  3026. return ESR_Failed;
  3027. // If we're hunting down a 'case' or 'default' label, recurse through
  3028. // substatements until we hit the label.
  3029. if (Case) {
  3030. // FIXME: We don't start the lifetime of objects whose initialization we
  3031. // jump over. However, such objects must be of class type with a trivial
  3032. // default constructor that initialize all subobjects, so must be empty,
  3033. // so this almost never matters.
  3034. switch (S->getStmtClass()) {
  3035. case Stmt::CompoundStmtClass:
  3036. // FIXME: Precompute which substatement of a compound statement we
  3037. // would jump to, and go straight there rather than performing a
  3038. // linear scan each time.
  3039. case Stmt::LabelStmtClass:
  3040. case Stmt::AttributedStmtClass:
  3041. case Stmt::DoStmtClass:
  3042. break;
  3043. case Stmt::CaseStmtClass:
  3044. case Stmt::DefaultStmtClass:
  3045. if (Case == S)
  3046. Case = nullptr;
  3047. break;
  3048. case Stmt::IfStmtClass: {
  3049. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3050. // straight there rather than scanning both sides.
  3051. const IfStmt *IS = cast<IfStmt>(S);
  3052. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3053. // preceded by our switch label.
  3054. BlockScopeRAII Scope(Info);
  3055. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3056. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3057. return ESR;
  3058. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3059. }
  3060. case Stmt::WhileStmtClass: {
  3061. EvalStmtResult ESR =
  3062. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3063. if (ESR != ESR_Continue)
  3064. return ESR;
  3065. break;
  3066. }
  3067. case Stmt::ForStmtClass: {
  3068. const ForStmt *FS = cast<ForStmt>(S);
  3069. EvalStmtResult ESR =
  3070. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3071. if (ESR != ESR_Continue)
  3072. return ESR;
  3073. if (FS->getInc()) {
  3074. FullExpressionRAII IncScope(Info);
  3075. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3076. return ESR_Failed;
  3077. }
  3078. break;
  3079. }
  3080. case Stmt::DeclStmtClass:
  3081. // FIXME: If the variable has initialization that can't be jumped over,
  3082. // bail out of any immediately-surrounding compound-statement too.
  3083. default:
  3084. return ESR_CaseNotFound;
  3085. }
  3086. }
  3087. switch (S->getStmtClass()) {
  3088. default:
  3089. if (const Expr *E = dyn_cast<Expr>(S)) {
  3090. // Don't bother evaluating beyond an expression-statement which couldn't
  3091. // be evaluated.
  3092. FullExpressionRAII Scope(Info);
  3093. if (!EvaluateIgnoredValue(Info, E))
  3094. return ESR_Failed;
  3095. return ESR_Succeeded;
  3096. }
  3097. Info.Diag(S->getLocStart());
  3098. return ESR_Failed;
  3099. case Stmt::NullStmtClass:
  3100. return ESR_Succeeded;
  3101. case Stmt::DeclStmtClass: {
  3102. const DeclStmt *DS = cast<DeclStmt>(S);
  3103. for (const auto *DclIt : DS->decls()) {
  3104. // Each declaration initialization is its own full-expression.
  3105. // FIXME: This isn't quite right; if we're performing aggregate
  3106. // initialization, each braced subexpression is its own full-expression.
  3107. FullExpressionRAII Scope(Info);
  3108. if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
  3109. return ESR_Failed;
  3110. }
  3111. return ESR_Succeeded;
  3112. }
  3113. case Stmt::ReturnStmtClass: {
  3114. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3115. FullExpressionRAII Scope(Info);
  3116. if (RetExpr && !Evaluate(Result, Info, RetExpr))
  3117. return ESR_Failed;
  3118. return ESR_Returned;
  3119. }
  3120. case Stmt::CompoundStmtClass: {
  3121. BlockScopeRAII Scope(Info);
  3122. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3123. for (const auto *BI : CS->body()) {
  3124. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3125. if (ESR == ESR_Succeeded)
  3126. Case = nullptr;
  3127. else if (ESR != ESR_CaseNotFound)
  3128. return ESR;
  3129. }
  3130. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3131. }
  3132. case Stmt::IfStmtClass: {
  3133. const IfStmt *IS = cast<IfStmt>(S);
  3134. // Evaluate the condition, as either a var decl or as an expression.
  3135. BlockScopeRAII Scope(Info);
  3136. bool Cond;
  3137. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3138. return ESR_Failed;
  3139. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3140. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3141. if (ESR != ESR_Succeeded)
  3142. return ESR;
  3143. }
  3144. return ESR_Succeeded;
  3145. }
  3146. case Stmt::WhileStmtClass: {
  3147. const WhileStmt *WS = cast<WhileStmt>(S);
  3148. while (true) {
  3149. BlockScopeRAII Scope(Info);
  3150. bool Continue;
  3151. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3152. Continue))
  3153. return ESR_Failed;
  3154. if (!Continue)
  3155. break;
  3156. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3157. if (ESR != ESR_Continue)
  3158. return ESR;
  3159. }
  3160. return ESR_Succeeded;
  3161. }
  3162. case Stmt::DoStmtClass: {
  3163. const DoStmt *DS = cast<DoStmt>(S);
  3164. bool Continue;
  3165. do {
  3166. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3167. if (ESR != ESR_Continue)
  3168. return ESR;
  3169. Case = nullptr;
  3170. FullExpressionRAII CondScope(Info);
  3171. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3172. return ESR_Failed;
  3173. } while (Continue);
  3174. return ESR_Succeeded;
  3175. }
  3176. case Stmt::ForStmtClass: {
  3177. const ForStmt *FS = cast<ForStmt>(S);
  3178. BlockScopeRAII Scope(Info);
  3179. if (FS->getInit()) {
  3180. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3181. if (ESR != ESR_Succeeded)
  3182. return ESR;
  3183. }
  3184. while (true) {
  3185. BlockScopeRAII Scope(Info);
  3186. bool Continue = true;
  3187. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3188. FS->getCond(), Continue))
  3189. return ESR_Failed;
  3190. if (!Continue)
  3191. break;
  3192. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3193. if (ESR != ESR_Continue)
  3194. return ESR;
  3195. if (FS->getInc()) {
  3196. FullExpressionRAII IncScope(Info);
  3197. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3198. return ESR_Failed;
  3199. }
  3200. }
  3201. return ESR_Succeeded;
  3202. }
  3203. case Stmt::CXXForRangeStmtClass: {
  3204. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3205. BlockScopeRAII Scope(Info);
  3206. // Initialize the __range variable.
  3207. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3208. if (ESR != ESR_Succeeded)
  3209. return ESR;
  3210. // Create the __begin and __end iterators.
  3211. ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
  3212. if (ESR != ESR_Succeeded)
  3213. return ESR;
  3214. while (true) {
  3215. // Condition: __begin != __end.
  3216. {
  3217. bool Continue = true;
  3218. FullExpressionRAII CondExpr(Info);
  3219. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3220. return ESR_Failed;
  3221. if (!Continue)
  3222. break;
  3223. }
  3224. // User's variable declaration, initialized by *__begin.
  3225. BlockScopeRAII InnerScope(Info);
  3226. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3227. if (ESR != ESR_Succeeded)
  3228. return ESR;
  3229. // Loop body.
  3230. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3231. if (ESR != ESR_Continue)
  3232. return ESR;
  3233. // Increment: ++__begin
  3234. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3235. return ESR_Failed;
  3236. }
  3237. return ESR_Succeeded;
  3238. }
  3239. case Stmt::SwitchStmtClass:
  3240. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3241. case Stmt::ContinueStmtClass:
  3242. return ESR_Continue;
  3243. case Stmt::BreakStmtClass:
  3244. return ESR_Break;
  3245. case Stmt::LabelStmtClass:
  3246. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3247. case Stmt::AttributedStmtClass:
  3248. // As a general principle, C++11 attributes can be ignored without
  3249. // any semantic impact.
  3250. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3251. Case);
  3252. case Stmt::CaseStmtClass:
  3253. case Stmt::DefaultStmtClass:
  3254. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3255. }
  3256. }
  3257. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3258. /// default constructor. If so, we'll fold it whether or not it's marked as
  3259. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3260. /// so we need special handling.
  3261. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3262. const CXXConstructorDecl *CD,
  3263. bool IsValueInitialization) {
  3264. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3265. return false;
  3266. // Value-initialization does not call a trivial default constructor, so such a
  3267. // call is a core constant expression whether or not the constructor is
  3268. // constexpr.
  3269. if (!CD->isConstexpr() && !IsValueInitialization) {
  3270. if (Info.getLangOpts().CPlusPlus11) {
  3271. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3272. // we should be much more explicit about why it's not constexpr.
  3273. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3274. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3275. Info.Note(CD->getLocation(), diag::note_declared_at);
  3276. } else {
  3277. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3278. }
  3279. }
  3280. return true;
  3281. }
  3282. /// CheckConstexprFunction - Check that a function can be called in a constant
  3283. /// expression.
  3284. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3285. const FunctionDecl *Declaration,
  3286. const FunctionDecl *Definition) {
  3287. // Potential constant expressions can contain calls to declared, but not yet
  3288. // defined, constexpr functions.
  3289. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3290. Declaration->isConstexpr())
  3291. return false;
  3292. // Bail out with no diagnostic if the function declaration itself is invalid.
  3293. // We will have produced a relevant diagnostic while parsing it.
  3294. if (Declaration->isInvalidDecl())
  3295. return false;
  3296. // Can we evaluate this function call?
  3297. if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
  3298. return true;
  3299. if (Info.getLangOpts().CPlusPlus11) {
  3300. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3301. // FIXME: If DiagDecl is an implicitly-declared special member function, we
  3302. // should be much more explicit about why it's not constexpr.
  3303. Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3304. << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
  3305. << DiagDecl;
  3306. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3307. } else {
  3308. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3309. }
  3310. return false;
  3311. }
  3312. /// Determine if a class has any fields that might need to be copied by a
  3313. /// trivial copy or move operation.
  3314. static bool hasFields(const CXXRecordDecl *RD) {
  3315. if (!RD || RD->isEmpty())
  3316. return false;
  3317. for (auto *FD : RD->fields()) {
  3318. if (FD->isUnnamedBitfield())
  3319. continue;
  3320. return true;
  3321. }
  3322. for (auto &Base : RD->bases())
  3323. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  3324. return true;
  3325. return false;
  3326. }
  3327. namespace {
  3328. typedef SmallVector<APValue, 8> ArgVector;
  3329. }
  3330. /// EvaluateArgs - Evaluate the arguments to a function call.
  3331. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  3332. EvalInfo &Info) {
  3333. bool Success = true;
  3334. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  3335. I != E; ++I) {
  3336. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  3337. // If we're checking for a potential constant expression, evaluate all
  3338. // initializers even if some of them fail.
  3339. if (!Info.keepEvaluatingAfterFailure())
  3340. return false;
  3341. Success = false;
  3342. }
  3343. }
  3344. return Success;
  3345. }
  3346. // HLSL Change Starts
  3347. /// Evaluate an HLSL intrinsic call.
  3348. static bool HandleIntrinsicCall(SourceLocation CallLoc, unsigned opcode,
  3349. const LValue *This, ArrayRef<const Expr *> Args,
  3350. EvalInfo &Info, APValue &Result) {
  3351. ArgVector ArgValues(Args.size());
  3352. if (!EvaluateArgs(Args, ArgValues, Info))
  3353. return false;
  3354. if (!Info.CheckCallLimit(CallLoc))
  3355. return false;
  3356. switch ((hlsl::IntrinsicOp)opcode) {
  3357. case hlsl::IntrinsicOp::IOP_asuint:
  3358. assert(Args.size() == 1 && "else call should be invalid");
  3359. if (ArgValues[0].isInt()) {
  3360. Result = ArgValues[0];
  3361. }
  3362. else if (ArgValues[0].isFloat()) {
  3363. const bool isUnsignedTrue = true;
  3364. Result = APValue(APSInt(ArgValues[0].getFloat().bitcastToAPInt(), isUnsignedTrue));
  3365. }
  3366. else {
  3367. // TODO: consider a better error message here
  3368. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3369. return false;
  3370. }
  3371. return true;
  3372. case hlsl::IntrinsicOp::IOP_max:
  3373. assert(Args.size() == 2 && "else call should be invalid");
  3374. assert(ArgValues[0].getKind() == ArgValues[1].getKind() && "else call is invalid");
  3375. if (ArgValues[0].isInt()) {
  3376. Result = ArgValues[0].getInt() > ArgValues[1].getInt() ? ArgValues[0] : ArgValues[1];
  3377. }
  3378. else if (ArgValues[0].isFloat()) {
  3379. // TODO: handle NaNs properly
  3380. APFloat::cmpResult r = ArgValues[0].getFloat().compare(ArgValues[1].getFloat());
  3381. Result = (r == APFloat::cmpGreaterThan) ? ArgValues[0] : ArgValues[1];
  3382. }
  3383. else {
  3384. // TODO: consider a better error message here
  3385. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3386. return false;
  3387. }
  3388. return true;
  3389. default:
  3390. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3391. return false;
  3392. }
  3393. }
  3394. // HLSL Change Ends
  3395. /// Evaluate a function call.
  3396. static bool HandleFunctionCall(SourceLocation CallLoc,
  3397. const FunctionDecl *Callee, const LValue *This,
  3398. ArrayRef<const Expr*> Args, const Stmt *Body,
  3399. EvalInfo &Info, APValue &Result) {
  3400. ArgVector ArgValues(Args.size());
  3401. if (!EvaluateArgs(Args, ArgValues, Info))
  3402. return false;
  3403. if (!Info.CheckCallLimit(CallLoc))
  3404. return false;
  3405. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  3406. // For a trivial copy or move assignment, perform an APValue copy. This is
  3407. // essential for unions, where the operations performed by the assignment
  3408. // operator cannot be represented as statements.
  3409. //
  3410. // Skip this for non-union classes with no fields; in that case, the defaulted
  3411. // copy/move does not actually read the object.
  3412. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  3413. if (MD && MD->isDefaulted() &&
  3414. (MD->getParent()->isUnion() ||
  3415. (MD->isTrivial() && hasFields(MD->getParent())))) {
  3416. assert(This &&
  3417. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  3418. LValue RHS;
  3419. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3420. APValue RHSValue;
  3421. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3422. RHS, RHSValue))
  3423. return false;
  3424. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
  3425. RHSValue))
  3426. return false;
  3427. This->moveInto(Result);
  3428. return true;
  3429. }
  3430. EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
  3431. if (ESR == ESR_Succeeded) {
  3432. if (Callee->getReturnType()->isVoidType())
  3433. return true;
  3434. Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
  3435. }
  3436. return ESR == ESR_Returned;
  3437. }
  3438. /// Evaluate a constructor call.
  3439. static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
  3440. ArrayRef<const Expr*> Args,
  3441. const CXXConstructorDecl *Definition,
  3442. EvalInfo &Info, APValue &Result) {
  3443. ArgVector ArgValues(Args.size());
  3444. if (!EvaluateArgs(Args, ArgValues, Info))
  3445. return false;
  3446. if (!Info.CheckCallLimit(CallLoc))
  3447. return false;
  3448. const CXXRecordDecl *RD = Definition->getParent();
  3449. if (RD->getNumVBases()) {
  3450. Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  3451. return false;
  3452. }
  3453. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
  3454. // If it's a delegating constructor, just delegate.
  3455. if (Definition->isDelegatingConstructor()) {
  3456. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  3457. {
  3458. FullExpressionRAII InitScope(Info);
  3459. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  3460. return false;
  3461. }
  3462. return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
  3463. }
  3464. // For a trivial copy or move constructor, perform an APValue copy. This is
  3465. // essential for unions (or classes with anonymous union members), where the
  3466. // operations performed by the constructor cannot be represented by
  3467. // ctor-initializers.
  3468. //
  3469. // Skip this for empty non-union classes; we should not perform an
  3470. // lvalue-to-rvalue conversion on them because their copy constructor does not
  3471. // actually read them.
  3472. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  3473. (Definition->getParent()->isUnion() ||
  3474. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  3475. LValue RHS;
  3476. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3477. return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3478. RHS, Result);
  3479. }
  3480. // Reserve space for the struct members.
  3481. if (!RD->isUnion() && Result.isUninit())
  3482. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  3483. std::distance(RD->field_begin(), RD->field_end()));
  3484. if (RD->isInvalidDecl()) return false;
  3485. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  3486. // A scope for temporaries lifetime-extended by reference members.
  3487. BlockScopeRAII LifetimeExtendedScope(Info);
  3488. bool Success = true;
  3489. unsigned BasesSeen = 0;
  3490. #ifndef NDEBUG
  3491. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  3492. #endif
  3493. for (const auto *I : Definition->inits()) {
  3494. LValue Subobject = This;
  3495. APValue *Value = &Result;
  3496. // Determine the subobject to initialize.
  3497. FieldDecl *FD = nullptr;
  3498. if (I->isBaseInitializer()) {
  3499. QualType BaseType(I->getBaseClass(), 0);
  3500. #ifndef NDEBUG
  3501. // Non-virtual base classes are initialized in the order in the class
  3502. // definition. We have already checked for virtual base classes.
  3503. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  3504. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  3505. "base class initializers not in expected order");
  3506. ++BaseIt;
  3507. #endif
  3508. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  3509. BaseType->getAsCXXRecordDecl(), &Layout))
  3510. return false;
  3511. Value = &Result.getStructBase(BasesSeen++);
  3512. } else if ((FD = I->getMember())) {
  3513. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  3514. return false;
  3515. if (RD->isUnion()) {
  3516. Result = APValue(FD);
  3517. Value = &Result.getUnionValue();
  3518. } else {
  3519. Value = &Result.getStructField(FD->getFieldIndex());
  3520. }
  3521. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  3522. // Walk the indirect field decl's chain to find the object to initialize,
  3523. // and make sure we've initialized every step along it.
  3524. for (auto *C : IFD->chain()) {
  3525. FD = cast<FieldDecl>(C);
  3526. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  3527. // Switch the union field if it differs. This happens if we had
  3528. // preceding zero-initialization, and we're now initializing a union
  3529. // subobject other than the first.
  3530. // FIXME: In this case, the values of the other subobjects are
  3531. // specified, since zero-initialization sets all padding bits to zero.
  3532. if (Value->isUninit() ||
  3533. (Value->isUnion() && Value->getUnionField() != FD)) {
  3534. if (CD->isUnion())
  3535. *Value = APValue(FD);
  3536. else
  3537. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  3538. std::distance(CD->field_begin(), CD->field_end()));
  3539. }
  3540. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  3541. return false;
  3542. if (CD->isUnion())
  3543. Value = &Value->getUnionValue();
  3544. else
  3545. Value = &Value->getStructField(FD->getFieldIndex());
  3546. }
  3547. } else {
  3548. llvm_unreachable("unknown base initializer kind");
  3549. }
  3550. FullExpressionRAII InitScope(Info);
  3551. if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
  3552. (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
  3553. *Value, FD))) {
  3554. // If we're checking for a potential constant expression, evaluate all
  3555. // initializers even if some of them fail.
  3556. if (!Info.keepEvaluatingAfterFailure())
  3557. return false;
  3558. Success = false;
  3559. }
  3560. }
  3561. return Success &&
  3562. EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
  3563. }
  3564. //===----------------------------------------------------------------------===//
  3565. // Generic Evaluation
  3566. //===----------------------------------------------------------------------===//
  3567. namespace {
  3568. template <class Derived>
  3569. class ExprEvaluatorBase
  3570. : public ConstStmtVisitor<Derived, bool> {
  3571. private:
  3572. bool DerivedSuccess(const APValue &V, const Expr *E) {
  3573. return static_cast<Derived*>(this)->Success(V, E);
  3574. }
  3575. bool DerivedZeroInitialization(const Expr *E) {
  3576. return static_cast<Derived*>(this)->ZeroInitialization(E);
  3577. }
  3578. // Check whether a conditional operator with a non-constant condition is a
  3579. // potential constant expression. If neither arm is a potential constant
  3580. // expression, then the conditional operator is not either.
  3581. template<typename ConditionalOperator>
  3582. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  3583. assert(Info.checkingPotentialConstantExpression());
  3584. // Speculatively evaluate both arms.
  3585. {
  3586. SmallVector<PartialDiagnosticAt, 8> Diag;
  3587. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  3588. StmtVisitorTy::Visit(E->getFalseExpr());
  3589. if (Diag.empty())
  3590. return;
  3591. Diag.clear();
  3592. StmtVisitorTy::Visit(E->getTrueExpr());
  3593. if (Diag.empty())
  3594. return;
  3595. }
  3596. Error(E, diag::note_constexpr_conditional_never_const);
  3597. }
  3598. template<typename ConditionalOperator>
  3599. bool HandleConditionalOperator(const ConditionalOperator *E) {
  3600. bool BoolResult;
  3601. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  3602. if (Info.checkingPotentialConstantExpression())
  3603. CheckPotentialConstantConditional(E);
  3604. return false;
  3605. }
  3606. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  3607. return StmtVisitorTy::Visit(EvalExpr);
  3608. }
  3609. protected:
  3610. EvalInfo &Info;
  3611. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  3612. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  3613. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  3614. return Info.CCEDiag(E, D);
  3615. }
  3616. bool ZeroInitialization(const Expr *E) { return Error(E); }
  3617. public:
  3618. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  3619. EvalInfo &getEvalInfo() { return Info; }
  3620. /// Report an evaluation error. This should only be called when an error is
  3621. /// first discovered. When propagating an error, just return false.
  3622. bool Error(const Expr *E, diag::kind D) {
  3623. Info.Diag(E, D);
  3624. return false;
  3625. }
  3626. bool Error(const Expr *E) {
  3627. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  3628. }
  3629. bool VisitStmt(const Stmt *) {
  3630. llvm_unreachable("Expression evaluator should not be called on stmts");
  3631. }
  3632. bool VisitExpr(const Expr *E) {
  3633. return Error(E);
  3634. }
  3635. bool VisitParenExpr(const ParenExpr *E)
  3636. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3637. bool VisitUnaryExtension(const UnaryOperator *E)
  3638. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3639. bool VisitUnaryPlus(const UnaryOperator *E)
  3640. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3641. bool VisitChooseExpr(const ChooseExpr *E)
  3642. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  3643. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  3644. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  3645. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  3646. { return StmtVisitorTy::Visit(E->getReplacement()); }
  3647. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
  3648. { return StmtVisitorTy::Visit(E->getExpr()); }
  3649. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  3650. // The initializer may not have been parsed yet, or might be erroneous.
  3651. if (!E->getExpr())
  3652. return Error(E);
  3653. return StmtVisitorTy::Visit(E->getExpr());
  3654. }
  3655. // We cannot create any objects for which cleanups are required, so there is
  3656. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  3657. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  3658. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3659. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  3660. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  3661. return static_cast<Derived*>(this)->VisitCastExpr(E);
  3662. }
  3663. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  3664. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  3665. return static_cast<Derived*>(this)->VisitCastExpr(E);
  3666. }
  3667. bool VisitBinaryOperator(const BinaryOperator *E) {
  3668. switch (E->getOpcode()) {
  3669. default:
  3670. return Error(E);
  3671. case BO_Comma:
  3672. VisitIgnoredValue(E->getLHS());
  3673. return StmtVisitorTy::Visit(E->getRHS());
  3674. case BO_PtrMemD:
  3675. case BO_PtrMemI: {
  3676. LValue Obj;
  3677. if (!HandleMemberPointerAccess(Info, E, Obj))
  3678. return false;
  3679. APValue Result;
  3680. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  3681. return false;
  3682. return DerivedSuccess(Result, E);
  3683. }
  3684. }
  3685. }
  3686. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  3687. // Evaluate and cache the common expression. We treat it as a temporary,
  3688. // even though it's not quite the same thing.
  3689. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  3690. Info, E->getCommon()))
  3691. return false;
  3692. return HandleConditionalOperator(E);
  3693. }
  3694. bool VisitConditionalOperator(const ConditionalOperator *E) {
  3695. bool IsBcpCall = false;
  3696. // If the condition (ignoring parens) is a __builtin_constant_p call,
  3697. // the result is a constant expression if it can be folded without
  3698. // side-effects. This is an important GNU extension. See GCC PR38377
  3699. // for discussion.
  3700. if (const CallExpr *CallCE =
  3701. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  3702. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  3703. IsBcpCall = true;
  3704. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  3705. // constant expression; we can't check whether it's potentially foldable.
  3706. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  3707. return false;
  3708. FoldConstant Fold(Info, IsBcpCall);
  3709. if (!HandleConditionalOperator(E)) {
  3710. Fold.keepDiagnostics();
  3711. return false;
  3712. }
  3713. return true;
  3714. }
  3715. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  3716. if (APValue *Value = Info.CurrentCall->getTemporary(E))
  3717. return DerivedSuccess(*Value, E);
  3718. const Expr *Source = E->getSourceExpr();
  3719. if (!Source)
  3720. return Error(E);
  3721. if (Source == E) { // sanity checking.
  3722. assert(0 && "OpaqueValueExpr recursively refers to itself");
  3723. return Error(E);
  3724. }
  3725. return StmtVisitorTy::Visit(Source);
  3726. }
  3727. bool VisitCallExpr(const CallExpr *E) {
  3728. const Expr *Callee = E->getCallee()->IgnoreParens();
  3729. QualType CalleeType = Callee->getType();
  3730. const FunctionDecl *FD = nullptr;
  3731. LValue *This = nullptr, ThisVal;
  3732. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  3733. bool HasQualifier = false;
  3734. // Extract function decl and 'this' pointer from the callee.
  3735. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  3736. const ValueDecl *Member = nullptr;
  3737. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  3738. // Explicit bound member calls, such as x.f() or p->g();
  3739. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  3740. return false;
  3741. Member = ME->getMemberDecl();
  3742. This = &ThisVal;
  3743. HasQualifier = ME->hasQualifier();
  3744. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  3745. // Indirect bound member calls ('.*' or '->*').
  3746. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  3747. if (!Member) return false;
  3748. This = &ThisVal;
  3749. } else
  3750. return Error(Callee);
  3751. FD = dyn_cast<FunctionDecl>(Member);
  3752. if (!FD)
  3753. return Error(Callee);
  3754. } else if (CalleeType->isFunctionPointerType()) {
  3755. LValue Call;
  3756. if (!EvaluatePointer(Callee, Call, Info))
  3757. return false;
  3758. if (!Call.getLValueOffset().isZero())
  3759. return Error(Callee);
  3760. FD = dyn_cast_or_null<FunctionDecl>(
  3761. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  3762. if (!FD)
  3763. return Error(Callee);
  3764. // Overloaded operator calls to member functions are represented as normal
  3765. // calls with '*this' as the first argument.
  3766. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  3767. if (MD && !MD->isStatic()) {
  3768. // FIXME: When selecting an implicit conversion for an overloaded
  3769. // operator delete, we sometimes try to evaluate calls to conversion
  3770. // operators without a 'this' parameter!
  3771. if (Args.empty())
  3772. return Error(E);
  3773. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  3774. return false;
  3775. This = &ThisVal;
  3776. Args = Args.slice(1);
  3777. }
  3778. // Don't call function pointers which have been cast to some other type.
  3779. if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
  3780. return Error(E);
  3781. } else
  3782. return Error(E);
  3783. if (This && !This->checkSubobject(Info, E, CSK_This))
  3784. return false;
  3785. // HLSL Changes Start
  3786. {
  3787. unsigned opcode;
  3788. StringRef group;
  3789. if (hlsl::GetIntrinsicOp(FD, opcode, group)) {
  3790. APValue opResult;
  3791. if (!HandleIntrinsicCall(E->getExprLoc(), opcode, This, Args, Info,
  3792. opResult)) {
  3793. return false;
  3794. }
  3795. return DerivedSuccess(opResult, E);
  3796. }
  3797. }
  3798. // HLSL Changes End
  3799. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  3800. // calls to such functions in constant expressions.
  3801. if (This && !HasQualifier &&
  3802. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  3803. return Error(E, diag::note_constexpr_virtual_call);
  3804. const FunctionDecl *Definition = nullptr;
  3805. Stmt *Body = FD->getBody(Definition);
  3806. APValue Result;
  3807. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
  3808. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
  3809. Info, Result))
  3810. return false;
  3811. return DerivedSuccess(Result, E);
  3812. }
  3813. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  3814. return StmtVisitorTy::Visit(E->getInitializer());
  3815. }
  3816. bool VisitInitListExpr(const InitListExpr *E) {
  3817. if (E->getNumInits() == 0)
  3818. return DerivedZeroInitialization(E);
  3819. if (Info.getLangOpts().HLSL && !E->getType()->isScalarType() && !IsHLSLVecInitList(E)) return Error(E); // HLSL Change
  3820. if (E->getNumInits() == 1)
  3821. return StmtVisitorTy::Visit(E->getInit(0));
  3822. return Error(E);
  3823. }
  3824. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  3825. return DerivedZeroInitialization(E);
  3826. }
  3827. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  3828. return DerivedZeroInitialization(E);
  3829. }
  3830. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  3831. return DerivedZeroInitialization(E);
  3832. }
  3833. /// A member expression where the object is a prvalue is itself a prvalue.
  3834. bool VisitMemberExpr(const MemberExpr *E) {
  3835. assert(!E->isArrow() && "missing call to bound member function?");
  3836. APValue Val;
  3837. if (!Evaluate(Val, Info, E->getBase()))
  3838. return false;
  3839. QualType BaseTy = E->getBase()->getType();
  3840. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  3841. if (!FD) return Error(E);
  3842. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  3843. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  3844. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  3845. CompleteObject Obj(&Val, BaseTy);
  3846. SubobjectDesignator Designator(BaseTy);
  3847. Designator.addDeclUnchecked(FD);
  3848. APValue Result;
  3849. return extractSubobject(Info, E, Obj, Designator, Result) &&
  3850. DerivedSuccess(Result, E);
  3851. }
  3852. bool VisitCastExpr(const CastExpr *E) {
  3853. // HLSL Change Begins
  3854. if (Info.getLangOpts().HLSL) {
  3855. const auto* subExpr = E->getSubExpr();
  3856. if (subExpr->getStmtClass() == Stmt::InitListExprClass && !IsHLSLVecInitList(subExpr) && !subExpr->getType()->isScalarType())
  3857. return Error(E);
  3858. }
  3859. // HLSL Change Ends
  3860. switch (E->getCastKind()) {
  3861. default:
  3862. break;
  3863. case CK_AtomicToNonAtomic: {
  3864. APValue AtomicVal;
  3865. if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
  3866. return false;
  3867. return DerivedSuccess(AtomicVal, E);
  3868. }
  3869. case CK_NoOp:
  3870. case CK_UserDefinedConversion:
  3871. return StmtVisitorTy::Visit(E->getSubExpr());
  3872. case CK_LValueToRValue: {
  3873. LValue LVal;
  3874. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  3875. return false;
  3876. APValue RVal;
  3877. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  3878. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  3879. LVal, RVal))
  3880. return false;
  3881. return DerivedSuccess(RVal, E);
  3882. }
  3883. }
  3884. return Error(E);
  3885. }
  3886. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  3887. return VisitUnaryPostIncDec(UO);
  3888. }
  3889. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  3890. return VisitUnaryPostIncDec(UO);
  3891. }
  3892. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  3893. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  3894. return Error(UO);
  3895. LValue LVal;
  3896. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  3897. return false;
  3898. APValue RVal;
  3899. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  3900. UO->isIncrementOp(), &RVal))
  3901. return false;
  3902. return DerivedSuccess(RVal, UO);
  3903. }
  3904. bool VisitStmtExpr(const StmtExpr *E) {
  3905. // We will have checked the full-expressions inside the statement expression
  3906. // when they were completed, and don't need to check them again now.
  3907. if (Info.checkingForOverflow())
  3908. return Error(E);
  3909. BlockScopeRAII Scope(Info);
  3910. const CompoundStmt *CS = E->getSubStmt();
  3911. if (CS->body_empty())
  3912. return true;
  3913. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  3914. BE = CS->body_end();
  3915. /**/; ++BI) {
  3916. if (BI + 1 == BE) {
  3917. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  3918. if (!FinalExpr) {
  3919. Info.Diag((*BI)->getLocStart(),
  3920. diag::note_constexpr_stmt_expr_unsupported);
  3921. return false;
  3922. }
  3923. return this->Visit(FinalExpr);
  3924. }
  3925. APValue ReturnValue;
  3926. EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
  3927. if (ESR != ESR_Succeeded) {
  3928. // FIXME: If the statement-expression terminated due to 'return',
  3929. // 'break', or 'continue', it would be nice to propagate that to
  3930. // the outer statement evaluation rather than bailing out.
  3931. if (ESR != ESR_Failed)
  3932. Info.Diag((*BI)->getLocStart(),
  3933. diag::note_constexpr_stmt_expr_unsupported);
  3934. return false;
  3935. }
  3936. }
  3937. llvm_unreachable("Return from function from the loop above.");
  3938. }
  3939. /// Visit a value which is evaluated, but whose value is ignored.
  3940. void VisitIgnoredValue(const Expr *E) {
  3941. EvaluateIgnoredValue(Info, E);
  3942. }
  3943. };
  3944. }
  3945. //===----------------------------------------------------------------------===//
  3946. // Common base class for lvalue and temporary evaluation.
  3947. //===----------------------------------------------------------------------===//
  3948. namespace {
  3949. template<class Derived>
  3950. class LValueExprEvaluatorBase
  3951. : public ExprEvaluatorBase<Derived> {
  3952. protected:
  3953. LValue &Result;
  3954. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  3955. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  3956. bool Success(APValue::LValueBase B) {
  3957. Result.set(B);
  3958. return true;
  3959. }
  3960. public:
  3961. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
  3962. ExprEvaluatorBaseTy(Info), Result(Result) {}
  3963. bool Success(const APValue &V, const Expr *E) {
  3964. Result.setFrom(this->Info.Ctx, V);
  3965. return true;
  3966. }
  3967. bool VisitMemberExpr(const MemberExpr *E) {
  3968. // Handle non-static data members.
  3969. QualType BaseTy;
  3970. if (E->isArrow()) {
  3971. if (!EvaluatePointer(E->getBase(), Result, this->Info))
  3972. return false;
  3973. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  3974. } else if (E->getBase()->isRValue()) {
  3975. assert(E->getBase()->getType()->isRecordType());
  3976. if (!EvaluateTemporary(E->getBase(), Result, this->Info))
  3977. return false;
  3978. BaseTy = E->getBase()->getType();
  3979. } else {
  3980. if (!this->Visit(E->getBase()))
  3981. return false;
  3982. BaseTy = E->getBase()->getType();
  3983. }
  3984. const ValueDecl *MD = E->getMemberDecl();
  3985. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  3986. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  3987. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  3988. (void)BaseTy;
  3989. if (!HandleLValueMember(this->Info, E, Result, FD))
  3990. return false;
  3991. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  3992. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  3993. return false;
  3994. } else
  3995. return this->Error(E);
  3996. if (MD->getType()->isReferenceType()) {
  3997. APValue RefValue;
  3998. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  3999. RefValue))
  4000. return false;
  4001. return Success(RefValue, E);
  4002. }
  4003. return true;
  4004. }
  4005. bool VisitBinaryOperator(const BinaryOperator *E) {
  4006. switch (E->getOpcode()) {
  4007. default:
  4008. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4009. case BO_PtrMemD:
  4010. case BO_PtrMemI:
  4011. return HandleMemberPointerAccess(this->Info, E, Result);
  4012. }
  4013. }
  4014. bool VisitCastExpr(const CastExpr *E) {
  4015. switch (E->getCastKind()) {
  4016. default:
  4017. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4018. case CK_DerivedToBase:
  4019. case CK_UncheckedDerivedToBase:
  4020. if (!this->Visit(E->getSubExpr()))
  4021. return false;
  4022. // Now figure out the necessary offset to add to the base LV to get from
  4023. // the derived class to the base class.
  4024. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  4025. Result);
  4026. }
  4027. }
  4028. };
  4029. }
  4030. //===----------------------------------------------------------------------===//
  4031. // LValue Evaluation
  4032. //
  4033. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  4034. // function designators (in C), decl references to void objects (in C), and
  4035. // temporaries (if building with -Wno-address-of-temporary).
  4036. //
  4037. // LValue evaluation produces values comprising a base expression of one of the
  4038. // following types:
  4039. // - Declarations
  4040. // * VarDecl
  4041. // * FunctionDecl
  4042. // - Literals
  4043. // * CompoundLiteralExpr in C
  4044. // * StringLiteral
  4045. // * CXXTypeidExpr
  4046. // * PredefinedExpr
  4047. // * ObjCStringLiteralExpr
  4048. // * ObjCEncodeExpr
  4049. // * AddrLabelExpr
  4050. // * BlockExpr
  4051. // * CallExpr for a MakeStringConstant builtin
  4052. // - Locals and temporaries
  4053. // * MaterializeTemporaryExpr
  4054. // * Any Expr, with a CallIndex indicating the function in which the temporary
  4055. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  4056. // from the AST (FIXME).
  4057. // * A MaterializeTemporaryExpr that has static storage duration, with no
  4058. // CallIndex, for a lifetime-extended temporary.
  4059. // plus an offset in bytes.
  4060. //===----------------------------------------------------------------------===//
  4061. namespace {
  4062. class LValueExprEvaluator
  4063. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  4064. public:
  4065. LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
  4066. LValueExprEvaluatorBaseTy(Info, Result) {}
  4067. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  4068. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  4069. bool VisitDeclRefExpr(const DeclRefExpr *E);
  4070. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  4071. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  4072. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  4073. bool VisitMemberExpr(const MemberExpr *E);
  4074. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  4075. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  4076. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  4077. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  4078. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  4079. bool VisitUnaryDeref(const UnaryOperator *E);
  4080. bool VisitUnaryReal(const UnaryOperator *E);
  4081. bool VisitUnaryImag(const UnaryOperator *E);
  4082. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  4083. return VisitUnaryPreIncDec(UO);
  4084. }
  4085. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  4086. return VisitUnaryPreIncDec(UO);
  4087. }
  4088. bool VisitBinAssign(const BinaryOperator *BO);
  4089. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  4090. bool VisitCastExpr(const CastExpr *E) {
  4091. switch (E->getCastKind()) {
  4092. default:
  4093. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4094. case CK_LValueBitCast:
  4095. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4096. if (!Visit(E->getSubExpr()))
  4097. return false;
  4098. Result.Designator.setInvalid();
  4099. return true;
  4100. case CK_BaseToDerived:
  4101. if (!Visit(E->getSubExpr()))
  4102. return false;
  4103. return HandleBaseToDerivedCast(Info, E, Result);
  4104. }
  4105. }
  4106. };
  4107. } // end anonymous namespace
  4108. /// Evaluate an expression as an lvalue. This can be legitimately called on
  4109. /// expressions which are not glvalues, in two cases:
  4110. /// * function designators in C, and
  4111. /// * "extern void" objects
  4112. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
  4113. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  4114. E->getType()->isVoidType());
  4115. return LValueExprEvaluator(Info, Result).Visit(E);
  4116. }
  4117. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  4118. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  4119. return Success(FD);
  4120. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  4121. return VisitVarDecl(E, VD);
  4122. return Error(E);
  4123. }
  4124. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  4125. CallStackFrame *Frame = nullptr;
  4126. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
  4127. Frame = Info.CurrentCall;
  4128. if (!VD->getType()->isReferenceType()) {
  4129. if (Frame) {
  4130. Result.set(VD, Frame->Index);
  4131. return true;
  4132. }
  4133. return Success(VD);
  4134. }
  4135. APValue *V;
  4136. if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
  4137. return false;
  4138. if (V->isUninit()) {
  4139. if (!Info.checkingPotentialConstantExpression())
  4140. Info.Diag(E, diag::note_constexpr_use_uninit_reference);
  4141. return false;
  4142. }
  4143. return Success(*V, E);
  4144. }
  4145. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  4146. const MaterializeTemporaryExpr *E) {
  4147. // Walk through the expression to find the materialized temporary itself.
  4148. SmallVector<const Expr *, 2> CommaLHSs;
  4149. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4150. const Expr *Inner = E->GetTemporaryExpr()->
  4151. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  4152. // If we passed any comma operators, evaluate their LHSs.
  4153. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  4154. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  4155. return false;
  4156. // A materialized temporary with static storage duration can appear within the
  4157. // result of a constant expression evaluation, so we need to preserve its
  4158. // value for use outside this evaluation.
  4159. APValue *Value;
  4160. if (E->getStorageDuration() == SD_Static) {
  4161. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  4162. *Value = APValue();
  4163. Result.set(E);
  4164. } else {
  4165. Value = &Info.CurrentCall->
  4166. createTemporary(E, E->getStorageDuration() == SD_Automatic);
  4167. Result.set(E, Info.CurrentCall->Index);
  4168. }
  4169. QualType Type = Inner->getType();
  4170. // Materialize the temporary itself.
  4171. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  4172. (E->getStorageDuration() == SD_Static &&
  4173. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  4174. *Value = APValue();
  4175. return false;
  4176. }
  4177. // Adjust our lvalue to refer to the desired subobject.
  4178. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  4179. --I;
  4180. switch (Adjustments[I].Kind) {
  4181. case SubobjectAdjustment::DerivedToBaseAdjustment:
  4182. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  4183. Type, Result))
  4184. return false;
  4185. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  4186. break;
  4187. case SubobjectAdjustment::FieldAdjustment:
  4188. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  4189. return false;
  4190. Type = Adjustments[I].Field->getType();
  4191. break;
  4192. case SubobjectAdjustment::MemberPointerAdjustment:
  4193. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  4194. Adjustments[I].Ptr.RHS))
  4195. return false;
  4196. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  4197. break;
  4198. }
  4199. }
  4200. return true;
  4201. }
  4202. bool
  4203. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4204. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  4205. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  4206. // only see this when folding in C, so there's no standard to follow here.
  4207. return Success(E);
  4208. }
  4209. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  4210. if (!E->isPotentiallyEvaluated())
  4211. return Success(E);
  4212. Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
  4213. << E->getExprOperand()->getType()
  4214. << E->getExprOperand()->getSourceRange();
  4215. return false;
  4216. }
  4217. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4218. return Success(E);
  4219. }
  4220. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  4221. // Handle static data members.
  4222. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  4223. VisitIgnoredValue(E->getBase());
  4224. return VisitVarDecl(E, VD);
  4225. }
  4226. // Handle static member functions.
  4227. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  4228. if (MD->isStatic()) {
  4229. VisitIgnoredValue(E->getBase());
  4230. return Success(MD);
  4231. }
  4232. }
  4233. // Handle non-static data members.
  4234. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  4235. }
  4236. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  4237. // FIXME: Deal with vectors as array subscript bases.
  4238. if (E->getBase()->getType()->isVectorType())
  4239. return Error(E);
  4240. if (this->getEvalInfo().Ctx.getLangOpts().HLSL) { // HLSL Change
  4241. return Error(E); // TODO: handle arrays
  4242. } else {
  4243. if (!EvaluatePointer(E->getBase(), Result, Info))
  4244. return false;
  4245. }
  4246. APSInt Index;
  4247. if (!EvaluateInteger(E->getIdx(), Index, Info))
  4248. return false;
  4249. return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
  4250. getExtValue(Index));
  4251. }
  4252. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  4253. return EvaluatePointer(E->getSubExpr(), Result, Info);
  4254. }
  4255. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4256. if (!Visit(E->getSubExpr()))
  4257. return false;
  4258. // __real is a no-op on scalar lvalues.
  4259. if (E->getSubExpr()->getType()->isAnyComplexType())
  4260. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  4261. return true;
  4262. }
  4263. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4264. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  4265. "lvalue __imag__ on scalar?");
  4266. if (!Visit(E->getSubExpr()))
  4267. return false;
  4268. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  4269. return true;
  4270. }
  4271. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  4272. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4273. return Error(UO);
  4274. if (!this->Visit(UO->getSubExpr()))
  4275. return false;
  4276. return handleIncDec(
  4277. this->Info, UO, Result, UO->getSubExpr()->getType(),
  4278. UO->isIncrementOp(), nullptr);
  4279. }
  4280. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  4281. const CompoundAssignOperator *CAO) {
  4282. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4283. return Error(CAO);
  4284. APValue RHS;
  4285. // The overall lvalue result is the result of evaluating the LHS.
  4286. if (!this->Visit(CAO->getLHS())) {
  4287. if (Info.keepEvaluatingAfterFailure())
  4288. Evaluate(RHS, this->Info, CAO->getRHS());
  4289. return false;
  4290. }
  4291. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  4292. return false;
  4293. return handleCompoundAssignment(
  4294. this->Info, CAO,
  4295. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  4296. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  4297. }
  4298. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  4299. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4300. return Error(E);
  4301. APValue NewVal;
  4302. if (!this->Visit(E->getLHS())) {
  4303. if (Info.keepEvaluatingAfterFailure())
  4304. Evaluate(NewVal, this->Info, E->getRHS());
  4305. return false;
  4306. }
  4307. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  4308. return false;
  4309. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  4310. NewVal);
  4311. }
  4312. //===----------------------------------------------------------------------===//
  4313. // Pointer Evaluation
  4314. //===----------------------------------------------------------------------===//
  4315. namespace {
  4316. class PointerExprEvaluator
  4317. : public ExprEvaluatorBase<PointerExprEvaluator> {
  4318. LValue &Result;
  4319. bool Success(const Expr *E) {
  4320. Result.set(E);
  4321. return true;
  4322. }
  4323. public:
  4324. PointerExprEvaluator(EvalInfo &info, LValue &Result)
  4325. : ExprEvaluatorBaseTy(info), Result(Result) {}
  4326. bool Success(const APValue &V, const Expr *E) {
  4327. Result.setFrom(Info.Ctx, V);
  4328. return true;
  4329. }
  4330. bool ZeroInitialization(const Expr *E) {
  4331. return Success((Expr*)nullptr);
  4332. }
  4333. bool VisitBinaryOperator(const BinaryOperator *E);
  4334. bool VisitCastExpr(const CastExpr* E);
  4335. bool VisitUnaryAddrOf(const UnaryOperator *E);
  4336. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  4337. { return Success(E); }
  4338. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
  4339. { return Success(E); }
  4340. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  4341. { return Success(E); }
  4342. bool VisitCallExpr(const CallExpr *E);
  4343. bool VisitBlockExpr(const BlockExpr *E) {
  4344. if (!E->getBlockDecl()->hasCaptures())
  4345. return Success(E);
  4346. return Error(E);
  4347. }
  4348. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  4349. // Can't look at 'this' when checking a potential constant expression.
  4350. if (Info.checkingPotentialConstantExpression())
  4351. return false;
  4352. if (!Info.CurrentCall->This) {
  4353. if (Info.getLangOpts().CPlusPlus11)
  4354. Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
  4355. else
  4356. Info.Diag(E);
  4357. return false;
  4358. }
  4359. Result = *Info.CurrentCall->This;
  4360. return true;
  4361. }
  4362. // FIXME: Missing: @protocol, @selector
  4363. };
  4364. } // end anonymous namespace
  4365. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
  4366. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  4367. return PointerExprEvaluator(Info, Result).Visit(E);
  4368. }
  4369. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  4370. if (E->getOpcode() != BO_Add &&
  4371. E->getOpcode() != BO_Sub)
  4372. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4373. const Expr *PExp = E->getLHS();
  4374. const Expr *IExp = E->getRHS();
  4375. if (IExp->getType()->isPointerType())
  4376. std::swap(PExp, IExp);
  4377. bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
  4378. if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
  4379. return false;
  4380. llvm::APSInt Offset;
  4381. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  4382. return false;
  4383. int64_t AdditionalOffset = getExtValue(Offset);
  4384. if (E->getOpcode() == BO_Sub)
  4385. AdditionalOffset = -AdditionalOffset;
  4386. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  4387. return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
  4388. AdditionalOffset);
  4389. }
  4390. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  4391. return EvaluateLValue(E->getSubExpr(), Result, Info);
  4392. }
  4393. bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  4394. const Expr* SubExpr = E->getSubExpr();
  4395. switch (E->getCastKind()) {
  4396. default:
  4397. break;
  4398. case CK_BitCast:
  4399. case CK_CPointerToObjCPointerCast:
  4400. case CK_BlockPointerToObjCPointerCast:
  4401. case CK_AnyPointerToBlockPointerCast:
  4402. case CK_AddressSpaceConversion:
  4403. if (!Visit(SubExpr))
  4404. return false;
  4405. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  4406. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  4407. // also static_casts, but we disallow them as a resolution to DR1312.
  4408. if (!E->getType()->isVoidPointerType()) {
  4409. Result.Designator.setInvalid();
  4410. if (SubExpr->getType()->isVoidPointerType())
  4411. CCEDiag(E, diag::note_constexpr_invalid_cast)
  4412. << 3 << SubExpr->getType();
  4413. else
  4414. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4415. }
  4416. return true;
  4417. case CK_DerivedToBase:
  4418. case CK_UncheckedDerivedToBase:
  4419. if (!EvaluatePointer(E->getSubExpr(), Result, Info))
  4420. return false;
  4421. if (!Result.Base && Result.Offset.isZero())
  4422. return true;
  4423. // Now figure out the necessary offset to add to the base LV to get from
  4424. // the derived class to the base class.
  4425. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  4426. castAs<PointerType>()->getPointeeType(),
  4427. Result);
  4428. case CK_BaseToDerived:
  4429. if (!Visit(E->getSubExpr()))
  4430. return false;
  4431. if (!Result.Base && Result.Offset.isZero())
  4432. return true;
  4433. return HandleBaseToDerivedCast(Info, E, Result);
  4434. case CK_NullToPointer:
  4435. VisitIgnoredValue(E->getSubExpr());
  4436. return ZeroInitialization(E);
  4437. case CK_IntegralToPointer: {
  4438. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4439. APValue Value;
  4440. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  4441. break;
  4442. if (Value.isInt()) {
  4443. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  4444. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  4445. Result.Base = (Expr*)nullptr;
  4446. Result.Offset = CharUnits::fromQuantity(N);
  4447. Result.CallIndex = 0;
  4448. Result.Designator.setInvalid();
  4449. return true;
  4450. } else {
  4451. // Cast is of an lvalue, no need to change value.
  4452. Result.setFrom(Info.Ctx, Value);
  4453. return true;
  4454. }
  4455. }
  4456. case CK_ArrayToPointerDecay:
  4457. if (SubExpr->isGLValue()) {
  4458. if (!EvaluateLValue(SubExpr, Result, Info))
  4459. return false;
  4460. } else {
  4461. Result.set(SubExpr, Info.CurrentCall->Index);
  4462. if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
  4463. Info, Result, SubExpr))
  4464. return false;
  4465. }
  4466. // The result is a pointer to the first element of the array.
  4467. if (const ConstantArrayType *CAT
  4468. = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
  4469. Result.addArray(Info, E, CAT);
  4470. else
  4471. Result.Designator.setInvalid();
  4472. return true;
  4473. case CK_FunctionToPointerDecay:
  4474. return EvaluateLValue(SubExpr, Result, Info);
  4475. }
  4476. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4477. }
  4478. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
  4479. // C++ [expr.alignof]p3:
  4480. // When alignof is applied to a reference type, the result is the
  4481. // alignment of the referenced type.
  4482. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  4483. T = Ref->getPointeeType();
  4484. // __alignof is defined to return the preferred alignment.
  4485. return Info.Ctx.toCharUnitsFromBits(
  4486. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  4487. }
  4488. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
  4489. E = E->IgnoreParens();
  4490. // The kinds of expressions that we have special-case logic here for
  4491. // should be kept up to date with the special checks for those
  4492. // expressions in Sema.
  4493. // alignof decl is always accepted, even if it doesn't make sense: we default
  4494. // to 1 in those cases.
  4495. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4496. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  4497. /*RefAsPointee*/true);
  4498. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  4499. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  4500. /*RefAsPointee*/true);
  4501. return GetAlignOfType(Info, E->getType());
  4502. }
  4503. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  4504. if (IsStringLiteralCall(E))
  4505. return Success(E);
  4506. switch (E->getBuiltinCallee()) {
  4507. case Builtin::BI__builtin_addressof:
  4508. return EvaluateLValue(E->getArg(0), Result, Info);
  4509. case Builtin::BI__builtin_assume_aligned: {
  4510. // We need to be very careful here because: if the pointer does not have the
  4511. // asserted alignment, then the behavior is undefined, and undefined
  4512. // behavior is non-constant.
  4513. if (!EvaluatePointer(E->getArg(0), Result, Info))
  4514. return false;
  4515. LValue OffsetResult(Result);
  4516. APSInt Alignment;
  4517. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  4518. return false;
  4519. CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
  4520. if (E->getNumArgs() > 2) {
  4521. APSInt Offset;
  4522. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  4523. return false;
  4524. int64_t AdditionalOffset = -getExtValue(Offset);
  4525. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  4526. }
  4527. // If there is a base object, then it must have the correct alignment.
  4528. if (OffsetResult.Base) {
  4529. CharUnits BaseAlignment;
  4530. if (const ValueDecl *VD =
  4531. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  4532. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  4533. } else {
  4534. BaseAlignment =
  4535. GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
  4536. }
  4537. if (BaseAlignment < Align) {
  4538. Result.Designator.setInvalid();
  4539. // FIXME: Quantities here cast to integers because the plural modifier
  4540. // does not work on APSInts yet.
  4541. CCEDiag(E->getArg(0),
  4542. diag::note_constexpr_baa_insufficient_alignment) << 0
  4543. << (int) BaseAlignment.getQuantity()
  4544. << (unsigned) getExtValue(Alignment);
  4545. return false;
  4546. }
  4547. }
  4548. // The offset must also have the correct alignment.
  4549. if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
  4550. Result.Designator.setInvalid();
  4551. APSInt Offset(64, false);
  4552. Offset = OffsetResult.Offset.getQuantity();
  4553. if (OffsetResult.Base)
  4554. CCEDiag(E->getArg(0),
  4555. diag::note_constexpr_baa_insufficient_alignment) << 1
  4556. << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
  4557. else
  4558. CCEDiag(E->getArg(0),
  4559. diag::note_constexpr_baa_value_insufficient_alignment)
  4560. << Offset << (unsigned) getExtValue(Alignment);
  4561. return false;
  4562. }
  4563. return true;
  4564. }
  4565. default:
  4566. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  4567. }
  4568. }
  4569. //===----------------------------------------------------------------------===//
  4570. // Member Pointer Evaluation
  4571. //===----------------------------------------------------------------------===//
  4572. namespace {
  4573. class MemberPointerExprEvaluator
  4574. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  4575. MemberPtr &Result;
  4576. bool Success(const ValueDecl *D) {
  4577. Result = MemberPtr(D);
  4578. return true;
  4579. }
  4580. public:
  4581. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  4582. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  4583. bool Success(const APValue &V, const Expr *E) {
  4584. Result.setFrom(V);
  4585. return true;
  4586. }
  4587. bool ZeroInitialization(const Expr *E) {
  4588. return Success((const ValueDecl*)nullptr);
  4589. }
  4590. bool VisitCastExpr(const CastExpr *E);
  4591. bool VisitUnaryAddrOf(const UnaryOperator *E);
  4592. };
  4593. } // end anonymous namespace
  4594. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  4595. EvalInfo &Info) {
  4596. assert(E->isRValue() && E->getType()->isMemberPointerType());
  4597. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  4598. }
  4599. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4600. switch (E->getCastKind()) {
  4601. default:
  4602. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4603. case CK_NullToMemberPointer:
  4604. VisitIgnoredValue(E->getSubExpr());
  4605. return ZeroInitialization(E);
  4606. case CK_BaseToDerivedMemberPointer: {
  4607. if (!Visit(E->getSubExpr()))
  4608. return false;
  4609. if (E->path_empty())
  4610. return true;
  4611. // Base-to-derived member pointer casts store the path in derived-to-base
  4612. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  4613. // the wrong end of the derived->base arc, so stagger the path by one class.
  4614. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  4615. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  4616. PathI != PathE; ++PathI) {
  4617. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  4618. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  4619. if (!Result.castToDerived(Derived))
  4620. return Error(E);
  4621. }
  4622. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  4623. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  4624. return Error(E);
  4625. return true;
  4626. }
  4627. case CK_DerivedToBaseMemberPointer:
  4628. if (!Visit(E->getSubExpr()))
  4629. return false;
  4630. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  4631. PathE = E->path_end(); PathI != PathE; ++PathI) {
  4632. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  4633. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  4634. if (!Result.castToBase(Base))
  4635. return Error(E);
  4636. }
  4637. return true;
  4638. }
  4639. }
  4640. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  4641. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  4642. // member can be formed.
  4643. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  4644. }
  4645. //===----------------------------------------------------------------------===//
  4646. // Record Evaluation
  4647. //===----------------------------------------------------------------------===//
  4648. namespace {
  4649. class RecordExprEvaluator
  4650. : public ExprEvaluatorBase<RecordExprEvaluator> {
  4651. const LValue &This;
  4652. APValue &Result;
  4653. public:
  4654. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  4655. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  4656. bool Success(const APValue &V, const Expr *E) {
  4657. Result = V;
  4658. return true;
  4659. }
  4660. bool ZeroInitialization(const Expr *E);
  4661. bool VisitCastExpr(const CastExpr *E);
  4662. bool VisitInitListExpr(const InitListExpr *E);
  4663. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  4664. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  4665. };
  4666. }
  4667. /// Perform zero-initialization on an object of non-union class type.
  4668. /// C++11 [dcl.init]p5:
  4669. /// To zero-initialize an object or reference of type T means:
  4670. /// [...]
  4671. /// -- if T is a (possibly cv-qualified) non-union class type,
  4672. /// each non-static data member and each base-class subobject is
  4673. /// zero-initialized
  4674. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  4675. const RecordDecl *RD,
  4676. const LValue &This, APValue &Result) {
  4677. assert(!RD->isUnion() && "Expected non-union class type");
  4678. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  4679. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  4680. std::distance(RD->field_begin(), RD->field_end()));
  4681. if (RD->isInvalidDecl()) return false;
  4682. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4683. if (CD) {
  4684. unsigned Index = 0;
  4685. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  4686. End = CD->bases_end(); I != End; ++I, ++Index) {
  4687. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  4688. LValue Subobject = This;
  4689. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  4690. return false;
  4691. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  4692. Result.getStructBase(Index)))
  4693. return false;
  4694. }
  4695. }
  4696. for (const auto *I : RD->fields()) {
  4697. // -- if T is a reference type, no initialization is performed.
  4698. if (I->getType()->isReferenceType())
  4699. continue;
  4700. LValue Subobject = This;
  4701. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  4702. return false;
  4703. ImplicitValueInitExpr VIE(I->getType());
  4704. if (!EvaluateInPlace(
  4705. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  4706. return false;
  4707. }
  4708. return true;
  4709. }
  4710. bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
  4711. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  4712. if (RD->isInvalidDecl()) return false;
  4713. if (RD->isUnion()) {
  4714. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  4715. // object's first non-static named data member is zero-initialized
  4716. RecordDecl::field_iterator I = RD->field_begin();
  4717. if (I == RD->field_end()) {
  4718. Result = APValue((const FieldDecl*)nullptr);
  4719. return true;
  4720. }
  4721. LValue Subobject = This;
  4722. if (!HandleLValueMember(Info, E, Subobject, *I))
  4723. return false;
  4724. Result = APValue(*I);
  4725. ImplicitValueInitExpr VIE(I->getType());
  4726. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  4727. }
  4728. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  4729. Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
  4730. return false;
  4731. }
  4732. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  4733. }
  4734. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4735. switch (E->getCastKind()) {
  4736. default:
  4737. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4738. case CK_ConstructorConversion:
  4739. return Visit(E->getSubExpr());
  4740. case CK_DerivedToBase:
  4741. case CK_UncheckedDerivedToBase: {
  4742. APValue DerivedObject;
  4743. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  4744. return false;
  4745. if (!DerivedObject.isStruct())
  4746. return Error(E->getSubExpr());
  4747. // Derived-to-base rvalue conversion: just slice off the derived part.
  4748. APValue *Value = &DerivedObject;
  4749. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  4750. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  4751. PathE = E->path_end(); PathI != PathE; ++PathI) {
  4752. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  4753. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  4754. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  4755. RD = Base;
  4756. }
  4757. Result = *Value;
  4758. return true;
  4759. }
  4760. }
  4761. }
  4762. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  4763. if (Info.getLangOpts().HLSL) return false; // HLSL Change
  4764. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  4765. if (RD->isInvalidDecl()) return false;
  4766. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4767. if (RD->isUnion()) {
  4768. const FieldDecl *Field = E->getInitializedFieldInUnion();
  4769. Result = APValue(Field);
  4770. if (!Field)
  4771. return true;
  4772. // If the initializer list for a union does not contain any elements, the
  4773. // first element of the union is value-initialized.
  4774. // FIXME: The element should be initialized from an initializer list.
  4775. // Is this difference ever observable for initializer lists which
  4776. // we don't build?
  4777. ImplicitValueInitExpr VIE(Field->getType());
  4778. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  4779. LValue Subobject = This;
  4780. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  4781. return false;
  4782. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  4783. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  4784. isa<CXXDefaultInitExpr>(InitExpr));
  4785. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  4786. }
  4787. assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
  4788. "initializer list for class with base classes");
  4789. Result = APValue(APValue::UninitStruct(), 0,
  4790. std::distance(RD->field_begin(), RD->field_end()));
  4791. unsigned ElementNo = 0;
  4792. bool Success = true;
  4793. for (const auto *Field : RD->fields()) {
  4794. // Anonymous bit-fields are not considered members of the class for
  4795. // purposes of aggregate initialization.
  4796. if (Field->isUnnamedBitfield())
  4797. continue;
  4798. LValue Subobject = This;
  4799. bool HaveInit = ElementNo < E->getNumInits();
  4800. // FIXME: Diagnostics here should point to the end of the initializer
  4801. // list, not the start.
  4802. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  4803. Subobject, Field, &Layout))
  4804. return false;
  4805. // Perform an implicit value-initialization for members beyond the end of
  4806. // the initializer list.
  4807. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  4808. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  4809. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  4810. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  4811. isa<CXXDefaultInitExpr>(Init));
  4812. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  4813. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  4814. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  4815. FieldVal, Field))) {
  4816. if (!Info.keepEvaluatingAfterFailure())
  4817. return false;
  4818. Success = false;
  4819. }
  4820. }
  4821. return Success;
  4822. }
  4823. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  4824. const CXXConstructorDecl *FD = E->getConstructor();
  4825. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  4826. bool ZeroInit = E->requiresZeroInitialization();
  4827. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  4828. // If we've already performed zero-initialization, we're already done.
  4829. if (!Result.isUninit())
  4830. return true;
  4831. // We can get here in two different ways:
  4832. // 1) We're performing value-initialization, and should zero-initialize
  4833. // the object, or
  4834. // 2) We're performing default-initialization of an object with a trivial
  4835. // constexpr default constructor, in which case we should start the
  4836. // lifetimes of all the base subobjects (there can be no data member
  4837. // subobjects in this case) per [basic.life]p1.
  4838. // Either way, ZeroInitialization is appropriate.
  4839. return ZeroInitialization(E);
  4840. }
  4841. const FunctionDecl *Definition = nullptr;
  4842. FD->getBody(Definition);
  4843. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  4844. return false;
  4845. // Avoid materializing a temporary for an elidable copy/move constructor.
  4846. if (E->isElidable() && !ZeroInit)
  4847. if (const MaterializeTemporaryExpr *ME
  4848. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  4849. return Visit(ME->GetTemporaryExpr());
  4850. if (ZeroInit && !ZeroInitialization(E))
  4851. return false;
  4852. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4853. return HandleConstructorCall(E->getExprLoc(), This, Args,
  4854. cast<CXXConstructorDecl>(Definition), Info,
  4855. Result);
  4856. }
  4857. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  4858. const CXXStdInitializerListExpr *E) {
  4859. const ConstantArrayType *ArrayType =
  4860. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  4861. LValue Array;
  4862. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  4863. return false;
  4864. // Get a pointer to the first element of the array.
  4865. Array.addArray(Info, E, ArrayType);
  4866. // FIXME: Perform the checks on the field types in SemaInit.
  4867. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  4868. RecordDecl::field_iterator Field = Record->field_begin();
  4869. if (Field == Record->field_end())
  4870. return Error(E);
  4871. // Start pointer.
  4872. if (!Field->getType()->isPointerType() ||
  4873. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  4874. ArrayType->getElementType()))
  4875. return Error(E);
  4876. // FIXME: What if the initializer_list type has base classes, etc?
  4877. Result = APValue(APValue::UninitStruct(), 0, 2);
  4878. Array.moveInto(Result.getStructField(0));
  4879. if (++Field == Record->field_end())
  4880. return Error(E);
  4881. if (Field->getType()->isPointerType() &&
  4882. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  4883. ArrayType->getElementType())) {
  4884. // End pointer.
  4885. if (!HandleLValueArrayAdjustment(Info, E, Array,
  4886. ArrayType->getElementType(),
  4887. ArrayType->getSize().getZExtValue()))
  4888. return false;
  4889. Array.moveInto(Result.getStructField(1));
  4890. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  4891. // Length.
  4892. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  4893. else
  4894. return Error(E);
  4895. if (++Field != Record->field_end())
  4896. return Error(E);
  4897. return true;
  4898. }
  4899. static bool EvaluateRecord(const Expr *E, const LValue &This,
  4900. APValue &Result, EvalInfo &Info) {
  4901. assert(E->isRValue() && E->getType()->isRecordType() &&
  4902. "can't evaluate expression as a record rvalue");
  4903. return RecordExprEvaluator(Info, This, Result).Visit(E);
  4904. }
  4905. //===----------------------------------------------------------------------===//
  4906. // Temporary Evaluation
  4907. //
  4908. // Temporaries are represented in the AST as rvalues, but generally behave like
  4909. // lvalues. The full-object of which the temporary is a subobject is implicitly
  4910. // materialized so that a reference can bind to it.
  4911. //===----------------------------------------------------------------------===//
  4912. namespace {
  4913. class TemporaryExprEvaluator
  4914. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  4915. public:
  4916. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  4917. LValueExprEvaluatorBaseTy(Info, Result) {}
  4918. /// Visit an expression which constructs the value of this temporary.
  4919. bool VisitConstructExpr(const Expr *E) {
  4920. Result.set(E, Info.CurrentCall->Index);
  4921. return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
  4922. Info, Result, E);
  4923. }
  4924. bool VisitCastExpr(const CastExpr *E) {
  4925. switch (E->getCastKind()) {
  4926. default:
  4927. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4928. case CK_ConstructorConversion:
  4929. return VisitConstructExpr(E->getSubExpr());
  4930. }
  4931. }
  4932. bool VisitInitListExpr(const InitListExpr *E) {
  4933. if (Info.getLangOpts().HLSL && !IsHLSLVecInitList(E)) return Error(E); // HLSL Change
  4934. return VisitConstructExpr(E);
  4935. }
  4936. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  4937. return VisitConstructExpr(E);
  4938. }
  4939. bool VisitCallExpr(const CallExpr *E) {
  4940. return VisitConstructExpr(E);
  4941. }
  4942. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  4943. return VisitConstructExpr(E);
  4944. }
  4945. };
  4946. } // end anonymous namespace
  4947. /// Evaluate an expression of record type as a temporary.
  4948. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  4949. assert(E->isRValue() && E->getType()->isRecordType());
  4950. return TemporaryExprEvaluator(Info, Result).Visit(E);
  4951. }
  4952. //===----------------------------------------------------------------------===//
  4953. // Vector Evaluation
  4954. //===----------------------------------------------------------------------===//
  4955. namespace {
  4956. class VectorExprEvaluator
  4957. : public ExprEvaluatorBase<VectorExprEvaluator> {
  4958. APValue &Result;
  4959. public:
  4960. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  4961. : ExprEvaluatorBaseTy(info), Result(Result) {}
  4962. bool Success(const ArrayRef<APValue> &V, const Expr *E) {
  4963. // HLSL Change Begins.
  4964. const VectorType *VT = nullptr;
  4965. if (hlsl::IsHLSLVecType(E->getType())) {
  4966. VT = hlsl::ConvertHLSLVecMatTypeToExtVectorType(getEvalInfo().Ctx,
  4967. E->getType());
  4968. } else
  4969. VT = E->getType()->castAs<VectorType>();
  4970. // HLSL Change Ends.
  4971. assert(V.size() == VT->getNumElements());
  4972. // FIXME: remove this APValue copy.
  4973. Result = APValue(V.data(), V.size());
  4974. return true;
  4975. }
  4976. bool Success(const APValue &V, const Expr *E) {
  4977. assert(V.isVector());
  4978. Result = V;
  4979. return true;
  4980. }
  4981. bool ZeroInitialization(const Expr *E);
  4982. bool VisitUnaryReal(const UnaryOperator *E)
  4983. { return Visit(E->getSubExpr()); }
  4984. bool VisitCastExpr(const CastExpr* E);
  4985. bool VisitInitListExpr(const InitListExpr *E);
  4986. bool VisitHLSLVectorElementExpr(const HLSLVectorElementExpr *E);
  4987. bool VisitUnaryImag(const UnaryOperator *E);
  4988. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  4989. // binary comparisons, binary and/or/xor,
  4990. // shufflevector, ExtVectorElementExpr
  4991. };
  4992. } // end anonymous namespace
  4993. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  4994. assert(E->isRValue() && (E->getType()->isVectorType() || hlsl::IsHLSLVecType(E->getType())) &&"not a vector rvalue"); // HLSL Change
  4995. return VectorExprEvaluator(Info, Result).Visit(E);
  4996. }
  4997. bool VectorExprEvaluator::VisitHLSLVectorElementExpr(
  4998. const HLSLVectorElementExpr *E) {
  4999. SmallVector<APValue, 4> Elts;
  5000. const Expr *baseExpr = E->getBase();
  5001. // Handling cases where HLSLVectorElement access into constant vector.
  5002. // For example: float4 a = (0.0).xxxx;
  5003. if (Evaluate(Result, Info, baseExpr) && !Info.EvalStatus.HasSideEffects &&
  5004. Result.getKind() == APValue::ValueKind::Vector) {
  5005. hlsl::VectorMemberAccessPositions accessor = E->getEncodedElementAccess();
  5006. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5007. uint32_t selector;
  5008. accessor.GetPosition(i, &selector);
  5009. Elts.push_back(Result.getVectorElt(selector));
  5010. }
  5011. return Success(Elts, E);
  5012. }
  5013. // TODO: Other cases may be added for other APValue::ValueKind.
  5014. return false;
  5015. }
  5016. bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
  5017. // HLSL Change Begins.
  5018. const VectorType *VTy;
  5019. if (Info.getLangOpts().HLSL && hlsl::IsHLSLVecType(E->getType())) {
  5020. VTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(getEvalInfo().Ctx, E->getType());
  5021. } else {
  5022. VTy = E->getType()->castAs<VectorType>();
  5023. }
  5024. // HLSL Change Ends.
  5025. unsigned NElts = VTy->getNumElements();
  5026. const Expr *SE = E->getSubExpr();
  5027. QualType SETy = SE->getType();
  5028. switch (E->getCastKind()) {
  5029. // HLSL Change Begins.
  5030. case CK_HLSLCC_FloatingCast: {
  5031. if (!Visit(SE))
  5032. return Error(E);
  5033. SmallVector<APValue, 4> Elts;
  5034. for (uint32_t i = 0; i < Result.getVectorLength(); ++i) {
  5035. APValue Elem = Result.getVectorElt(i);
  5036. HandleFloatToFloatCast(
  5037. Info, E, hlsl::GetHLSLVecElementType(SE->getType()),
  5038. hlsl::GetHLSLVecElementType(E->getType()), Elem.getFloat());
  5039. Elts.push_back(Elem);
  5040. }
  5041. const auto EltsSize = Elts.size();
  5042. return Success(Elts, E);
  5043. }
  5044. case CK_HLSLCC_IntegralToFloating: {
  5045. if (!Visit(SE))
  5046. return Error(E);
  5047. SmallVector<APValue, 4> Elts;
  5048. for (uint32_t i = 0; i < Result.getVectorLength(); ++i) {
  5049. APFloat ElemFloat(0.0);
  5050. HandleIntToFloatCast(Info, E, hlsl::GetHLSLVecElementType(SE->getType()),
  5051. Result.getVectorElt(i).getInt(),
  5052. hlsl::GetHLSLVecElementType(E->getType()),
  5053. ElemFloat);
  5054. Elts.push_back(APValue(ElemFloat));
  5055. }
  5056. const auto EltsSize = Elts.size();
  5057. return Success(Elts, E);
  5058. }
  5059. case CK_HLSLCC_FloatingToIntegral: {
  5060. if (!Visit(SE))
  5061. return Error(E);
  5062. SmallVector<APValue, 4> Elts;
  5063. for (uint32_t i = 0; i < Result.getVectorLength(); ++i) {
  5064. APSInt ElemInt;
  5065. HandleFloatToIntCast(Info, E, hlsl::GetHLSLVecElementType(SE->getType()),
  5066. Result.getVectorElt(i).getFloat(),
  5067. hlsl::GetHLSLVecElementType(E->getType()), ElemInt);
  5068. Elts.push_back(APValue(ElemInt));
  5069. }
  5070. return Success(Elts, E);
  5071. }
  5072. // HLSL Change Ends.
  5073. case CK_HLSLVectorSplat: // HLSL Change
  5074. case CK_VectorSplat: {
  5075. APValue Val = APValue();
  5076. if (SETy->isIntegerType()) {
  5077. APSInt IntResult;
  5078. if (!EvaluateInteger(SE, IntResult, Info))
  5079. return false;
  5080. Val = APValue(IntResult);
  5081. } else if (SETy->isRealFloatingType()) {
  5082. APFloat F(0.0);
  5083. if (!EvaluateFloat(SE, F, Info))
  5084. return false;
  5085. Val = APValue(F);
  5086. } else {
  5087. return Error(E);
  5088. }
  5089. // Splat and create vector APValue.
  5090. SmallVector<APValue, 4> Elts(NElts, Val);
  5091. return Success(Elts, E);
  5092. }
  5093. case CK_BitCast: {
  5094. // Evaluate the operand into an APInt we can extract from.
  5095. llvm::APInt SValInt;
  5096. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  5097. return false;
  5098. // Extract the elements
  5099. QualType EltTy = VTy->getElementType();
  5100. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  5101. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  5102. SmallVector<APValue, 4> Elts;
  5103. if (EltTy->isRealFloatingType()) {
  5104. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  5105. unsigned FloatEltSize = EltSize;
  5106. if (&Sem == &APFloat::x87DoubleExtended)
  5107. FloatEltSize = 80;
  5108. for (unsigned i = 0; i < NElts; i++) {
  5109. llvm::APInt Elt;
  5110. if (BigEndian)
  5111. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  5112. else
  5113. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  5114. Elts.push_back(APValue(APFloat(Sem, Elt)));
  5115. }
  5116. } else if (EltTy->isIntegerType()) {
  5117. for (unsigned i = 0; i < NElts; i++) {
  5118. llvm::APInt Elt;
  5119. if (BigEndian)
  5120. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  5121. else
  5122. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  5123. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  5124. }
  5125. } else {
  5126. return Error(E);
  5127. }
  5128. return Success(Elts, E);
  5129. }
  5130. default:
  5131. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5132. }
  5133. }
  5134. bool
  5135. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5136. // HLSL Change Begins.
  5137. if (Info.getLangOpts().HLSL) {
  5138. QualType Ty = E->getType();
  5139. if (!hlsl::IsHLSLVecType(Ty))
  5140. return Error(E); // HLSL Change
  5141. unsigned vecSize = hlsl::GetHLSLVecSize(Ty);
  5142. // TODO: support all cases.
  5143. if (E->getNumInits() != vecSize)
  5144. return Error(E); // HLSL Change
  5145. }
  5146. // HLSL Change Ends.
  5147. const VectorType *VT = nullptr;
  5148. // HLSL Change Begins.
  5149. if (hlsl::IsHLSLVecType(E->getType())) {
  5150. VT = hlsl::ConvertHLSLVecMatTypeToExtVectorType(getEvalInfo().Ctx,
  5151. E->getType());
  5152. } else
  5153. VT = E->getType()->castAs<VectorType>();
  5154. // HLSL Change Ends.
  5155. unsigned NumInits = E->getNumInits();
  5156. unsigned NumElements = VT->getNumElements();
  5157. QualType EltTy = VT->getElementType();
  5158. SmallVector<APValue, 4> Elements;
  5159. // The number of initializers can be less than the number of
  5160. // vector elements. For OpenCL, this can be due to nested vector
  5161. // initialization. For GCC compatibility, missing trailing elements
  5162. // should be initialized with zeroes.
  5163. unsigned CountInits = 0, CountElts = 0;
  5164. while (CountElts < NumElements) {
  5165. // Handle nested vector initialization.
  5166. if (CountInits < NumInits
  5167. && (E->getInit(CountInits)->getType()->isVectorType() ||
  5168. // HLSL Change Begins.
  5169. (Info.getLangOpts().HLSL &&
  5170. hlsl::IsHLSLVecType(E->getInit(CountInits)->getType())))) {
  5171. // HLSL Change Ends.
  5172. APValue v;
  5173. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  5174. return Error(E);
  5175. unsigned vlen = v.getVectorLength();
  5176. for (unsigned j = 0; j < vlen; j++)
  5177. Elements.push_back(v.getVectorElt(j));
  5178. CountElts += vlen;
  5179. } else if (EltTy->isIntegerType()) {
  5180. llvm::APSInt sInt(32);
  5181. if (CountInits < NumInits) {
  5182. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  5183. return false;
  5184. } else // trailing integer zero.
  5185. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  5186. Elements.push_back(APValue(sInt));
  5187. CountElts++;
  5188. } else {
  5189. llvm::APFloat f(0.0);
  5190. if (CountInits < NumInits) {
  5191. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  5192. return false;
  5193. } else // trailing float zero.
  5194. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  5195. Elements.push_back(APValue(f));
  5196. CountElts++;
  5197. }
  5198. CountInits++;
  5199. }
  5200. return Success(Elements, E);
  5201. }
  5202. bool
  5203. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  5204. const VectorType *VT = E->getType()->getAs<VectorType>();
  5205. QualType EltTy = VT->getElementType();
  5206. APValue ZeroElement;
  5207. if (EltTy->isIntegerType())
  5208. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  5209. else
  5210. ZeroElement =
  5211. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  5212. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  5213. return Success(Elements, E);
  5214. }
  5215. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  5216. VisitIgnoredValue(E->getSubExpr());
  5217. return ZeroInitialization(E);
  5218. }
  5219. //===----------------------------------------------------------------------===//
  5220. // Array Evaluation
  5221. //===----------------------------------------------------------------------===//
  5222. namespace {
  5223. class ArrayExprEvaluator
  5224. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  5225. const LValue &This;
  5226. APValue &Result;
  5227. public:
  5228. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  5229. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  5230. bool Success(const APValue &V, const Expr *E) {
  5231. assert((V.isArray() || V.isLValue()) &&
  5232. "expected array or string literal");
  5233. Result = V;
  5234. return true;
  5235. }
  5236. bool ZeroInitialization(const Expr *E) {
  5237. const ConstantArrayType *CAT =
  5238. Info.Ctx.getAsConstantArrayType(E->getType());
  5239. if (!CAT)
  5240. return Error(E);
  5241. Result = APValue(APValue::UninitArray(), 0,
  5242. CAT->getSize().getZExtValue());
  5243. if (!Result.hasArrayFiller()) return true;
  5244. // Zero-initialize all elements.
  5245. LValue Subobject = This;
  5246. Subobject.addArray(Info, E, CAT);
  5247. ImplicitValueInitExpr VIE(CAT->getElementType());
  5248. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  5249. }
  5250. bool VisitInitListExpr(const InitListExpr *E);
  5251. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  5252. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  5253. const LValue &Subobject,
  5254. APValue *Value, QualType Type);
  5255. };
  5256. } // end anonymous namespace
  5257. static bool EvaluateArray(const Expr *E, const LValue &This,
  5258. APValue &Result, EvalInfo &Info) {
  5259. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  5260. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  5261. }
  5262. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5263. if (Info.getLangOpts().HLSL) return Error(E); // HLSL Change
  5264. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  5265. if (!CAT)
  5266. return Error(E);
  5267. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  5268. // an appropriately-typed string literal enclosed in braces.
  5269. if (E->isStringLiteralInit()) {
  5270. LValue LV;
  5271. if (!EvaluateLValue(E->getInit(0), LV, Info))
  5272. return false;
  5273. APValue Val;
  5274. LV.moveInto(Val);
  5275. return Success(Val, E);
  5276. }
  5277. bool Success = true;
  5278. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  5279. "zero-initialized array shouldn't have any initialized elts");
  5280. APValue Filler;
  5281. if (Result.isArray() && Result.hasArrayFiller())
  5282. Filler = Result.getArrayFiller();
  5283. unsigned NumEltsToInit = E->getNumInits();
  5284. unsigned NumElts = CAT->getSize().getZExtValue();
  5285. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  5286. // If the initializer might depend on the array index, run it for each
  5287. // array element. For now, just whitelist non-class value-initialization.
  5288. if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
  5289. NumEltsToInit = NumElts;
  5290. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  5291. // If the array was previously zero-initialized, preserve the
  5292. // zero-initialized values.
  5293. if (!Filler.isUninit()) {
  5294. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  5295. Result.getArrayInitializedElt(I) = Filler;
  5296. if (Result.hasArrayFiller())
  5297. Result.getArrayFiller() = Filler;
  5298. }
  5299. LValue Subobject = This;
  5300. Subobject.addArray(Info, E, CAT);
  5301. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  5302. const Expr *Init =
  5303. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  5304. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  5305. Info, Subobject, Init) ||
  5306. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  5307. CAT->getElementType(), 1)) {
  5308. if (!Info.keepEvaluatingAfterFailure())
  5309. return false;
  5310. Success = false;
  5311. }
  5312. }
  5313. if (!Result.hasArrayFiller())
  5314. return Success;
  5315. // If we get here, we have a trivial filler, which we can just evaluate
  5316. // once and splat over the rest of the array elements.
  5317. assert(FillerExpr && "no array filler for incomplete init list");
  5318. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  5319. FillerExpr) && Success;
  5320. }
  5321. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5322. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  5323. }
  5324. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5325. const LValue &Subobject,
  5326. APValue *Value,
  5327. QualType Type) {
  5328. bool HadZeroInit = !Value->isUninit();
  5329. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  5330. unsigned N = CAT->getSize().getZExtValue();
  5331. // Preserve the array filler if we had prior zero-initialization.
  5332. APValue Filler =
  5333. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  5334. : APValue();
  5335. *Value = APValue(APValue::UninitArray(), N, N);
  5336. if (HadZeroInit)
  5337. for (unsigned I = 0; I != N; ++I)
  5338. Value->getArrayInitializedElt(I) = Filler;
  5339. // Initialize the elements.
  5340. LValue ArrayElt = Subobject;
  5341. ArrayElt.addArray(Info, E, CAT);
  5342. for (unsigned I = 0; I != N; ++I)
  5343. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  5344. CAT->getElementType()) ||
  5345. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  5346. CAT->getElementType(), 1))
  5347. return false;
  5348. return true;
  5349. }
  5350. if (!Type->isRecordType())
  5351. return Error(E);
  5352. const CXXConstructorDecl *FD = E->getConstructor();
  5353. bool ZeroInit = E->requiresZeroInitialization();
  5354. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  5355. if (HadZeroInit)
  5356. return true;
  5357. // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
  5358. ImplicitValueInitExpr VIE(Type);
  5359. return EvaluateInPlace(*Value, Info, Subobject, &VIE);
  5360. }
  5361. const FunctionDecl *Definition = nullptr;
  5362. FD->getBody(Definition);
  5363. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  5364. return false;
  5365. if (ZeroInit && !HadZeroInit) {
  5366. ImplicitValueInitExpr VIE(Type);
  5367. if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
  5368. return false;
  5369. }
  5370. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5371. return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
  5372. cast<CXXConstructorDecl>(Definition),
  5373. Info, *Value);
  5374. }
  5375. //===----------------------------------------------------------------------===//
  5376. // Integer Evaluation
  5377. //
  5378. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  5379. // types and back in constant folding. Integer values are thus represented
  5380. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  5381. //===----------------------------------------------------------------------===//
  5382. namespace {
  5383. class IntExprEvaluator
  5384. : public ExprEvaluatorBase<IntExprEvaluator> {
  5385. APValue &Result;
  5386. public:
  5387. IntExprEvaluator(EvalInfo &info, APValue &result)
  5388. : ExprEvaluatorBaseTy(info), Result(result) {}
  5389. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  5390. assert(E->getType()->isIntegralOrEnumerationType() &&
  5391. "Invalid evaluation result.");
  5392. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  5393. "Invalid evaluation result.");
  5394. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  5395. "Invalid evaluation result.");
  5396. Result = APValue(SI);
  5397. return true;
  5398. }
  5399. bool Success(const llvm::APSInt &SI, const Expr *E) {
  5400. return Success(SI, E, Result);
  5401. }
  5402. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  5403. assert(E->getType()->isIntegralOrEnumerationType() &&
  5404. "Invalid evaluation result.");
  5405. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  5406. "Invalid evaluation result.");
  5407. Result = APValue(APSInt(I));
  5408. Result.getInt().setIsUnsigned(
  5409. E->getType()->isUnsignedIntegerOrEnumerationType());
  5410. return true;
  5411. }
  5412. bool Success(const llvm::APInt &I, const Expr *E) {
  5413. return Success(I, E, Result);
  5414. }
  5415. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  5416. assert(E->getType()->isIntegralOrEnumerationType() &&
  5417. "Invalid evaluation result.");
  5418. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  5419. return true;
  5420. }
  5421. bool Success(uint64_t Value, const Expr *E) {
  5422. return Success(Value, E, Result);
  5423. }
  5424. bool Success(CharUnits Size, const Expr *E) {
  5425. return Success(Size.getQuantity(), E);
  5426. }
  5427. bool Success(const APValue &V, const Expr *E) {
  5428. if (V.isLValue() || V.isAddrLabelDiff()) {
  5429. Result = V;
  5430. return true;
  5431. }
  5432. return Success(V.getInt(), E);
  5433. }
  5434. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  5435. //===--------------------------------------------------------------------===//
  5436. // Visitor Methods
  5437. //===--------------------------------------------------------------------===//
  5438. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  5439. return Success(E->getValue(), E);
  5440. }
  5441. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  5442. return Success(E->getValue(), E);
  5443. }
  5444. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  5445. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5446. if (CheckReferencedDecl(E, E->getDecl()))
  5447. return true;
  5448. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  5449. }
  5450. bool VisitMemberExpr(const MemberExpr *E) {
  5451. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  5452. VisitIgnoredValue(E->getBase());
  5453. return true;
  5454. }
  5455. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  5456. }
  5457. bool VisitCallExpr(const CallExpr *E);
  5458. bool VisitBinaryOperator(const BinaryOperator *E);
  5459. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  5460. bool VisitUnaryOperator(const UnaryOperator *E);
  5461. bool VisitCastExpr(const CastExpr* E);
  5462. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  5463. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  5464. return Success(E->getValue(), E);
  5465. }
  5466. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  5467. return Success(E->getValue(), E);
  5468. }
  5469. // Note, GNU defines __null as an integer, not a pointer.
  5470. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  5471. return ZeroInitialization(E);
  5472. }
  5473. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  5474. return Success(E->getValue(), E);
  5475. }
  5476. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  5477. return Success(E->getValue(), E);
  5478. }
  5479. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  5480. return Success(E->getValue(), E);
  5481. }
  5482. bool VisitUnaryReal(const UnaryOperator *E);
  5483. bool VisitUnaryImag(const UnaryOperator *E);
  5484. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  5485. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  5486. private:
  5487. static QualType GetObjectType(APValue::LValueBase B);
  5488. bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
  5489. // FIXME: Missing: array subscript of vector, member of vector
  5490. };
  5491. } // end anonymous namespace
  5492. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  5493. /// produce either the integer value or a pointer.
  5494. ///
  5495. /// GCC has a heinous extension which folds casts between pointer types and
  5496. /// pointer-sized integral types. We support this by allowing the evaluation of
  5497. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  5498. /// Some simple arithmetic on such values is supported (they are treated much
  5499. /// like char*).
  5500. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  5501. EvalInfo &Info) {
  5502. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  5503. return IntExprEvaluator(Info, Result).Visit(E);
  5504. }
  5505. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  5506. APValue Val;
  5507. if (!EvaluateIntegerOrLValue(E, Val, Info))
  5508. return false;
  5509. if (!Val.isInt()) {
  5510. // FIXME: It would be better to produce the diagnostic for casting
  5511. // a pointer to an integer.
  5512. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  5513. return false;
  5514. }
  5515. Result = Val.getInt();
  5516. return true;
  5517. }
  5518. /// Check whether the given declaration can be directly converted to an integral
  5519. /// rvalue. If not, no diagnostic is produced; there are other things we can
  5520. /// try.
  5521. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  5522. // Enums are integer constant exprs.
  5523. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  5524. // Check for signedness/width mismatches between E type and ECD value.
  5525. bool SameSign = (ECD->getInitVal().isSigned()
  5526. == E->getType()->isSignedIntegerOrEnumerationType());
  5527. bool SameWidth = (ECD->getInitVal().getBitWidth()
  5528. == Info.Ctx.getIntWidth(E->getType()));
  5529. if (SameSign && SameWidth)
  5530. return Success(ECD->getInitVal(), E);
  5531. else {
  5532. // Get rid of mismatch (otherwise Success assertions will fail)
  5533. // by computing a new value matching the type of E.
  5534. llvm::APSInt Val = ECD->getInitVal();
  5535. if (!SameSign)
  5536. Val.setIsSigned(!ECD->getInitVal().isSigned());
  5537. if (!SameWidth)
  5538. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  5539. return Success(Val, E);
  5540. }
  5541. }
  5542. return false;
  5543. }
  5544. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  5545. /// as GCC.
  5546. static int EvaluateBuiltinClassifyType(const CallExpr *E) {
  5547. // The following enum mimics the values returned by GCC.
  5548. // FIXME: Does GCC differ between lvalue and rvalue references here?
  5549. enum gcc_type_class {
  5550. no_type_class = -1,
  5551. void_type_class, integer_type_class, char_type_class,
  5552. enumeral_type_class, boolean_type_class,
  5553. pointer_type_class, reference_type_class, offset_type_class,
  5554. real_type_class, complex_type_class,
  5555. function_type_class, method_type_class,
  5556. record_type_class, union_type_class,
  5557. array_type_class, string_type_class,
  5558. lang_type_class
  5559. };
  5560. // If no argument was supplied, default to "no_type_class". This isn't
  5561. // ideal, however it is what gcc does.
  5562. if (E->getNumArgs() == 0)
  5563. return no_type_class;
  5564. QualType ArgTy = E->getArg(0)->getType();
  5565. if (ArgTy->isVoidType())
  5566. return void_type_class;
  5567. else if (ArgTy->isEnumeralType())
  5568. return enumeral_type_class;
  5569. else if (ArgTy->isBooleanType())
  5570. return boolean_type_class;
  5571. else if (ArgTy->isCharType())
  5572. return string_type_class; // gcc doesn't appear to use char_type_class
  5573. else if (ArgTy->isIntegerType())
  5574. return integer_type_class;
  5575. else if (ArgTy->isPointerType())
  5576. return pointer_type_class;
  5577. else if (ArgTy->isReferenceType())
  5578. return reference_type_class;
  5579. else if (ArgTy->isRealType())
  5580. return real_type_class;
  5581. else if (ArgTy->isComplexType())
  5582. return complex_type_class;
  5583. else if (ArgTy->isFunctionType())
  5584. return function_type_class;
  5585. else if (ArgTy->isStructureOrClassType())
  5586. return record_type_class;
  5587. else if (ArgTy->isUnionType())
  5588. return union_type_class;
  5589. else if (ArgTy->isArrayType())
  5590. return array_type_class;
  5591. else if (ArgTy->isUnionType())
  5592. return union_type_class;
  5593. else // FIXME: offset_type_class, method_type_class, & lang_type_class?
  5594. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  5595. }
  5596. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  5597. /// __builtin_constant_p when applied to the given lvalue.
  5598. ///
  5599. /// An lvalue is only "constant" if it is a pointer or reference to the first
  5600. /// character of a string literal.
  5601. template<typename LValue>
  5602. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  5603. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  5604. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  5605. }
  5606. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  5607. /// GCC as we can manage.
  5608. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  5609. QualType ArgType = Arg->getType();
  5610. // __builtin_constant_p always has one operand. The rules which gcc follows
  5611. // are not precisely documented, but are as follows:
  5612. //
  5613. // - If the operand is of integral, floating, complex or enumeration type,
  5614. // and can be folded to a known value of that type, it returns 1.
  5615. // - If the operand and can be folded to a pointer to the first character
  5616. // of a string literal (or such a pointer cast to an integral type), it
  5617. // returns 1.
  5618. //
  5619. // Otherwise, it returns 0.
  5620. //
  5621. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  5622. // its support for this does not currently work.
  5623. if (ArgType->isIntegralOrEnumerationType()) {
  5624. Expr::EvalResult Result;
  5625. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  5626. return false;
  5627. APValue &V = Result.Val;
  5628. if (V.getKind() == APValue::Int)
  5629. return true;
  5630. return EvaluateBuiltinConstantPForLValue(V);
  5631. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  5632. return Arg->isEvaluatable(Ctx);
  5633. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  5634. LValue LV;
  5635. Expr::EvalStatus Status;
  5636. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  5637. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  5638. : EvaluatePointer(Arg, LV, Info)) &&
  5639. !Status.HasSideEffects)
  5640. return EvaluateBuiltinConstantPForLValue(LV);
  5641. }
  5642. // Anything else isn't considered to be sufficiently constant.
  5643. return false;
  5644. }
  5645. /// Retrieves the "underlying object type" of the given expression,
  5646. /// as used by __builtin_object_size.
  5647. QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
  5648. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  5649. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  5650. return VD->getType();
  5651. } else if (const Expr *E = B.get<const Expr*>()) {
  5652. if (isa<CompoundLiteralExpr>(E))
  5653. return E->getType();
  5654. }
  5655. return QualType();
  5656. }
  5657. bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
  5658. LValue Base;
  5659. {
  5660. // The operand of __builtin_object_size is never evaluated for side-effects.
  5661. // If there are any, but we can determine the pointed-to object anyway, then
  5662. // ignore the side-effects.
  5663. SpeculativeEvaluationRAII SpeculativeEval(Info);
  5664. if (!EvaluatePointer(E->getArg(0), Base, Info))
  5665. return false;
  5666. }
  5667. if (!Base.getLValueBase()) {
  5668. // It is not possible to determine which objects ptr points to at compile time,
  5669. // __builtin_object_size should return (size_t) -1 for type 0 or 1
  5670. // and (size_t) 0 for type 2 or 3.
  5671. llvm::APSInt TypeIntVaue;
  5672. const Expr *ExprType = E->getArg(1);
  5673. if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
  5674. return false;
  5675. if (TypeIntVaue == 0 || TypeIntVaue == 1)
  5676. return Success(-1, E);
  5677. if (TypeIntVaue == 2 || TypeIntVaue == 3)
  5678. return Success(0, E);
  5679. return Error(E);
  5680. }
  5681. QualType T = GetObjectType(Base.getLValueBase());
  5682. if (T.isNull() ||
  5683. T->isIncompleteType() ||
  5684. T->isFunctionType() ||
  5685. T->isVariablyModifiedType() ||
  5686. T->isDependentType())
  5687. return Error(E);
  5688. CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
  5689. CharUnits Offset = Base.getLValueOffset();
  5690. if (!Offset.isNegative() && Offset <= Size)
  5691. Size -= Offset;
  5692. else
  5693. Size = CharUnits::Zero();
  5694. return Success(Size, E);
  5695. }
  5696. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  5697. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  5698. default:
  5699. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  5700. case Builtin::BI__builtin_object_size: {
  5701. if (TryEvaluateBuiltinObjectSize(E))
  5702. return true;
  5703. // If evaluating the argument has side-effects, we can't determine the size
  5704. // of the object, and so we lower it to unknown now. CodeGen relies on us to
  5705. // handle all cases where the expression has side-effects.
  5706. if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
  5707. if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
  5708. return Success(-1ULL, E);
  5709. return Success(0, E);
  5710. }
  5711. // Expression had no side effects, but we couldn't statically determine the
  5712. // size of the referenced object.
  5713. switch (Info.EvalMode) {
  5714. case EvalInfo::EM_ConstantExpression:
  5715. case EvalInfo::EM_PotentialConstantExpression:
  5716. case EvalInfo::EM_ConstantFold:
  5717. case EvalInfo::EM_EvaluateForOverflow:
  5718. case EvalInfo::EM_IgnoreSideEffects:
  5719. return Error(E);
  5720. case EvalInfo::EM_ConstantExpressionUnevaluated:
  5721. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  5722. return Success(-1ULL, E);
  5723. }
  5724. }
  5725. case Builtin::BI__builtin_bswap16:
  5726. case Builtin::BI__builtin_bswap32:
  5727. case Builtin::BI__builtin_bswap64: {
  5728. APSInt Val;
  5729. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5730. return false;
  5731. return Success(Val.byteSwap(), E);
  5732. }
  5733. case Builtin::BI__builtin_classify_type:
  5734. return Success(EvaluateBuiltinClassifyType(E), E);
  5735. // FIXME: BI__builtin_clrsb
  5736. // FIXME: BI__builtin_clrsbl
  5737. // FIXME: BI__builtin_clrsbll
  5738. case Builtin::BI__builtin_clz:
  5739. case Builtin::BI__builtin_clzl:
  5740. case Builtin::BI__builtin_clzll:
  5741. case Builtin::BI__builtin_clzs: {
  5742. APSInt Val;
  5743. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5744. return false;
  5745. if (!Val)
  5746. return Error(E);
  5747. return Success(Val.countLeadingZeros(), E);
  5748. }
  5749. case Builtin::BI__builtin_constant_p:
  5750. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  5751. case Builtin::BI__builtin_ctz:
  5752. case Builtin::BI__builtin_ctzl:
  5753. case Builtin::BI__builtin_ctzll:
  5754. case Builtin::BI__builtin_ctzs: {
  5755. APSInt Val;
  5756. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5757. return false;
  5758. if (!Val)
  5759. return Error(E);
  5760. return Success(Val.countTrailingZeros(), E);
  5761. }
  5762. case Builtin::BI__builtin_eh_return_data_regno: {
  5763. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  5764. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  5765. return Success(Operand, E);
  5766. }
  5767. case Builtin::BI__builtin_expect:
  5768. return Visit(E->getArg(0));
  5769. case Builtin::BI__builtin_ffs:
  5770. case Builtin::BI__builtin_ffsl:
  5771. case Builtin::BI__builtin_ffsll: {
  5772. APSInt Val;
  5773. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5774. return false;
  5775. unsigned N = Val.countTrailingZeros();
  5776. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  5777. }
  5778. case Builtin::BI__builtin_fpclassify: {
  5779. APFloat Val(0.0);
  5780. if (!EvaluateFloat(E->getArg(5), Val, Info))
  5781. return false;
  5782. unsigned Arg;
  5783. switch (Val.getCategory()) {
  5784. case APFloat::fcNaN: Arg = 0; break;
  5785. case APFloat::fcInfinity: Arg = 1; break;
  5786. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  5787. case APFloat::fcZero: Arg = 4; break;
  5788. }
  5789. return Visit(E->getArg(Arg));
  5790. }
  5791. case Builtin::BI__builtin_isinf_sign: {
  5792. APFloat Val(0.0);
  5793. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5794. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  5795. }
  5796. case Builtin::BI__builtin_isinf: {
  5797. APFloat Val(0.0);
  5798. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5799. Success(Val.isInfinity() ? 1 : 0, E);
  5800. }
  5801. case Builtin::BI__builtin_isfinite: {
  5802. APFloat Val(0.0);
  5803. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5804. Success(Val.isFinite() ? 1 : 0, E);
  5805. }
  5806. case Builtin::BI__builtin_isnan: {
  5807. APFloat Val(0.0);
  5808. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5809. Success(Val.isNaN() ? 1 : 0, E);
  5810. }
  5811. case Builtin::BI__builtin_isnormal: {
  5812. APFloat Val(0.0);
  5813. return EvaluateFloat(E->getArg(0), Val, Info) &&
  5814. Success(Val.isNormal() ? 1 : 0, E);
  5815. }
  5816. case Builtin::BI__builtin_parity:
  5817. case Builtin::BI__builtin_parityl:
  5818. case Builtin::BI__builtin_parityll: {
  5819. APSInt Val;
  5820. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5821. return false;
  5822. return Success(Val.countPopulation() % 2, E);
  5823. }
  5824. case Builtin::BI__builtin_popcount:
  5825. case Builtin::BI__builtin_popcountl:
  5826. case Builtin::BI__builtin_popcountll: {
  5827. APSInt Val;
  5828. if (!EvaluateInteger(E->getArg(0), Val, Info))
  5829. return false;
  5830. return Success(Val.countPopulation(), E);
  5831. }
  5832. case Builtin::BIstrlen:
  5833. // A call to strlen is not a constant expression.
  5834. if (Info.getLangOpts().CPlusPlus11)
  5835. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5836. << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
  5837. else
  5838. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5839. // Fall through.
  5840. case Builtin::BI__builtin_strlen: {
  5841. // As an extension, we support __builtin_strlen() as a constant expression,
  5842. // and support folding strlen() to a constant.
  5843. LValue String;
  5844. if (!EvaluatePointer(E->getArg(0), String, Info))
  5845. return false;
  5846. // Fast path: if it's a string literal, search the string value.
  5847. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  5848. String.getLValueBase().dyn_cast<const Expr *>())) {
  5849. // The string literal may have embedded null characters. Find the first
  5850. // one and truncate there.
  5851. StringRef Str = S->getBytes();
  5852. int64_t Off = String.Offset.getQuantity();
  5853. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  5854. S->getCharByteWidth() == 1) {
  5855. Str = Str.substr(Off);
  5856. StringRef::size_type Pos = Str.find(0);
  5857. if (Pos != StringRef::npos)
  5858. Str = Str.substr(0, Pos);
  5859. return Success(Str.size(), E);
  5860. }
  5861. // Fall through to slow path to issue appropriate diagnostic.
  5862. }
  5863. // Slow path: scan the bytes of the string looking for the terminating 0.
  5864. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  5865. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  5866. APValue Char;
  5867. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  5868. !Char.isInt())
  5869. return false;
  5870. if (!Char.getInt())
  5871. return Success(Strlen, E);
  5872. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  5873. return false;
  5874. }
  5875. }
  5876. case Builtin::BI__atomic_always_lock_free:
  5877. case Builtin::BI__atomic_is_lock_free:
  5878. case Builtin::BI__c11_atomic_is_lock_free: {
  5879. APSInt SizeVal;
  5880. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  5881. return false;
  5882. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  5883. // of two less than the maximum inline atomic width, we know it is
  5884. // lock-free. If the size isn't a power of two, or greater than the
  5885. // maximum alignment where we promote atomics, we know it is not lock-free
  5886. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  5887. // the answer can only be determined at runtime; for example, 16-byte
  5888. // atomics have lock-free implementations on some, but not all,
  5889. // x86-64 processors.
  5890. // Check power-of-two.
  5891. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  5892. if (Size.isPowerOfTwo()) {
  5893. // Check against inlining width.
  5894. unsigned InlineWidthBits =
  5895. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  5896. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  5897. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  5898. Size == CharUnits::One() ||
  5899. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  5900. Expr::NPC_NeverValueDependent))
  5901. // OK, we will inline appropriately-aligned operations of this size,
  5902. // and _Atomic(T) is appropriately-aligned.
  5903. return Success(1, E);
  5904. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  5905. castAs<PointerType>()->getPointeeType();
  5906. if (!PointeeType->isIncompleteType() &&
  5907. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  5908. // OK, we will inline operations on this object.
  5909. return Success(1, E);
  5910. }
  5911. }
  5912. }
  5913. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  5914. Success(0, E) : Error(E);
  5915. }
  5916. }
  5917. }
  5918. static bool HasSameBase(const LValue &A, const LValue &B) {
  5919. if (!A.getLValueBase())
  5920. return !B.getLValueBase();
  5921. if (!B.getLValueBase())
  5922. return false;
  5923. if (A.getLValueBase().getOpaqueValue() !=
  5924. B.getLValueBase().getOpaqueValue()) {
  5925. const Decl *ADecl = GetLValueBaseDecl(A);
  5926. if (!ADecl)
  5927. return false;
  5928. const Decl *BDecl = GetLValueBaseDecl(B);
  5929. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  5930. return false;
  5931. }
  5932. return IsGlobalLValue(A.getLValueBase()) ||
  5933. A.getLValueCallIndex() == B.getLValueCallIndex();
  5934. }
  5935. /// \brief Determine whether this is a pointer past the end of the complete
  5936. /// object referred to by the lvalue.
  5937. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  5938. const LValue &LV) {
  5939. // A null pointer can be viewed as being "past the end" but we don't
  5940. // choose to look at it that way here.
  5941. if (!LV.getLValueBase())
  5942. return false;
  5943. // If the designator is valid and refers to a subobject, we're not pointing
  5944. // past the end.
  5945. if (!LV.getLValueDesignator().Invalid &&
  5946. !LV.getLValueDesignator().isOnePastTheEnd())
  5947. return false;
  5948. // We're a past-the-end pointer if we point to the byte after the object,
  5949. // no matter what our type or path is.
  5950. auto Size = Ctx.getTypeSizeInChars(getType(LV.getLValueBase()));
  5951. return LV.getLValueOffset() == Size;
  5952. }
  5953. namespace {
  5954. /// \brief Data recursive integer evaluator of certain binary operators.
  5955. ///
  5956. /// We use a data recursive algorithm for binary operators so that we are able
  5957. /// to handle extreme cases of chained binary operators without causing stack
  5958. /// overflow.
  5959. class DataRecursiveIntBinOpEvaluator {
  5960. struct EvalResult {
  5961. APValue Val;
  5962. bool Failed;
  5963. EvalResult() : Failed(false) { }
  5964. void swap(EvalResult &RHS) {
  5965. Val.swap(RHS.Val);
  5966. Failed = RHS.Failed;
  5967. RHS.Failed = false;
  5968. }
  5969. };
  5970. struct Job {
  5971. const Expr *E;
  5972. EvalResult LHSResult; // meaningful only for binary operator expression.
  5973. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  5974. Job() : StoredInfo(nullptr) {}
  5975. void startSpeculativeEval(EvalInfo &Info) {
  5976. OldEvalStatus = Info.EvalStatus;
  5977. Info.EvalStatus.Diag = nullptr;
  5978. StoredInfo = &Info;
  5979. }
  5980. ~Job() {
  5981. if (StoredInfo) {
  5982. StoredInfo->EvalStatus = OldEvalStatus;
  5983. }
  5984. }
  5985. private:
  5986. EvalInfo *StoredInfo; // non-null if status changed.
  5987. Expr::EvalStatus OldEvalStatus;
  5988. };
  5989. SmallVector<Job, 16> Queue;
  5990. IntExprEvaluator &IntEval;
  5991. EvalInfo &Info;
  5992. APValue &FinalResult;
  5993. public:
  5994. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  5995. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  5996. /// \brief True if \param E is a binary operator that we are going to handle
  5997. /// data recursively.
  5998. /// We handle binary operators that are comma, logical, or that have operands
  5999. /// with integral or enumeration type.
  6000. static bool shouldEnqueue(const BinaryOperator *E) {
  6001. return E->getOpcode() == BO_Comma ||
  6002. E->isLogicalOp() ||
  6003. (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6004. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6005. }
  6006. bool Traverse(const BinaryOperator *E) {
  6007. enqueue(E);
  6008. EvalResult PrevResult;
  6009. while (!Queue.empty())
  6010. process(PrevResult);
  6011. if (PrevResult.Failed) return false;
  6012. FinalResult.swap(PrevResult.Val);
  6013. return true;
  6014. }
  6015. private:
  6016. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6017. return IntEval.Success(Value, E, Result);
  6018. }
  6019. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  6020. return IntEval.Success(Value, E, Result);
  6021. }
  6022. bool Error(const Expr *E) {
  6023. return IntEval.Error(E);
  6024. }
  6025. bool Error(const Expr *E, diag::kind D) {
  6026. return IntEval.Error(E, D);
  6027. }
  6028. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  6029. return Info.CCEDiag(E, D);
  6030. }
  6031. // \brief Returns true if visiting the RHS is necessary, false otherwise.
  6032. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  6033. bool &SuppressRHSDiags);
  6034. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  6035. const BinaryOperator *E, APValue &Result);
  6036. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  6037. Result.Failed = !Evaluate(Result.Val, Info, E);
  6038. if (Result.Failed)
  6039. Result.Val = APValue();
  6040. }
  6041. void process(EvalResult &Result);
  6042. void enqueue(const Expr *E) {
  6043. E = E->IgnoreParens();
  6044. Queue.resize(Queue.size()+1);
  6045. Queue.back().E = E;
  6046. Queue.back().Kind = Job::AnyExprKind;
  6047. }
  6048. };
  6049. }
  6050. bool DataRecursiveIntBinOpEvaluator::
  6051. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  6052. bool &SuppressRHSDiags) {
  6053. if (E->getOpcode() == BO_Comma) {
  6054. // Ignore LHS but note if we could not evaluate it.
  6055. if (LHSResult.Failed)
  6056. return Info.noteSideEffect();
  6057. return true;
  6058. }
  6059. if (E->isLogicalOp()) {
  6060. bool LHSAsBool;
  6061. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  6062. // We were able to evaluate the LHS, see if we can get away with not
  6063. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  6064. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  6065. Success(LHSAsBool, E, LHSResult.Val);
  6066. return false; // Ignore RHS
  6067. }
  6068. } else {
  6069. LHSResult.Failed = true;
  6070. // Since we weren't able to evaluate the left hand side, it
  6071. // must have had side effects.
  6072. if (!Info.noteSideEffect())
  6073. return false;
  6074. // We can't evaluate the LHS; however, sometimes the result
  6075. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  6076. // Don't ignore RHS and suppress diagnostics from this arm.
  6077. SuppressRHSDiags = true;
  6078. }
  6079. return true;
  6080. }
  6081. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6082. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6083. if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
  6084. return false; // Ignore RHS;
  6085. return true;
  6086. }
  6087. bool DataRecursiveIntBinOpEvaluator::
  6088. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  6089. const BinaryOperator *E, APValue &Result) {
  6090. if (E->getOpcode() == BO_Comma) {
  6091. if (RHSResult.Failed)
  6092. return false;
  6093. Result = RHSResult.Val;
  6094. return true;
  6095. }
  6096. if (E->isLogicalOp()) {
  6097. bool lhsResult, rhsResult;
  6098. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  6099. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  6100. if (LHSIsOK) {
  6101. if (RHSIsOK) {
  6102. if (E->getOpcode() == BO_LOr)
  6103. return Success(lhsResult || rhsResult, E, Result);
  6104. else
  6105. return Success(lhsResult && rhsResult, E, Result);
  6106. }
  6107. } else {
  6108. if (RHSIsOK) {
  6109. // We can't evaluate the LHS; however, sometimes the result
  6110. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  6111. if (rhsResult == (E->getOpcode() == BO_LOr))
  6112. return Success(rhsResult, E, Result);
  6113. }
  6114. }
  6115. return false;
  6116. }
  6117. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6118. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6119. if (LHSResult.Failed || RHSResult.Failed)
  6120. return false;
  6121. const APValue &LHSVal = LHSResult.Val;
  6122. const APValue &RHSVal = RHSResult.Val;
  6123. // Handle cases like (unsigned long)&a + 4.
  6124. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  6125. Result = LHSVal;
  6126. CharUnits AdditionalOffset =
  6127. CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
  6128. if (E->getOpcode() == BO_Add)
  6129. Result.getLValueOffset() += AdditionalOffset;
  6130. else
  6131. Result.getLValueOffset() -= AdditionalOffset;
  6132. return true;
  6133. }
  6134. // Handle cases like 4 + (unsigned long)&a
  6135. if (E->getOpcode() == BO_Add &&
  6136. RHSVal.isLValue() && LHSVal.isInt()) {
  6137. Result = RHSVal;
  6138. Result.getLValueOffset() +=
  6139. CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
  6140. return true;
  6141. }
  6142. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  6143. // Handle (intptr_t)&&A - (intptr_t)&&B.
  6144. if (!LHSVal.getLValueOffset().isZero() ||
  6145. !RHSVal.getLValueOffset().isZero())
  6146. return false;
  6147. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  6148. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  6149. if (!LHSExpr || !RHSExpr)
  6150. return false;
  6151. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  6152. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  6153. if (!LHSAddrExpr || !RHSAddrExpr)
  6154. return false;
  6155. // Make sure both labels come from the same function.
  6156. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  6157. RHSAddrExpr->getLabel()->getDeclContext())
  6158. return false;
  6159. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  6160. return true;
  6161. }
  6162. // All the remaining cases expect both operands to be an integer
  6163. if (!LHSVal.isInt() || !RHSVal.isInt())
  6164. return Error(E);
  6165. // Set up the width and signedness manually, in case it can't be deduced
  6166. // from the operation we're performing.
  6167. // FIXME: Don't do this in the cases where we can deduce it.
  6168. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  6169. E->getType()->isUnsignedIntegerOrEnumerationType());
  6170. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  6171. RHSVal.getInt(), Value))
  6172. return false;
  6173. return Success(Value, E, Result);
  6174. }
  6175. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  6176. Job &job = Queue.back();
  6177. switch (job.Kind) {
  6178. case Job::AnyExprKind: {
  6179. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  6180. if (shouldEnqueue(Bop)) {
  6181. job.Kind = Job::BinOpKind;
  6182. enqueue(Bop->getLHS());
  6183. return;
  6184. }
  6185. }
  6186. EvaluateExpr(job.E, Result);
  6187. Queue.pop_back();
  6188. return;
  6189. }
  6190. case Job::BinOpKind: {
  6191. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  6192. bool SuppressRHSDiags = false;
  6193. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  6194. Queue.pop_back();
  6195. return;
  6196. }
  6197. if (SuppressRHSDiags)
  6198. job.startSpeculativeEval(Info);
  6199. job.LHSResult.swap(Result);
  6200. job.Kind = Job::BinOpVisitedLHSKind;
  6201. enqueue(Bop->getRHS());
  6202. return;
  6203. }
  6204. case Job::BinOpVisitedLHSKind: {
  6205. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  6206. EvalResult RHS;
  6207. RHS.swap(Result);
  6208. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  6209. Queue.pop_back();
  6210. return;
  6211. }
  6212. }
  6213. llvm_unreachable("Invalid Job::Kind!");
  6214. }
  6215. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6216. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  6217. return Error(E);
  6218. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  6219. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  6220. QualType LHSTy = E->getLHS()->getType();
  6221. QualType RHSTy = E->getRHS()->getType();
  6222. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  6223. ComplexValue LHS, RHS;
  6224. bool LHSOK;
  6225. if (E->isAssignmentOp()) {
  6226. LValue LV;
  6227. EvaluateLValue(E->getLHS(), LV, Info);
  6228. LHSOK = false;
  6229. } else if (LHSTy->isRealFloatingType()) {
  6230. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  6231. if (LHSOK) {
  6232. LHS.makeComplexFloat();
  6233. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  6234. }
  6235. } else {
  6236. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  6237. }
  6238. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  6239. return false;
  6240. if (E->getRHS()->getType()->isRealFloatingType()) {
  6241. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  6242. return false;
  6243. RHS.makeComplexFloat();
  6244. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  6245. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  6246. return false;
  6247. if (LHS.isComplexFloat()) {
  6248. APFloat::cmpResult CR_r =
  6249. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  6250. APFloat::cmpResult CR_i =
  6251. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  6252. if (E->getOpcode() == BO_EQ)
  6253. return Success((CR_r == APFloat::cmpEqual &&
  6254. CR_i == APFloat::cmpEqual), E);
  6255. else {
  6256. assert(E->getOpcode() == BO_NE &&
  6257. "Invalid complex comparison.");
  6258. return Success(((CR_r == APFloat::cmpGreaterThan ||
  6259. CR_r == APFloat::cmpLessThan ||
  6260. CR_r == APFloat::cmpUnordered) ||
  6261. (CR_i == APFloat::cmpGreaterThan ||
  6262. CR_i == APFloat::cmpLessThan ||
  6263. CR_i == APFloat::cmpUnordered)), E);
  6264. }
  6265. } else {
  6266. if (E->getOpcode() == BO_EQ)
  6267. return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  6268. LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
  6269. else {
  6270. assert(E->getOpcode() == BO_NE &&
  6271. "Invalid compex comparison.");
  6272. return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
  6273. LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
  6274. }
  6275. }
  6276. }
  6277. if (LHSTy->isRealFloatingType() &&
  6278. RHSTy->isRealFloatingType()) {
  6279. APFloat RHS(0.0), LHS(0.0);
  6280. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  6281. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  6282. return false;
  6283. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  6284. return false;
  6285. APFloat::cmpResult CR = LHS.compare(RHS);
  6286. switch (E->getOpcode()) {
  6287. default:
  6288. llvm_unreachable("Invalid binary operator!");
  6289. case BO_LT:
  6290. return Success(CR == APFloat::cmpLessThan, E);
  6291. case BO_GT:
  6292. return Success(CR == APFloat::cmpGreaterThan, E);
  6293. case BO_LE:
  6294. return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
  6295. case BO_GE:
  6296. return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
  6297. E);
  6298. case BO_EQ:
  6299. return Success(CR == APFloat::cmpEqual, E);
  6300. case BO_NE:
  6301. return Success(CR == APFloat::cmpGreaterThan
  6302. || CR == APFloat::cmpLessThan
  6303. || CR == APFloat::cmpUnordered, E);
  6304. }
  6305. }
  6306. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  6307. if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
  6308. LValue LHSValue, RHSValue;
  6309. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  6310. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  6311. return false;
  6312. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  6313. return false;
  6314. // Reject differing bases from the normal codepath; we special-case
  6315. // comparisons to null.
  6316. if (!HasSameBase(LHSValue, RHSValue)) {
  6317. if (E->getOpcode() == BO_Sub) {
  6318. // Handle &&A - &&B.
  6319. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  6320. return false;
  6321. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
  6322. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
  6323. if (!LHSExpr || !RHSExpr)
  6324. return false;
  6325. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  6326. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  6327. if (!LHSAddrExpr || !RHSAddrExpr)
  6328. return false;
  6329. // Make sure both labels come from the same function.
  6330. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  6331. RHSAddrExpr->getLabel()->getDeclContext())
  6332. return false;
  6333. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  6334. return true;
  6335. }
  6336. // Inequalities and subtractions between unrelated pointers have
  6337. // unspecified or undefined behavior.
  6338. if (!E->isEqualityOp())
  6339. return Error(E);
  6340. // A constant address may compare equal to the address of a symbol.
  6341. // The one exception is that address of an object cannot compare equal
  6342. // to a null pointer constant.
  6343. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  6344. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  6345. return Error(E);
  6346. // It's implementation-defined whether distinct literals will have
  6347. // distinct addresses. In clang, the result of such a comparison is
  6348. // unspecified, so it is not a constant expression. However, we do know
  6349. // that the address of a literal will be non-null.
  6350. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  6351. LHSValue.Base && RHSValue.Base)
  6352. return Error(E);
  6353. // We can't tell whether weak symbols will end up pointing to the same
  6354. // object.
  6355. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  6356. return Error(E);
  6357. // We can't compare the address of the start of one object with the
  6358. // past-the-end address of another object, per C++ DR1652.
  6359. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  6360. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  6361. (RHSValue.Base && RHSValue.Offset.isZero() &&
  6362. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  6363. return Error(E);
  6364. // We can't tell whether an object is at the same address as another
  6365. // zero sized object.
  6366. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  6367. (LHSValue.Base && isZeroSized(RHSValue)))
  6368. return Error(E);
  6369. // Pointers with different bases cannot represent the same object.
  6370. // (Note that clang defaults to -fmerge-all-constants, which can
  6371. // lead to inconsistent results for comparisons involving the address
  6372. // of a constant; this generally doesn't matter in practice.)
  6373. return Success(E->getOpcode() == BO_NE, E);
  6374. }
  6375. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  6376. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  6377. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  6378. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  6379. if (E->getOpcode() == BO_Sub) {
  6380. // C++11 [expr.add]p6:
  6381. // Unless both pointers point to elements of the same array object, or
  6382. // one past the last element of the array object, the behavior is
  6383. // undefined.
  6384. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  6385. !AreElementsOfSameArray(getType(LHSValue.Base),
  6386. LHSDesignator, RHSDesignator))
  6387. CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  6388. QualType Type = E->getLHS()->getType();
  6389. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  6390. CharUnits ElementSize;
  6391. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  6392. return false;
  6393. // As an extension, a type may have zero size (empty struct or union in
  6394. // C, array of zero length). Pointer subtraction in such cases has
  6395. // undefined behavior, so is not constant.
  6396. if (ElementSize.isZero()) {
  6397. Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  6398. << ElementType;
  6399. return false;
  6400. }
  6401. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  6402. // and produce incorrect results when it overflows. Such behavior
  6403. // appears to be non-conforming, but is common, so perhaps we should
  6404. // assume the standard intended for such cases to be undefined behavior
  6405. // and check for them.
  6406. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  6407. // overflow in the final conversion to ptrdiff_t.
  6408. APSInt LHS(
  6409. llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  6410. APSInt RHS(
  6411. llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  6412. APSInt ElemSize(
  6413. llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
  6414. APSInt TrueResult = (LHS - RHS) / ElemSize;
  6415. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  6416. if (Result.extend(65) != TrueResult)
  6417. HandleOverflow(Info, E, TrueResult, E->getType());
  6418. return Success(Result, E);
  6419. }
  6420. // C++11 [expr.rel]p3:
  6421. // Pointers to void (after pointer conversions) can be compared, with a
  6422. // result defined as follows: If both pointers represent the same
  6423. // address or are both the null pointer value, the result is true if the
  6424. // operator is <= or >= and false otherwise; otherwise the result is
  6425. // unspecified.
  6426. // We interpret this as applying to pointers to *cv* void.
  6427. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
  6428. E->isRelationalOp())
  6429. CCEDiag(E, diag::note_constexpr_void_comparison);
  6430. // C++11 [expr.rel]p2:
  6431. // - If two pointers point to non-static data members of the same object,
  6432. // or to subobjects or array elements fo such members, recursively, the
  6433. // pointer to the later declared member compares greater provided the
  6434. // two members have the same access control and provided their class is
  6435. // not a union.
  6436. // [...]
  6437. // - Otherwise pointer comparisons are unspecified.
  6438. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  6439. E->isRelationalOp()) {
  6440. bool WasArrayIndex;
  6441. unsigned Mismatch =
  6442. FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
  6443. RHSDesignator, WasArrayIndex);
  6444. // At the point where the designators diverge, the comparison has a
  6445. // specified value if:
  6446. // - we are comparing array indices
  6447. // - we are comparing fields of a union, or fields with the same access
  6448. // Otherwise, the result is unspecified and thus the comparison is not a
  6449. // constant expression.
  6450. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  6451. Mismatch < RHSDesignator.Entries.size()) {
  6452. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  6453. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  6454. if (!LF && !RF)
  6455. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  6456. else if (!LF)
  6457. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  6458. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  6459. << RF->getParent() << RF;
  6460. else if (!RF)
  6461. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  6462. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  6463. << LF->getParent() << LF;
  6464. else if (!LF->getParent()->isUnion() &&
  6465. LF->getAccess() != RF->getAccess())
  6466. CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
  6467. << LF << LF->getAccess() << RF << RF->getAccess()
  6468. << LF->getParent();
  6469. }
  6470. }
  6471. // The comparison here must be unsigned, and performed with the same
  6472. // width as the pointer.
  6473. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  6474. uint64_t CompareLHS = LHSOffset.getQuantity();
  6475. uint64_t CompareRHS = RHSOffset.getQuantity();
  6476. assert(PtrSize <= 64 && "Unexpected pointer width");
  6477. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  6478. CompareLHS &= Mask;
  6479. CompareRHS &= Mask;
  6480. // If there is a base and this is a relational operator, we can only
  6481. // compare pointers within the object in question; otherwise, the result
  6482. // depends on where the object is located in memory.
  6483. if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
  6484. QualType BaseTy = getType(LHSValue.Base);
  6485. if (BaseTy->isIncompleteType())
  6486. return Error(E);
  6487. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  6488. uint64_t OffsetLimit = Size.getQuantity();
  6489. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  6490. return Error(E);
  6491. }
  6492. switch (E->getOpcode()) {
  6493. default: llvm_unreachable("missing comparison operator");
  6494. case BO_LT: return Success(CompareLHS < CompareRHS, E);
  6495. case BO_GT: return Success(CompareLHS > CompareRHS, E);
  6496. case BO_LE: return Success(CompareLHS <= CompareRHS, E);
  6497. case BO_GE: return Success(CompareLHS >= CompareRHS, E);
  6498. case BO_EQ: return Success(CompareLHS == CompareRHS, E);
  6499. case BO_NE: return Success(CompareLHS != CompareRHS, E);
  6500. }
  6501. }
  6502. }
  6503. if (LHSTy->isMemberPointerType()) {
  6504. assert(E->isEqualityOp() && "unexpected member pointer operation");
  6505. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  6506. MemberPtr LHSValue, RHSValue;
  6507. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  6508. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  6509. return false;
  6510. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  6511. return false;
  6512. // C++11 [expr.eq]p2:
  6513. // If both operands are null, they compare equal. Otherwise if only one is
  6514. // null, they compare unequal.
  6515. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  6516. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  6517. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  6518. }
  6519. // Otherwise if either is a pointer to a virtual member function, the
  6520. // result is unspecified.
  6521. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  6522. if (MD->isVirtual())
  6523. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  6524. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  6525. if (MD->isVirtual())
  6526. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  6527. // Otherwise they compare equal if and only if they would refer to the
  6528. // same member of the same most derived object or the same subobject if
  6529. // they were dereferenced with a hypothetical object of the associated
  6530. // class type.
  6531. bool Equal = LHSValue == RHSValue;
  6532. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  6533. }
  6534. if (LHSTy->isNullPtrType()) {
  6535. assert(E->isComparisonOp() && "unexpected nullptr operation");
  6536. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  6537. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  6538. // are compared, the result is true of the operator is <=, >= or ==, and
  6539. // false otherwise.
  6540. BinaryOperator::Opcode Opcode = E->getOpcode();
  6541. return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
  6542. }
  6543. assert((!LHSTy->isIntegralOrEnumerationType() ||
  6544. !RHSTy->isIntegralOrEnumerationType()) &&
  6545. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  6546. // We can't continue from here for non-integral types.
  6547. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6548. }
  6549. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  6550. /// a result as the expression's type.
  6551. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  6552. const UnaryExprOrTypeTraitExpr *E) {
  6553. switch(E->getKind()) {
  6554. case UETT_AlignOf: {
  6555. if (E->isArgumentType())
  6556. return Success(GetAlignOfType(Info, E->getArgumentType()), E);
  6557. else
  6558. return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
  6559. }
  6560. case UETT_VecStep: {
  6561. QualType Ty = E->getTypeOfArgument();
  6562. if (Ty->isVectorType()) {
  6563. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  6564. // The vec_step built-in functions that take a 3-component
  6565. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  6566. if (n == 3)
  6567. n = 4;
  6568. return Success(n, E);
  6569. } else
  6570. return Success(1, E);
  6571. }
  6572. case UETT_SizeOf: {
  6573. QualType SrcTy = E->getTypeOfArgument();
  6574. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  6575. // the result is the size of the referenced type."
  6576. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  6577. SrcTy = Ref->getPointeeType();
  6578. CharUnits Sizeof;
  6579. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  6580. return false;
  6581. return Success(Sizeof, E);
  6582. }
  6583. case UETT_OpenMPRequiredSimdAlign:
  6584. assert(E->isArgumentType());
  6585. return Success(
  6586. Info.Ctx.toCharUnitsFromBits(
  6587. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  6588. .getQuantity(),
  6589. E);
  6590. }
  6591. llvm_unreachable("unknown expr/type trait");
  6592. }
  6593. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  6594. CharUnits Result;
  6595. unsigned n = OOE->getNumComponents();
  6596. if (n == 0)
  6597. return Error(OOE);
  6598. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  6599. for (unsigned i = 0; i != n; ++i) {
  6600. OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
  6601. switch (ON.getKind()) {
  6602. case OffsetOfExpr::OffsetOfNode::Array: {
  6603. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  6604. APSInt IdxResult;
  6605. if (!EvaluateInteger(Idx, IdxResult, Info))
  6606. return false;
  6607. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  6608. if (!AT)
  6609. return Error(OOE);
  6610. CurrentType = AT->getElementType();
  6611. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  6612. Result += IdxResult.getSExtValue() * ElementSize;
  6613. break;
  6614. }
  6615. case OffsetOfExpr::OffsetOfNode::Field: {
  6616. FieldDecl *MemberDecl = ON.getField();
  6617. const RecordType *RT = CurrentType->getAs<RecordType>();
  6618. if (!RT)
  6619. return Error(OOE);
  6620. RecordDecl *RD = RT->getDecl();
  6621. if (RD->isInvalidDecl()) return false;
  6622. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  6623. unsigned i = MemberDecl->getFieldIndex();
  6624. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  6625. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  6626. CurrentType = MemberDecl->getType().getNonReferenceType();
  6627. break;
  6628. }
  6629. case OffsetOfExpr::OffsetOfNode::Identifier:
  6630. llvm_unreachable("dependent __builtin_offsetof");
  6631. case OffsetOfExpr::OffsetOfNode::Base: {
  6632. CXXBaseSpecifier *BaseSpec = ON.getBase();
  6633. if (BaseSpec->isVirtual())
  6634. return Error(OOE);
  6635. // Find the layout of the class whose base we are looking into.
  6636. const RecordType *RT = CurrentType->getAs<RecordType>();
  6637. if (!RT)
  6638. return Error(OOE);
  6639. RecordDecl *RD = RT->getDecl();
  6640. if (RD->isInvalidDecl()) return false;
  6641. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  6642. // Find the base class itself.
  6643. CurrentType = BaseSpec->getType();
  6644. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  6645. if (!BaseRT)
  6646. return Error(OOE);
  6647. // Add the offset to the base.
  6648. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  6649. break;
  6650. }
  6651. }
  6652. }
  6653. return Success(Result, OOE);
  6654. }
  6655. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  6656. switch (E->getOpcode()) {
  6657. default:
  6658. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  6659. // See C99 6.6p3.
  6660. return Error(E);
  6661. case UO_Extension:
  6662. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  6663. // If so, we could clear the diagnostic ID.
  6664. return Visit(E->getSubExpr());
  6665. case UO_Plus:
  6666. // The result is just the value.
  6667. return Visit(E->getSubExpr());
  6668. case UO_Minus: {
  6669. if (!Visit(E->getSubExpr()))
  6670. return false;
  6671. if (!Result.isInt()) return Error(E);
  6672. const APSInt &Value = Result.getInt();
  6673. if (Value.isSigned() && Value.isMinSignedValue())
  6674. HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  6675. E->getType());
  6676. return Success(-Value, E);
  6677. }
  6678. case UO_Not: {
  6679. if (!Visit(E->getSubExpr()))
  6680. return false;
  6681. if (!Result.isInt()) return Error(E);
  6682. return Success(~Result.getInt(), E);
  6683. }
  6684. case UO_LNot: {
  6685. bool bres;
  6686. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  6687. return false;
  6688. return Success(!bres, E);
  6689. }
  6690. }
  6691. }
  6692. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  6693. /// result type is integer.
  6694. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6695. const Expr *SubExpr = E->getSubExpr();
  6696. QualType DestType = E->getType();
  6697. QualType SrcType = SubExpr->getType();
  6698. switch (E->getCastKind()) {
  6699. case CK_BaseToDerived:
  6700. case CK_DerivedToBase:
  6701. case CK_UncheckedDerivedToBase:
  6702. case CK_Dynamic:
  6703. case CK_ToUnion:
  6704. case CK_ArrayToPointerDecay:
  6705. case CK_FunctionToPointerDecay:
  6706. case CK_NullToPointer:
  6707. case CK_NullToMemberPointer:
  6708. case CK_BaseToDerivedMemberPointer:
  6709. case CK_DerivedToBaseMemberPointer:
  6710. case CK_ReinterpretMemberPointer:
  6711. case CK_ConstructorConversion:
  6712. case CK_IntegralToPointer:
  6713. case CK_ToVoid:
  6714. case CK_VectorSplat:
  6715. case CK_IntegralToFloating:
  6716. case CK_FloatingCast:
  6717. case CK_CPointerToObjCPointerCast:
  6718. case CK_BlockPointerToObjCPointerCast:
  6719. case CK_AnyPointerToBlockPointerCast:
  6720. case CK_ObjCObjectLValueCast:
  6721. case CK_FloatingRealToComplex:
  6722. case CK_FloatingComplexToReal:
  6723. case CK_FloatingComplexCast:
  6724. case CK_FloatingComplexToIntegralComplex:
  6725. case CK_IntegralRealToComplex:
  6726. case CK_IntegralComplexCast:
  6727. case CK_IntegralComplexToFloatingComplex:
  6728. case CK_BuiltinFnToFnPtr:
  6729. case CK_ZeroToOCLEvent:
  6730. case CK_NonAtomicToAtomic:
  6731. case CK_AddressSpaceConversion:
  6732. llvm_unreachable("invalid cast kind for integral value");
  6733. case CK_BitCast:
  6734. case CK_Dependent:
  6735. case CK_LValueBitCast:
  6736. case CK_ARCProduceObject:
  6737. case CK_ARCConsumeObject:
  6738. case CK_ARCReclaimReturnedObject:
  6739. case CK_ARCExtendBlockObject:
  6740. case CK_CopyAndAutoreleaseBlockObject:
  6741. case CK_HLSLVectorToScalarCast: // HLSL Change
  6742. case CK_HLSLMatrixToScalarCast: // HLSL Change
  6743. return Error(E);
  6744. case CK_UserDefinedConversion:
  6745. case CK_LValueToRValue:
  6746. case CK_AtomicToNonAtomic:
  6747. case CK_NoOp:
  6748. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6749. case CK_MemberPointerToBoolean:
  6750. case CK_PointerToBoolean:
  6751. case CK_IntegralToBoolean:
  6752. case CK_FloatingToBoolean:
  6753. case CK_FloatingComplexToBoolean:
  6754. case CK_IntegralComplexToBoolean: {
  6755. bool BoolResult;
  6756. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  6757. return false;
  6758. return Success(BoolResult, E);
  6759. }
  6760. case CK_IntegralCast: {
  6761. if (!Visit(SubExpr))
  6762. return false;
  6763. if (!Result.isInt()) {
  6764. // Allow casts of address-of-label differences if they are no-ops
  6765. // or narrowing. (The narrowing case isn't actually guaranteed to
  6766. // be constant-evaluatable except in some narrow cases which are hard
  6767. // to detect here. We let it through on the assumption the user knows
  6768. // what they are doing.)
  6769. if (Result.isAddrLabelDiff())
  6770. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  6771. // Only allow casts of lvalues if they are lossless.
  6772. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  6773. }
  6774. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  6775. Result.getInt()), E);
  6776. }
  6777. case CK_PointerToIntegral: {
  6778. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6779. LValue LV;
  6780. if (!EvaluatePointer(SubExpr, LV, Info))
  6781. return false;
  6782. if (LV.getLValueBase()) {
  6783. // Only allow based lvalue casts if they are lossless.
  6784. // FIXME: Allow a larger integer size than the pointer size, and allow
  6785. // narrowing back down to pointer width in subsequent integral casts.
  6786. // FIXME: Check integer type's active bits, not its type size.
  6787. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  6788. return Error(E);
  6789. LV.Designator.setInvalid();
  6790. LV.moveInto(Result);
  6791. return true;
  6792. }
  6793. APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
  6794. SrcType);
  6795. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  6796. }
  6797. case CK_IntegralComplexToReal: {
  6798. ComplexValue C;
  6799. if (!EvaluateComplex(SubExpr, C, Info))
  6800. return false;
  6801. return Success(C.getComplexIntReal(), E);
  6802. }
  6803. case CK_FloatingToIntegral: {
  6804. APFloat F(0.0);
  6805. if (!EvaluateFloat(SubExpr, F, Info))
  6806. return false;
  6807. APSInt Value;
  6808. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  6809. return false;
  6810. return Success(Value, E);
  6811. }
  6812. }
  6813. llvm_unreachable("unknown cast resulting in integral value");
  6814. }
  6815. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6816. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  6817. ComplexValue LV;
  6818. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  6819. return false;
  6820. if (!LV.isComplexInt())
  6821. return Error(E);
  6822. return Success(LV.getComplexIntReal(), E);
  6823. }
  6824. return Visit(E->getSubExpr());
  6825. }
  6826. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6827. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  6828. ComplexValue LV;
  6829. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  6830. return false;
  6831. if (!LV.isComplexInt())
  6832. return Error(E);
  6833. return Success(LV.getComplexIntImag(), E);
  6834. }
  6835. VisitIgnoredValue(E->getSubExpr());
  6836. return Success(0, E);
  6837. }
  6838. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  6839. return Success(E->getPackLength(), E);
  6840. }
  6841. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  6842. return Success(E->getValue(), E);
  6843. }
  6844. //===----------------------------------------------------------------------===//
  6845. // Float Evaluation
  6846. //===----------------------------------------------------------------------===//
  6847. namespace {
  6848. class FloatExprEvaluator
  6849. : public ExprEvaluatorBase<FloatExprEvaluator> {
  6850. APFloat &Result;
  6851. public:
  6852. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  6853. : ExprEvaluatorBaseTy(info), Result(result) {}
  6854. bool Success(const APValue &V, const Expr *e) {
  6855. Result = V.getFloat();
  6856. return true;
  6857. }
  6858. bool ZeroInitialization(const Expr *E) {
  6859. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  6860. return true;
  6861. }
  6862. bool VisitCallExpr(const CallExpr *E);
  6863. bool VisitUnaryOperator(const UnaryOperator *E);
  6864. bool VisitBinaryOperator(const BinaryOperator *E);
  6865. bool VisitFloatingLiteral(const FloatingLiteral *E);
  6866. bool VisitCastExpr(const CastExpr *E);
  6867. bool VisitUnaryReal(const UnaryOperator *E);
  6868. bool VisitUnaryImag(const UnaryOperator *E);
  6869. // FIXME: Missing: array subscript of vector, member of vector
  6870. };
  6871. } // end anonymous namespace
  6872. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  6873. assert(E->isRValue() && E->getType()->isRealFloatingType());
  6874. return FloatExprEvaluator(Info, Result).Visit(E);
  6875. }
  6876. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  6877. QualType ResultTy,
  6878. const Expr *Arg,
  6879. bool SNaN,
  6880. llvm::APFloat &Result) {
  6881. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  6882. if (!S) return false;
  6883. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  6884. llvm::APInt fill;
  6885. // Treat empty strings as if they were zero.
  6886. if (S->getString().empty())
  6887. fill = llvm::APInt(32, 0);
  6888. else if (S->getString().getAsInteger(0, fill))
  6889. return false;
  6890. if (Context.getTargetInfo().isNan2008()) {
  6891. if (SNaN)
  6892. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  6893. else
  6894. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  6895. } else {
  6896. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  6897. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  6898. // a different encoding to what became a standard in 2008, and for pre-
  6899. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  6900. // sNaN. This is now known as "legacy NaN" encoding.
  6901. if (SNaN)
  6902. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  6903. else
  6904. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  6905. }
  6906. return true;
  6907. }
  6908. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6909. switch (E->getBuiltinCallee()) {
  6910. default:
  6911. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  6912. case Builtin::BI__builtin_huge_val:
  6913. case Builtin::BI__builtin_huge_valf:
  6914. case Builtin::BI__builtin_huge_vall:
  6915. case Builtin::BI__builtin_inf:
  6916. case Builtin::BI__builtin_inff:
  6917. case Builtin::BI__builtin_infl: {
  6918. const llvm::fltSemantics &Sem =
  6919. Info.Ctx.getFloatTypeSemantics(E->getType());
  6920. Result = llvm::APFloat::getInf(Sem);
  6921. return true;
  6922. }
  6923. case Builtin::BI__builtin_nans:
  6924. case Builtin::BI__builtin_nansf:
  6925. case Builtin::BI__builtin_nansl:
  6926. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  6927. true, Result))
  6928. return Error(E);
  6929. return true;
  6930. case Builtin::BI__builtin_nan:
  6931. case Builtin::BI__builtin_nanf:
  6932. case Builtin::BI__builtin_nanl:
  6933. // If this is __builtin_nan() turn this into a nan, otherwise we
  6934. // can't constant fold it.
  6935. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  6936. false, Result))
  6937. return Error(E);
  6938. return true;
  6939. case Builtin::BI__builtin_fabs:
  6940. case Builtin::BI__builtin_fabsf:
  6941. case Builtin::BI__builtin_fabsl:
  6942. if (!EvaluateFloat(E->getArg(0), Result, Info))
  6943. return false;
  6944. if (Result.isNegative())
  6945. Result.changeSign();
  6946. return true;
  6947. // FIXME: Builtin::BI__builtin_powi
  6948. // FIXME: Builtin::BI__builtin_powif
  6949. // FIXME: Builtin::BI__builtin_powil
  6950. case Builtin::BI__builtin_copysign:
  6951. case Builtin::BI__builtin_copysignf:
  6952. case Builtin::BI__builtin_copysignl: {
  6953. APFloat RHS(0.);
  6954. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  6955. !EvaluateFloat(E->getArg(1), RHS, Info))
  6956. return false;
  6957. Result.copySign(RHS);
  6958. return true;
  6959. }
  6960. }
  6961. }
  6962. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6963. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  6964. ComplexValue CV;
  6965. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  6966. return false;
  6967. Result = CV.FloatReal;
  6968. return true;
  6969. }
  6970. return Visit(E->getSubExpr());
  6971. }
  6972. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6973. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  6974. ComplexValue CV;
  6975. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  6976. return false;
  6977. Result = CV.FloatImag;
  6978. return true;
  6979. }
  6980. VisitIgnoredValue(E->getSubExpr());
  6981. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  6982. Result = llvm::APFloat::getZero(Sem);
  6983. return true;
  6984. }
  6985. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  6986. switch (E->getOpcode()) {
  6987. default: return Error(E);
  6988. case UO_Plus:
  6989. return EvaluateFloat(E->getSubExpr(), Result, Info);
  6990. case UO_Minus:
  6991. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  6992. return false;
  6993. Result.changeSign();
  6994. return true;
  6995. }
  6996. }
  6997. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6998. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  6999. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7000. APFloat RHS(0.0);
  7001. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  7002. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  7003. return false;
  7004. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  7005. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  7006. }
  7007. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  7008. Result = E->getValue();
  7009. return true;
  7010. }
  7011. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7012. const Expr* SubExpr = E->getSubExpr();
  7013. switch (E->getCastKind()) {
  7014. default:
  7015. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7016. case CK_IntegralToFloating: {
  7017. APSInt IntResult;
  7018. return EvaluateInteger(SubExpr, IntResult, Info) &&
  7019. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  7020. E->getType(), Result);
  7021. }
  7022. case CK_FloatingCast: {
  7023. if (!Visit(SubExpr))
  7024. return false;
  7025. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  7026. Result);
  7027. }
  7028. case CK_FloatingComplexToReal: {
  7029. ComplexValue V;
  7030. if (!EvaluateComplex(SubExpr, V, Info))
  7031. return false;
  7032. Result = V.getComplexFloatReal();
  7033. return true;
  7034. }
  7035. }
  7036. }
  7037. //===----------------------------------------------------------------------===//
  7038. // Complex Evaluation (for float and integer)
  7039. //===----------------------------------------------------------------------===//
  7040. namespace {
  7041. class ComplexExprEvaluator
  7042. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  7043. ComplexValue &Result;
  7044. public:
  7045. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  7046. : ExprEvaluatorBaseTy(info), Result(Result) {}
  7047. bool Success(const APValue &V, const Expr *e) {
  7048. Result.setFrom(V);
  7049. return true;
  7050. }
  7051. bool ZeroInitialization(const Expr *E);
  7052. //===--------------------------------------------------------------------===//
  7053. // Visitor Methods
  7054. //===--------------------------------------------------------------------===//
  7055. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  7056. bool VisitCastExpr(const CastExpr *E);
  7057. bool VisitBinaryOperator(const BinaryOperator *E);
  7058. bool VisitUnaryOperator(const UnaryOperator *E);
  7059. bool VisitInitListExpr(const InitListExpr *E);
  7060. };
  7061. } // end anonymous namespace
  7062. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  7063. EvalInfo &Info) {
  7064. assert(E->isRValue() && E->getType()->isAnyComplexType());
  7065. return ComplexExprEvaluator(Info, Result).Visit(E);
  7066. }
  7067. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  7068. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  7069. if (ElemTy->isRealFloatingType()) {
  7070. Result.makeComplexFloat();
  7071. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  7072. Result.FloatReal = Zero;
  7073. Result.FloatImag = Zero;
  7074. } else {
  7075. Result.makeComplexInt();
  7076. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  7077. Result.IntReal = Zero;
  7078. Result.IntImag = Zero;
  7079. }
  7080. return true;
  7081. }
  7082. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  7083. const Expr* SubExpr = E->getSubExpr();
  7084. if (SubExpr->getType()->isRealFloatingType()) {
  7085. Result.makeComplexFloat();
  7086. APFloat &Imag = Result.FloatImag;
  7087. if (!EvaluateFloat(SubExpr, Imag, Info))
  7088. return false;
  7089. Result.FloatReal = APFloat(Imag.getSemantics());
  7090. return true;
  7091. } else {
  7092. assert(SubExpr->getType()->isIntegerType() &&
  7093. "Unexpected imaginary literal.");
  7094. Result.makeComplexInt();
  7095. APSInt &Imag = Result.IntImag;
  7096. if (!EvaluateInteger(SubExpr, Imag, Info))
  7097. return false;
  7098. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  7099. return true;
  7100. }
  7101. }
  7102. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7103. switch (E->getCastKind()) {
  7104. case CK_BitCast:
  7105. case CK_BaseToDerived:
  7106. case CK_DerivedToBase:
  7107. case CK_UncheckedDerivedToBase:
  7108. case CK_Dynamic:
  7109. case CK_ToUnion:
  7110. case CK_ArrayToPointerDecay:
  7111. case CK_FunctionToPointerDecay:
  7112. case CK_NullToPointer:
  7113. case CK_NullToMemberPointer:
  7114. case CK_BaseToDerivedMemberPointer:
  7115. case CK_DerivedToBaseMemberPointer:
  7116. case CK_MemberPointerToBoolean:
  7117. case CK_ReinterpretMemberPointer:
  7118. case CK_ConstructorConversion:
  7119. case CK_IntegralToPointer:
  7120. case CK_PointerToIntegral:
  7121. case CK_PointerToBoolean:
  7122. case CK_ToVoid:
  7123. case CK_VectorSplat:
  7124. case CK_IntegralCast:
  7125. case CK_IntegralToBoolean:
  7126. case CK_IntegralToFloating:
  7127. case CK_FloatingToIntegral:
  7128. case CK_FloatingToBoolean:
  7129. case CK_FloatingCast:
  7130. case CK_CPointerToObjCPointerCast:
  7131. case CK_BlockPointerToObjCPointerCast:
  7132. case CK_AnyPointerToBlockPointerCast:
  7133. case CK_ObjCObjectLValueCast:
  7134. case CK_FloatingComplexToReal:
  7135. case CK_FloatingComplexToBoolean:
  7136. case CK_IntegralComplexToReal:
  7137. case CK_IntegralComplexToBoolean:
  7138. case CK_ARCProduceObject:
  7139. case CK_ARCConsumeObject:
  7140. case CK_ARCReclaimReturnedObject:
  7141. case CK_ARCExtendBlockObject:
  7142. case CK_CopyAndAutoreleaseBlockObject:
  7143. case CK_BuiltinFnToFnPtr:
  7144. case CK_ZeroToOCLEvent:
  7145. case CK_NonAtomicToAtomic:
  7146. case CK_AddressSpaceConversion:
  7147. llvm_unreachable("invalid cast kind for complex value");
  7148. case CK_LValueToRValue:
  7149. case CK_AtomicToNonAtomic:
  7150. case CK_NoOp:
  7151. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7152. case CK_Dependent:
  7153. case CK_LValueBitCast:
  7154. case CK_UserDefinedConversion:
  7155. return Error(E);
  7156. case CK_FloatingRealToComplex: {
  7157. APFloat &Real = Result.FloatReal;
  7158. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  7159. return false;
  7160. Result.makeComplexFloat();
  7161. Result.FloatImag = APFloat(Real.getSemantics());
  7162. return true;
  7163. }
  7164. case CK_FloatingComplexCast: {
  7165. if (!Visit(E->getSubExpr()))
  7166. return false;
  7167. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7168. QualType From
  7169. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7170. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  7171. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  7172. }
  7173. case CK_FloatingComplexToIntegralComplex: {
  7174. if (!Visit(E->getSubExpr()))
  7175. return false;
  7176. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7177. QualType From
  7178. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7179. Result.makeComplexInt();
  7180. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  7181. To, Result.IntReal) &&
  7182. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  7183. To, Result.IntImag);
  7184. }
  7185. case CK_IntegralRealToComplex: {
  7186. APSInt &Real = Result.IntReal;
  7187. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  7188. return false;
  7189. Result.makeComplexInt();
  7190. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  7191. return true;
  7192. }
  7193. case CK_IntegralComplexCast: {
  7194. if (!Visit(E->getSubExpr()))
  7195. return false;
  7196. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7197. QualType From
  7198. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7199. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  7200. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  7201. return true;
  7202. }
  7203. case CK_IntegralComplexToFloatingComplex: {
  7204. if (!Visit(E->getSubExpr()))
  7205. return false;
  7206. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  7207. QualType From
  7208. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  7209. Result.makeComplexFloat();
  7210. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  7211. To, Result.FloatReal) &&
  7212. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  7213. To, Result.FloatImag);
  7214. }
  7215. }
  7216. llvm_unreachable("unknown cast resulting in complex value");
  7217. }
  7218. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  7219. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  7220. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7221. // Track whether the LHS or RHS is real at the type system level. When this is
  7222. // the case we can simplify our evaluation strategy.
  7223. bool LHSReal = false, RHSReal = false;
  7224. bool LHSOK;
  7225. if (E->getLHS()->getType()->isRealFloatingType()) {
  7226. LHSReal = true;
  7227. APFloat &Real = Result.FloatReal;
  7228. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  7229. if (LHSOK) {
  7230. Result.makeComplexFloat();
  7231. Result.FloatImag = APFloat(Real.getSemantics());
  7232. }
  7233. } else {
  7234. LHSOK = Visit(E->getLHS());
  7235. }
  7236. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  7237. return false;
  7238. ComplexValue RHS;
  7239. if (E->getRHS()->getType()->isRealFloatingType()) {
  7240. RHSReal = true;
  7241. APFloat &Real = RHS.FloatReal;
  7242. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  7243. return false;
  7244. RHS.makeComplexFloat();
  7245. RHS.FloatImag = APFloat(Real.getSemantics());
  7246. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  7247. return false;
  7248. assert(!(LHSReal && RHSReal) &&
  7249. "Cannot have both operands of a complex operation be real.");
  7250. switch (E->getOpcode()) {
  7251. default: return Error(E);
  7252. case BO_Add:
  7253. if (Result.isComplexFloat()) {
  7254. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  7255. APFloat::rmNearestTiesToEven);
  7256. if (LHSReal)
  7257. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  7258. else if (!RHSReal)
  7259. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  7260. APFloat::rmNearestTiesToEven);
  7261. } else {
  7262. Result.getComplexIntReal() += RHS.getComplexIntReal();
  7263. Result.getComplexIntImag() += RHS.getComplexIntImag();
  7264. }
  7265. break;
  7266. case BO_Sub:
  7267. if (Result.isComplexFloat()) {
  7268. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  7269. APFloat::rmNearestTiesToEven);
  7270. if (LHSReal) {
  7271. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  7272. Result.getComplexFloatImag().changeSign();
  7273. } else if (!RHSReal) {
  7274. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  7275. APFloat::rmNearestTiesToEven);
  7276. }
  7277. } else {
  7278. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  7279. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  7280. }
  7281. break;
  7282. case BO_Mul:
  7283. if (Result.isComplexFloat()) {
  7284. // This is an implementation of complex multiplication according to the
  7285. // constraints laid out in C11 Annex G. The implemantion uses the
  7286. // following naming scheme:
  7287. // (a + ib) * (c + id)
  7288. ComplexValue LHS = Result;
  7289. APFloat &A = LHS.getComplexFloatReal();
  7290. APFloat &B = LHS.getComplexFloatImag();
  7291. APFloat &C = RHS.getComplexFloatReal();
  7292. APFloat &D = RHS.getComplexFloatImag();
  7293. APFloat &ResR = Result.getComplexFloatReal();
  7294. APFloat &ResI = Result.getComplexFloatImag();
  7295. if (LHSReal) {
  7296. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  7297. ResR = A * C;
  7298. ResI = A * D;
  7299. } else if (RHSReal) {
  7300. ResR = C * A;
  7301. ResI = C * B;
  7302. } else {
  7303. // In the fully general case, we need to handle NaNs and infinities
  7304. // robustly.
  7305. APFloat AC = A * C;
  7306. APFloat BD = B * D;
  7307. APFloat AD = A * D;
  7308. APFloat BC = B * C;
  7309. ResR = AC - BD;
  7310. ResI = AD + BC;
  7311. if (ResR.isNaN() && ResI.isNaN()) {
  7312. bool Recalc = false;
  7313. if (A.isInfinity() || B.isInfinity()) {
  7314. A = APFloat::copySign(
  7315. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  7316. B = APFloat::copySign(
  7317. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  7318. if (C.isNaN())
  7319. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  7320. if (D.isNaN())
  7321. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  7322. Recalc = true;
  7323. }
  7324. if (C.isInfinity() || D.isInfinity()) {
  7325. C = APFloat::copySign(
  7326. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  7327. D = APFloat::copySign(
  7328. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  7329. if (A.isNaN())
  7330. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  7331. if (B.isNaN())
  7332. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  7333. Recalc = true;
  7334. }
  7335. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  7336. AD.isInfinity() || BC.isInfinity())) {
  7337. if (A.isNaN())
  7338. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  7339. if (B.isNaN())
  7340. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  7341. if (C.isNaN())
  7342. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  7343. if (D.isNaN())
  7344. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  7345. Recalc = true;
  7346. }
  7347. if (Recalc) {
  7348. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  7349. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  7350. }
  7351. }
  7352. }
  7353. } else {
  7354. ComplexValue LHS = Result;
  7355. Result.getComplexIntReal() =
  7356. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  7357. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  7358. Result.getComplexIntImag() =
  7359. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  7360. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  7361. }
  7362. break;
  7363. case BO_Div:
  7364. if (Result.isComplexFloat()) {
  7365. // This is an implementation of complex division according to the
  7366. // constraints laid out in C11 Annex G. The implemantion uses the
  7367. // following naming scheme:
  7368. // (a + ib) / (c + id)
  7369. ComplexValue LHS = Result;
  7370. APFloat &A = LHS.getComplexFloatReal();
  7371. APFloat &B = LHS.getComplexFloatImag();
  7372. APFloat &C = RHS.getComplexFloatReal();
  7373. APFloat &D = RHS.getComplexFloatImag();
  7374. APFloat &ResR = Result.getComplexFloatReal();
  7375. APFloat &ResI = Result.getComplexFloatImag();
  7376. if (RHSReal) {
  7377. ResR = A / C;
  7378. ResI = B / C;
  7379. } else {
  7380. if (LHSReal) {
  7381. // No real optimizations we can do here, stub out with zero.
  7382. B = APFloat::getZero(A.getSemantics());
  7383. }
  7384. int DenomLogB = 0;
  7385. APFloat MaxCD = maxnum(abs(C), abs(D));
  7386. if (MaxCD.isFinite()) {
  7387. DenomLogB = ilogb(MaxCD);
  7388. C = scalbn(C, -DenomLogB);
  7389. D = scalbn(D, -DenomLogB);
  7390. }
  7391. APFloat Denom = C * C + D * D;
  7392. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
  7393. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
  7394. if (ResR.isNaN() && ResI.isNaN()) {
  7395. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  7396. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  7397. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  7398. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  7399. D.isFinite()) {
  7400. A = APFloat::copySign(
  7401. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  7402. B = APFloat::copySign(
  7403. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  7404. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  7405. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  7406. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  7407. C = APFloat::copySign(
  7408. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  7409. D = APFloat::copySign(
  7410. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  7411. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  7412. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  7413. }
  7414. }
  7415. }
  7416. } else {
  7417. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  7418. return Error(E, diag::note_expr_divide_by_zero);
  7419. ComplexValue LHS = Result;
  7420. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  7421. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  7422. Result.getComplexIntReal() =
  7423. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  7424. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  7425. Result.getComplexIntImag() =
  7426. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  7427. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  7428. }
  7429. break;
  7430. }
  7431. return true;
  7432. }
  7433. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  7434. // Get the operand value into 'Result'.
  7435. if (!Visit(E->getSubExpr()))
  7436. return false;
  7437. switch (E->getOpcode()) {
  7438. default:
  7439. return Error(E);
  7440. case UO_Extension:
  7441. return true;
  7442. case UO_Plus:
  7443. // The result is always just the subexpr.
  7444. return true;
  7445. case UO_Minus:
  7446. if (Result.isComplexFloat()) {
  7447. Result.getComplexFloatReal().changeSign();
  7448. Result.getComplexFloatImag().changeSign();
  7449. }
  7450. else {
  7451. Result.getComplexIntReal() = -Result.getComplexIntReal();
  7452. Result.getComplexIntImag() = -Result.getComplexIntImag();
  7453. }
  7454. return true;
  7455. case UO_Not:
  7456. if (Result.isComplexFloat())
  7457. Result.getComplexFloatImag().changeSign();
  7458. else
  7459. Result.getComplexIntImag() = -Result.getComplexIntImag();
  7460. return true;
  7461. }
  7462. }
  7463. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7464. if (E->getNumInits() == 2) {
  7465. if (E->getType()->isComplexType()) {
  7466. Result.makeComplexFloat();
  7467. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  7468. return false;
  7469. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  7470. return false;
  7471. } else {
  7472. Result.makeComplexInt();
  7473. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  7474. return false;
  7475. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  7476. return false;
  7477. }
  7478. return true;
  7479. }
  7480. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  7481. }
  7482. //===----------------------------------------------------------------------===//
  7483. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  7484. // implicit conversion.
  7485. //===----------------------------------------------------------------------===//
  7486. namespace {
  7487. class AtomicExprEvaluator :
  7488. public ExprEvaluatorBase<AtomicExprEvaluator> {
  7489. APValue &Result;
  7490. public:
  7491. AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
  7492. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  7493. bool Success(const APValue &V, const Expr *E) {
  7494. Result = V;
  7495. return true;
  7496. }
  7497. bool ZeroInitialization(const Expr *E) {
  7498. ImplicitValueInitExpr VIE(
  7499. E->getType()->castAs<AtomicType>()->getValueType());
  7500. return Evaluate(Result, Info, &VIE);
  7501. }
  7502. bool VisitCastExpr(const CastExpr *E) {
  7503. switch (E->getCastKind()) {
  7504. default:
  7505. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7506. case CK_NonAtomicToAtomic:
  7507. return Evaluate(Result, Info, E->getSubExpr());
  7508. }
  7509. }
  7510. };
  7511. } // end anonymous namespace
  7512. static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
  7513. assert(E->isRValue() && E->getType()->isAtomicType());
  7514. return AtomicExprEvaluator(Info, Result).Visit(E);
  7515. }
  7516. //===----------------------------------------------------------------------===//
  7517. // Void expression evaluation, primarily for a cast to void on the LHS of a
  7518. // comma operator
  7519. //===----------------------------------------------------------------------===//
  7520. namespace {
  7521. class VoidExprEvaluator
  7522. : public ExprEvaluatorBase<VoidExprEvaluator> {
  7523. public:
  7524. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  7525. bool Success(const APValue &V, const Expr *e) { return true; }
  7526. bool VisitCastExpr(const CastExpr *E) {
  7527. switch (E->getCastKind()) {
  7528. default:
  7529. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7530. case CK_ToVoid:
  7531. VisitIgnoredValue(E->getSubExpr());
  7532. return true;
  7533. }
  7534. }
  7535. bool VisitCallExpr(const CallExpr *E) {
  7536. switch (E->getBuiltinCallee()) {
  7537. default:
  7538. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7539. case Builtin::BI__assume:
  7540. case Builtin::BI__builtin_assume:
  7541. // The argument is not evaluated!
  7542. return true;
  7543. }
  7544. }
  7545. };
  7546. } // end anonymous namespace
  7547. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  7548. assert(E->isRValue() && E->getType()->isVoidType());
  7549. return VoidExprEvaluator(Info).Visit(E);
  7550. }
  7551. //===----------------------------------------------------------------------===//
  7552. // Top level Expr::EvaluateAsRValue method.
  7553. //===----------------------------------------------------------------------===//
  7554. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  7555. // In C, function designators are not lvalues, but we evaluate them as if they
  7556. // are.
  7557. // HLSL Change Begins.
  7558. if (Info.getLangOpts().HLSL) {
  7559. if (E->isRValue() && hlsl::IsHLSLVecType(E->getType()) && EvaluateVector(E, Result, Info))
  7560. return true;
  7561. if (E->getStmtClass() == Stmt::InitListExprClass && !E->getType()->isScalarType())
  7562. return false;
  7563. if (E->getStmtClass() == Stmt::DeclRefExprClass) {
  7564. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  7565. const ValueDecl *VD = DRE->getDecl();
  7566. // External variable is in cbuffer, cannot use as immediate.
  7567. if (VD->hasExternalFormalLinkage() &&
  7568. !isa<EnumConstantDecl>(VD))
  7569. return false;
  7570. }
  7571. }
  7572. // HLSL Change Ends.
  7573. QualType T = E->getType();
  7574. if (E->isGLValue() || T->isFunctionType()) {
  7575. LValue LV;
  7576. if (!EvaluateLValue(E, LV, Info))
  7577. return false;
  7578. LV.moveInto(Result);
  7579. } else if (T->isVectorType()) {
  7580. if (!EvaluateVector(E, Result, Info))
  7581. return false;
  7582. } else if (T->isIntegralOrEnumerationType()) {
  7583. if (!IntExprEvaluator(Info, Result).Visit(E))
  7584. return false;
  7585. } else if (T->hasPointerRepresentation()) {
  7586. LValue LV;
  7587. if (!EvaluatePointer(E, LV, Info))
  7588. return false;
  7589. LV.moveInto(Result);
  7590. } else if (T->isRealFloatingType()) {
  7591. llvm::APFloat F(0.0);
  7592. if (!EvaluateFloat(E, F, Info))
  7593. return false;
  7594. Result = APValue(F);
  7595. } else if (T->isAnyComplexType()) {
  7596. ComplexValue C;
  7597. if (!EvaluateComplex(E, C, Info))
  7598. return false;
  7599. C.moveInto(Result);
  7600. } else if (T->isMemberPointerType()) {
  7601. MemberPtr P;
  7602. if (!EvaluateMemberPointer(E, P, Info))
  7603. return false;
  7604. P.moveInto(Result);
  7605. return true;
  7606. } else if (T->isArrayType()) {
  7607. LValue LV;
  7608. LV.set(E, Info.CurrentCall->Index);
  7609. APValue &Value = Info.CurrentCall->createTemporary(E, false);
  7610. if (!EvaluateArray(E, LV, Value, Info))
  7611. return false;
  7612. Result = Value;
  7613. } else if (T->isRecordType()) {
  7614. LValue LV;
  7615. LV.set(E, Info.CurrentCall->Index);
  7616. APValue &Value = Info.CurrentCall->createTemporary(E, false);
  7617. if (!EvaluateRecord(E, LV, Value, Info))
  7618. return false;
  7619. Result = Value;
  7620. } else if (T->isVoidType()) {
  7621. if (!Info.getLangOpts().CPlusPlus11)
  7622. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  7623. << E->getType();
  7624. if (!EvaluateVoid(E, Info))
  7625. return false;
  7626. } else if (T->isAtomicType()) {
  7627. if (!EvaluateAtomic(E, Result, Info))
  7628. return false;
  7629. } else if (Info.getLangOpts().CPlusPlus11) {
  7630. Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
  7631. return false;
  7632. } else {
  7633. Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
  7634. return false;
  7635. }
  7636. return true;
  7637. }
  7638. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  7639. /// cases, the in-place evaluation is essential, since later initializers for
  7640. /// an object can indirectly refer to subobjects which were initialized earlier.
  7641. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  7642. const Expr *E, bool AllowNonLiteralTypes) {
  7643. assert(!E->isValueDependent());
  7644. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  7645. return false;
  7646. if (E->isRValue()) {
  7647. // Evaluate arrays and record types in-place, so that later initializers can
  7648. // refer to earlier-initialized members of the object.
  7649. if (E->getType()->isArrayType())
  7650. return EvaluateArray(E, This, Result, Info);
  7651. else if (E->getType()->isRecordType())
  7652. return EvaluateRecord(E, This, Result, Info);
  7653. }
  7654. // For any other type, in-place evaluation is unimportant.
  7655. return Evaluate(Result, Info, E);
  7656. }
  7657. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  7658. /// lvalue-to-rvalue cast if it is an lvalue.
  7659. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  7660. if (E->getType().isNull())
  7661. return false;
  7662. if (!CheckLiteralType(Info, E))
  7663. return false;
  7664. if (!::Evaluate(Result, Info, E))
  7665. return false;
  7666. if (E->isGLValue()) {
  7667. LValue LV;
  7668. LV.setFrom(Info.Ctx, Result);
  7669. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  7670. return false;
  7671. }
  7672. // Check this core constant expression is a constant expression.
  7673. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  7674. }
  7675. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  7676. const ASTContext &Ctx, bool &IsConst) {
  7677. // Fast-path evaluations of integer literals, since we sometimes see files
  7678. // containing vast quantities of these.
  7679. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  7680. Result.Val = APValue(APSInt(L->getValue(),
  7681. L->getType()->isUnsignedIntegerType()));
  7682. IsConst = true;
  7683. return true;
  7684. }
  7685. // This case should be rare, but we need to check it before we check on
  7686. // the type below.
  7687. if (Exp->getType().isNull()) {
  7688. IsConst = false;
  7689. return true;
  7690. }
  7691. // FIXME: Evaluating values of large array and record types can cause
  7692. // performance problems. Only do so in C++11 for now.
  7693. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  7694. Exp->getType()->isRecordType()) &&
  7695. !hlsl::IsHLSLVecMatType(Exp->getType()) && // HLSL Change
  7696. !Ctx.getLangOpts().CPlusPlus11) {
  7697. IsConst = false;
  7698. return true;
  7699. }
  7700. return false;
  7701. }
  7702. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  7703. /// any crazy technique (that has nothing to do with language standards) that
  7704. /// we want to. If this function returns true, it returns the folded constant
  7705. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  7706. /// will be applied to the result.
  7707. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  7708. bool IsConst;
  7709. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
  7710. return IsConst;
  7711. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  7712. return ::EvaluateAsRValue(Info, this, Result.Val);
  7713. }
  7714. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  7715. const ASTContext &Ctx) const {
  7716. EvalResult Scratch;
  7717. return EvaluateAsRValue(Scratch, Ctx) &&
  7718. HandleConversionToBool(Scratch.Val, Result);
  7719. }
  7720. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  7721. SideEffectsKind AllowSideEffects) const {
  7722. if (!getType()->isIntegralOrEnumerationType())
  7723. return false;
  7724. EvalResult ExprResult;
  7725. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  7726. (!AllowSideEffects && ExprResult.HasSideEffects))
  7727. return false;
  7728. Result = ExprResult.Val.getInt();
  7729. return true;
  7730. }
  7731. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  7732. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  7733. LValue LV;
  7734. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  7735. !CheckLValueConstantExpression(Info, getExprLoc(),
  7736. Ctx.getLValueReferenceType(getType()), LV))
  7737. return false;
  7738. LV.moveInto(Result.Val);
  7739. return true;
  7740. }
  7741. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  7742. const VarDecl *VD,
  7743. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  7744. // FIXME: Evaluating initializers for large array and record types can cause
  7745. // performance problems. Only do so in C++11 for now.
  7746. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  7747. !Ctx.getLangOpts().CPlusPlus11)
  7748. return false;
  7749. Expr::EvalStatus EStatus;
  7750. EStatus.Diag = &Notes;
  7751. EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
  7752. InitInfo.setEvaluatingDecl(VD, Value);
  7753. LValue LVal;
  7754. LVal.set(VD);
  7755. // C++11 [basic.start.init]p2:
  7756. // Variables with static storage duration or thread storage duration shall be
  7757. // zero-initialized before any other initialization takes place.
  7758. // This behavior is not present in C.
  7759. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  7760. !VD->getType()->isReferenceType()) {
  7761. ImplicitValueInitExpr VIE(VD->getType());
  7762. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  7763. /*AllowNonLiteralTypes=*/true))
  7764. return false;
  7765. }
  7766. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  7767. /*AllowNonLiteralTypes=*/true) ||
  7768. EStatus.HasSideEffects)
  7769. return false;
  7770. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  7771. Value);
  7772. }
  7773. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  7774. /// constant folded, but discard the result.
  7775. bool Expr::isEvaluatable(const ASTContext &Ctx) const {
  7776. EvalResult Result;
  7777. return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
  7778. }
  7779. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  7780. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  7781. EvalResult EvalResult;
  7782. EvalResult.Diag = Diag;
  7783. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  7784. (void)Result;
  7785. assert(Result && "Could not evaluate expression");
  7786. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  7787. return EvalResult.Val.getInt();
  7788. }
  7789. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  7790. bool IsConst;
  7791. EvalResult EvalResult;
  7792. if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
  7793. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  7794. (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
  7795. }
  7796. }
  7797. bool Expr::EvalResult::isGlobalLValue() const {
  7798. assert(Val.isLValue());
  7799. return IsGlobalLValue(Val.getLValueBase());
  7800. }
  7801. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  7802. /// an integer constant expression.
  7803. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  7804. /// comma, etc
  7805. // CheckICE - This function does the fundamental ICE checking: the returned
  7806. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  7807. // and a (possibly null) SourceLocation indicating the location of the problem.
  7808. //
  7809. // Note that to reduce code duplication, this helper does no evaluation
  7810. // itself; the caller checks whether the expression is evaluatable, and
  7811. // in the rare cases where CheckICE actually cares about the evaluated
  7812. // value, it calls into Evalute.
  7813. namespace {
  7814. enum ICEKind {
  7815. /// This expression is an ICE.
  7816. IK_ICE,
  7817. /// This expression is not an ICE, but if it isn't evaluated, it's
  7818. /// a legal subexpression for an ICE. This return value is used to handle
  7819. /// the comma operator in C99 mode, and non-constant subexpressions.
  7820. IK_ICEIfUnevaluated,
  7821. /// This expression is not an ICE, and is not a legal subexpression for one.
  7822. IK_NotICE
  7823. };
  7824. struct ICEDiag {
  7825. ICEKind Kind;
  7826. SourceLocation Loc;
  7827. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  7828. };
  7829. }
  7830. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  7831. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  7832. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  7833. Expr::EvalResult EVResult;
  7834. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  7835. !EVResult.Val.isInt())
  7836. return ICEDiag(IK_NotICE, E->getLocStart());
  7837. return NoDiag();
  7838. }
  7839. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  7840. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  7841. if (!E->getType()->isIntegralOrEnumerationType())
  7842. return ICEDiag(IK_NotICE, E->getLocStart());
  7843. switch (E->getStmtClass()) {
  7844. #define ABSTRACT_STMT(Node)
  7845. #define STMT(Node, Base) case Expr::Node##Class:
  7846. #define EXPR(Node, Base)
  7847. #include "clang/AST/StmtNodes.inc"
  7848. case Expr::PredefinedExprClass:
  7849. case Expr::FloatingLiteralClass:
  7850. case Expr::ImaginaryLiteralClass:
  7851. case Expr::StringLiteralClass:
  7852. case Expr::ArraySubscriptExprClass:
  7853. case Expr::MemberExprClass:
  7854. case Expr::CompoundAssignOperatorClass:
  7855. case Expr::CompoundLiteralExprClass:
  7856. case Expr::ExtVectorElementExprClass:
  7857. case Expr::ExtMatrixElementExprClass: // HLSL Change
  7858. case Expr::HLSLVectorElementExprClass: // HLSL Change
  7859. case Expr::DesignatedInitExprClass:
  7860. case Expr::NoInitExprClass:
  7861. case Expr::DesignatedInitUpdateExprClass:
  7862. case Expr::ImplicitValueInitExprClass:
  7863. case Expr::ParenListExprClass:
  7864. case Expr::VAArgExprClass:
  7865. case Expr::AddrLabelExprClass:
  7866. case Expr::StmtExprClass:
  7867. case Expr::CXXMemberCallExprClass:
  7868. case Expr::CUDAKernelCallExprClass:
  7869. case Expr::CXXDynamicCastExprClass:
  7870. case Expr::CXXTypeidExprClass:
  7871. case Expr::CXXUuidofExprClass:
  7872. case Expr::MSPropertyRefExprClass:
  7873. case Expr::CXXNullPtrLiteralExprClass:
  7874. case Expr::UserDefinedLiteralClass:
  7875. case Expr::CXXThisExprClass:
  7876. case Expr::CXXThrowExprClass:
  7877. case Expr::CXXNewExprClass:
  7878. case Expr::CXXDeleteExprClass:
  7879. case Expr::CXXPseudoDestructorExprClass:
  7880. case Expr::UnresolvedLookupExprClass:
  7881. case Expr::TypoExprClass:
  7882. case Expr::DependentScopeDeclRefExprClass:
  7883. case Expr::CXXConstructExprClass:
  7884. case Expr::CXXStdInitializerListExprClass:
  7885. case Expr::CXXBindTemporaryExprClass:
  7886. case Expr::ExprWithCleanupsClass:
  7887. case Expr::CXXTemporaryObjectExprClass:
  7888. case Expr::CXXUnresolvedConstructExprClass:
  7889. case Expr::CXXDependentScopeMemberExprClass:
  7890. case Expr::UnresolvedMemberExprClass:
  7891. case Expr::ObjCStringLiteralClass:
  7892. case Expr::ObjCBoxedExprClass:
  7893. case Expr::ObjCArrayLiteralClass:
  7894. case Expr::ObjCDictionaryLiteralClass:
  7895. case Expr::ObjCEncodeExprClass:
  7896. case Expr::ObjCMessageExprClass:
  7897. case Expr::ObjCSelectorExprClass:
  7898. case Expr::ObjCProtocolExprClass:
  7899. case Expr::ObjCIvarRefExprClass:
  7900. case Expr::ObjCPropertyRefExprClass:
  7901. case Expr::ObjCSubscriptRefExprClass:
  7902. case Expr::ObjCIsaExprClass:
  7903. case Expr::ShuffleVectorExprClass:
  7904. case Expr::ConvertVectorExprClass:
  7905. case Expr::BlockExprClass:
  7906. case Expr::NoStmtClass:
  7907. case Expr::OpaqueValueExprClass:
  7908. case Expr::PackExpansionExprClass:
  7909. case Expr::SubstNonTypeTemplateParmPackExprClass:
  7910. case Expr::FunctionParmPackExprClass:
  7911. case Expr::AsTypeExprClass:
  7912. case Expr::ObjCIndirectCopyRestoreExprClass:
  7913. case Expr::MaterializeTemporaryExprClass:
  7914. case Expr::PseudoObjectExprClass:
  7915. case Expr::AtomicExprClass:
  7916. case Expr::LambdaExprClass:
  7917. case Expr::CXXFoldExprClass:
  7918. return ICEDiag(IK_NotICE, E->getLocStart());
  7919. case Expr::InitListExprClass: {
  7920. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  7921. // form "T x = { a };" is equivalent to "T x = a;".
  7922. // Unless we're initializing a reference, T is a scalar as it is known to be
  7923. // of integral or enumeration type.
  7924. if (E->isRValue() && (!Ctx.getLangOpts().HLSL || E->getType()->isScalarType() || IsHLSLVecInitList(E))) // HLSL Change
  7925. if (cast<InitListExpr>(E)->getNumInits() == 1)
  7926. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  7927. return ICEDiag(IK_NotICE, E->getLocStart());
  7928. }
  7929. case Expr::SizeOfPackExprClass:
  7930. case Expr::GNUNullExprClass:
  7931. // GCC considers the GNU __null value to be an integral constant expression.
  7932. return NoDiag();
  7933. case Expr::SubstNonTypeTemplateParmExprClass:
  7934. return
  7935. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  7936. case Expr::ParenExprClass:
  7937. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  7938. case Expr::GenericSelectionExprClass:
  7939. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  7940. case Expr::IntegerLiteralClass:
  7941. case Expr::CharacterLiteralClass:
  7942. case Expr::ObjCBoolLiteralExprClass:
  7943. case Expr::CXXBoolLiteralExprClass:
  7944. case Expr::CXXScalarValueInitExprClass:
  7945. case Expr::TypeTraitExprClass:
  7946. case Expr::ArrayTypeTraitExprClass:
  7947. case Expr::ExpressionTraitExprClass:
  7948. case Expr::CXXNoexceptExprClass:
  7949. return NoDiag();
  7950. case Expr::CallExprClass:
  7951. case Expr::CXXOperatorCallExprClass: {
  7952. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  7953. // constant expressions, but they can never be ICEs because an ICE cannot
  7954. // contain an operand of (pointer to) function type.
  7955. const CallExpr *CE = cast<CallExpr>(E);
  7956. if (hlsl::IsIntrinsicOp(GetCallExprFunction(CE)) || CE->getBuiltinCallee()) // HLSL Change
  7957. return CheckEvalInICE(E, Ctx);
  7958. return ICEDiag(IK_NotICE, E->getLocStart());
  7959. }
  7960. case Expr::DeclRefExprClass: {
  7961. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  7962. return NoDiag();
  7963. const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
  7964. if (Ctx.getLangOpts().CPlusPlus &&
  7965. D && IsConstNonVolatile(D->getType())) {
  7966. // Parameter variables are never constants. Without this check,
  7967. // getAnyInitializer() can find a default argument, which leads
  7968. // to chaos.
  7969. if (isa<ParmVarDecl>(D))
  7970. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  7971. // C++ 7.1.5.1p2
  7972. // A variable of non-volatile const-qualified integral or enumeration
  7973. // type initialized by an ICE can be used in ICEs.
  7974. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  7975. if (!Dcl->getType()->isIntegralOrEnumerationType())
  7976. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  7977. const VarDecl *VD;
  7978. // Look for a declaration of this variable that has an initializer, and
  7979. // check whether it is an ICE.
  7980. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  7981. return NoDiag();
  7982. else
  7983. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  7984. }
  7985. }
  7986. return ICEDiag(IK_NotICE, E->getLocStart());
  7987. }
  7988. case Expr::UnaryOperatorClass: {
  7989. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  7990. switch (Exp->getOpcode()) {
  7991. case UO_PostInc:
  7992. case UO_PostDec:
  7993. case UO_PreInc:
  7994. case UO_PreDec:
  7995. case UO_AddrOf:
  7996. case UO_Deref:
  7997. // C99 6.6/3 allows increment and decrement within unevaluated
  7998. // subexpressions of constant expressions, but they can never be ICEs
  7999. // because an ICE cannot contain an lvalue operand.
  8000. return ICEDiag(IK_NotICE, E->getLocStart());
  8001. case UO_Extension:
  8002. case UO_LNot:
  8003. case UO_Plus:
  8004. case UO_Minus:
  8005. case UO_Not:
  8006. case UO_Real:
  8007. case UO_Imag:
  8008. return CheckICE(Exp->getSubExpr(), Ctx);
  8009. }
  8010. // OffsetOf falls through here.
  8011. }
  8012. case Expr::OffsetOfExprClass: {
  8013. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  8014. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  8015. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  8016. // compliance: we should warn earlier for offsetof expressions with
  8017. // array subscripts that aren't ICEs, and if the array subscripts
  8018. // are ICEs, the value of the offsetof must be an integer constant.
  8019. return CheckEvalInICE(E, Ctx);
  8020. }
  8021. case Expr::UnaryExprOrTypeTraitExprClass: {
  8022. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  8023. if ((Exp->getKind() == UETT_SizeOf) &&
  8024. Exp->getTypeOfArgument()->isVariableArrayType())
  8025. return ICEDiag(IK_NotICE, E->getLocStart());
  8026. return NoDiag();
  8027. }
  8028. case Expr::BinaryOperatorClass: {
  8029. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  8030. switch (Exp->getOpcode()) {
  8031. case BO_PtrMemD:
  8032. case BO_PtrMemI:
  8033. case BO_Assign:
  8034. case BO_MulAssign:
  8035. case BO_DivAssign:
  8036. case BO_RemAssign:
  8037. case BO_AddAssign:
  8038. case BO_SubAssign:
  8039. case BO_ShlAssign:
  8040. case BO_ShrAssign:
  8041. case BO_AndAssign:
  8042. case BO_XorAssign:
  8043. case BO_OrAssign:
  8044. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  8045. // constant expressions, but they can never be ICEs because an ICE cannot
  8046. // contain an lvalue operand.
  8047. return ICEDiag(IK_NotICE, E->getLocStart());
  8048. case BO_Mul:
  8049. case BO_Div:
  8050. case BO_Rem:
  8051. case BO_Add:
  8052. case BO_Sub:
  8053. case BO_Shl:
  8054. case BO_Shr:
  8055. case BO_LT:
  8056. case BO_GT:
  8057. case BO_LE:
  8058. case BO_GE:
  8059. case BO_EQ:
  8060. case BO_NE:
  8061. case BO_And:
  8062. case BO_Xor:
  8063. case BO_Or:
  8064. case BO_Comma: {
  8065. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  8066. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  8067. if (Exp->getOpcode() == BO_Div ||
  8068. Exp->getOpcode() == BO_Rem) {
  8069. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  8070. // we don't evaluate one.
  8071. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  8072. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  8073. if (REval == 0)
  8074. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8075. if (REval.isSigned() && REval.isAllOnesValue()) {
  8076. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  8077. if (LEval.isMinSignedValue())
  8078. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8079. }
  8080. }
  8081. }
  8082. if (Exp->getOpcode() == BO_Comma && !Ctx.getLangOpts().HLSL) { // HLSL Change: comma is allowed in ICE
  8083. if (Ctx.getLangOpts().C99) {
  8084. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  8085. // if it isn't evaluated.
  8086. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  8087. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8088. } else {
  8089. // In both C89 and C++, commas in ICEs are illegal.
  8090. return ICEDiag(IK_NotICE, E->getLocStart());
  8091. }
  8092. }
  8093. return Worst(LHSResult, RHSResult);
  8094. }
  8095. case BO_LAnd:
  8096. case BO_LOr: {
  8097. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  8098. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  8099. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  8100. // Rare case where the RHS has a comma "side-effect"; we need
  8101. // to actually check the condition to see whether the side
  8102. // with the comma is evaluated.
  8103. if ((Exp->getOpcode() == BO_LAnd) !=
  8104. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  8105. return RHSResult;
  8106. return NoDiag();
  8107. }
  8108. return Worst(LHSResult, RHSResult);
  8109. }
  8110. }
  8111. }
  8112. case Expr::ImplicitCastExprClass:
  8113. case Expr::CStyleCastExprClass:
  8114. case Expr::CXXFunctionalCastExprClass:
  8115. case Expr::CXXStaticCastExprClass:
  8116. case Expr::CXXReinterpretCastExprClass:
  8117. case Expr::CXXConstCastExprClass:
  8118. case Expr::ObjCBridgedCastExprClass: {
  8119. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  8120. if (isa<ExplicitCastExpr>(E)) {
  8121. if (const FloatingLiteral *FL
  8122. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  8123. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  8124. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  8125. APSInt IgnoredVal(DestWidth, !DestSigned);
  8126. bool Ignored;
  8127. // If the value does not fit in the destination type, the behavior is
  8128. // undefined, so we are not required to treat it as a constant
  8129. // expression.
  8130. if (FL->getValue().convertToInteger(IgnoredVal,
  8131. llvm::APFloat::rmTowardZero,
  8132. &Ignored) & APFloat::opInvalidOp)
  8133. return ICEDiag(IK_NotICE, E->getLocStart());
  8134. return NoDiag();
  8135. }
  8136. }
  8137. switch (cast<CastExpr>(E)->getCastKind()) {
  8138. case CK_LValueToRValue:
  8139. case CK_AtomicToNonAtomic:
  8140. case CK_NonAtomicToAtomic:
  8141. case CK_NoOp:
  8142. case CK_IntegralToBoolean:
  8143. case CK_IntegralCast:
  8144. return CheckICE(SubExpr, Ctx);
  8145. default:
  8146. return ICEDiag(IK_NotICE, E->getLocStart());
  8147. }
  8148. }
  8149. case Expr::BinaryConditionalOperatorClass: {
  8150. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  8151. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  8152. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  8153. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  8154. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  8155. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  8156. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  8157. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  8158. return FalseResult;
  8159. }
  8160. case Expr::ConditionalOperatorClass: {
  8161. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  8162. // If the condition (ignoring parens) is a __builtin_constant_p call,
  8163. // then only the true side is actually considered in an integer constant
  8164. // expression, and it is fully evaluated. This is an important GNU
  8165. // extension. See GCC PR38377 for discussion.
  8166. if (const CallExpr *CallCE
  8167. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  8168. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  8169. return CheckEvalInICE(E, Ctx);
  8170. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  8171. if (CondResult.Kind == IK_NotICE)
  8172. return CondResult;
  8173. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  8174. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  8175. if (TrueResult.Kind == IK_NotICE)
  8176. return TrueResult;
  8177. if (FalseResult.Kind == IK_NotICE)
  8178. return FalseResult;
  8179. if (CondResult.Kind == IK_ICEIfUnevaluated)
  8180. return CondResult;
  8181. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  8182. return NoDiag();
  8183. // Rare case where the diagnostics depend on which side is evaluated
  8184. // Note that if we get here, CondResult is 0, and at least one of
  8185. // TrueResult and FalseResult is non-zero.
  8186. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  8187. return FalseResult;
  8188. return TrueResult;
  8189. }
  8190. case Expr::CXXDefaultArgExprClass:
  8191. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  8192. case Expr::CXXDefaultInitExprClass:
  8193. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  8194. case Expr::ChooseExprClass: {
  8195. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  8196. }
  8197. }
  8198. llvm_unreachable("Invalid StmtClass!");
  8199. }
  8200. /// Evaluate an expression as a C++11 integral constant expression.
  8201. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  8202. const Expr *E,
  8203. llvm::APSInt *Value,
  8204. SourceLocation *Loc) {
  8205. if (!E->getType()->isIntegralOrEnumerationType()) {
  8206. if (Loc) *Loc = E->getExprLoc();
  8207. return false;
  8208. }
  8209. APValue Result;
  8210. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  8211. return false;
  8212. if (!Result.isInt()) {
  8213. if (Loc) *Loc = E->getExprLoc();
  8214. return false;
  8215. }
  8216. if (Value) *Value = Result.getInt();
  8217. return true;
  8218. }
  8219. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  8220. SourceLocation *Loc) const {
  8221. if (Ctx.getLangOpts().CPlusPlus11)
  8222. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  8223. ICEDiag D = CheckICE(this, Ctx);
  8224. if (D.Kind != IK_ICE) {
  8225. if (Loc) *Loc = D.Loc;
  8226. return false;
  8227. }
  8228. return true;
  8229. }
  8230. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  8231. SourceLocation *Loc, bool isEvaluated) const {
  8232. if (Ctx.getLangOpts().CPlusPlus11)
  8233. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  8234. if (!isIntegerConstantExpr(Ctx, Loc))
  8235. return false;
  8236. if (!EvaluateAsInt(Value, Ctx))
  8237. llvm_unreachable("ICE cannot be evaluated!");
  8238. return true;
  8239. }
  8240. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  8241. return CheckICE(this, Ctx).Kind == IK_ICE;
  8242. }
  8243. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  8244. SourceLocation *Loc) const {
  8245. // We support this checking in C++98 mode in order to diagnose compatibility
  8246. // issues.
  8247. assert(Ctx.getLangOpts().CPlusPlus);
  8248. // Build evaluation settings.
  8249. Expr::EvalStatus Status;
  8250. SmallVector<PartialDiagnosticAt, 8> Diags;
  8251. Status.Diag = &Diags;
  8252. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  8253. APValue Scratch;
  8254. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  8255. if (!Diags.empty()) {
  8256. IsConstExpr = false;
  8257. if (Loc) *Loc = Diags[0].first;
  8258. } else if (!IsConstExpr) {
  8259. // FIXME: This shouldn't happen.
  8260. if (Loc) *Loc = getExprLoc();
  8261. }
  8262. return IsConstExpr;
  8263. }
  8264. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  8265. const FunctionDecl *Callee,
  8266. ArrayRef<const Expr*> Args) const {
  8267. Expr::EvalStatus Status;
  8268. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  8269. ArgVector ArgValues(Args.size());
  8270. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  8271. I != E; ++I) {
  8272. if ((*I)->isValueDependent() ||
  8273. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  8274. // If evaluation fails, throw away the argument entirely.
  8275. ArgValues[I - Args.begin()] = APValue();
  8276. if (Info.EvalStatus.HasSideEffects)
  8277. return false;
  8278. }
  8279. // Build fake call to Callee.
  8280. CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
  8281. ArgValues.data());
  8282. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  8283. }
  8284. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  8285. SmallVectorImpl<
  8286. PartialDiagnosticAt> &Diags) {
  8287. // FIXME: It would be useful to check constexpr function templates, but at the
  8288. // moment the constant expression evaluator cannot cope with the non-rigorous
  8289. // ASTs which we build for dependent expressions.
  8290. if (FD->isDependentContext())
  8291. return true;
  8292. Expr::EvalStatus Status;
  8293. Status.Diag = &Diags;
  8294. EvalInfo Info(FD->getASTContext(), Status,
  8295. EvalInfo::EM_PotentialConstantExpression);
  8296. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  8297. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  8298. // Fabricate an arbitrary expression on the stack and pretend that it
  8299. // is a temporary being used as the 'this' pointer.
  8300. LValue This;
  8301. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  8302. This.set(&VIE, Info.CurrentCall->Index);
  8303. ArrayRef<const Expr*> Args;
  8304. SourceLocation Loc = FD->getLocation();
  8305. APValue Scratch;
  8306. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  8307. // Evaluate the call as a constant initializer, to allow the construction
  8308. // of objects of non-literal types.
  8309. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  8310. HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
  8311. } else
  8312. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  8313. Args, FD->getBody(), Info, Scratch);
  8314. return Diags.empty();
  8315. }
  8316. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  8317. const FunctionDecl *FD,
  8318. SmallVectorImpl<
  8319. PartialDiagnosticAt> &Diags) {
  8320. Expr::EvalStatus Status;
  8321. Status.Diag = &Diags;
  8322. EvalInfo Info(FD->getASTContext(), Status,
  8323. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  8324. // Fabricate a call stack frame to give the arguments a plausible cover story.
  8325. ArrayRef<const Expr*> Args;
  8326. ArgVector ArgValues(0);
  8327. bool Success = EvaluateArgs(Args, ArgValues, Info);
  8328. (void)Success;
  8329. assert(Success &&
  8330. "Failed to set up arguments for potential constant evaluation");
  8331. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  8332. APValue ResultScratch;
  8333. Evaluate(ResultScratch, Info, E);
  8334. return Diags.empty();
  8335. }