ExprConstant.cpp 501 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Expr constant evaluator.
  10. //
  11. // Constant expression evaluation produces four main results:
  12. //
  13. // * A success/failure flag indicating whether constant folding was successful.
  14. // This is the 'bool' return value used by most of the code in this file. A
  15. // 'false' return value indicates that constant folding has failed, and any
  16. // appropriate diagnostic has already been produced.
  17. //
  18. // * An evaluated result, valid only if constant folding has not failed.
  19. //
  20. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  21. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  22. // where it is possible to determine the evaluated result regardless.
  23. //
  24. // * A set of notes indicating why the evaluation was not a constant expression
  25. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  26. // too, why the expression could not be folded.
  27. //
  28. // If we are checking for a potential constant expression, failure to constant
  29. // fold a potential constant sub-expression will be indicated by a 'false'
  30. // return value (the expression could not be folded) and no diagnostic (the
  31. // expression is not necessarily non-constant).
  32. //
  33. //===----------------------------------------------------------------------===//
  34. #include <cstring>
  35. #include <functional>
  36. #include "Interp/Context.h"
  37. #include "Interp/Frame.h"
  38. #include "Interp/State.h"
  39. #include "clang/AST/APValue.h"
  40. #include "clang/AST/ASTContext.h"
  41. #include "clang/AST/ASTDiagnostic.h"
  42. #include "clang/AST/ASTLambda.h"
  43. #include "clang/AST/CXXInheritance.h"
  44. #include "clang/AST/CharUnits.h"
  45. #include "clang/AST/CurrentSourceLocExprScope.h"
  46. #include "clang/AST/Expr.h"
  47. #include "clang/AST/OSLog.h"
  48. #include "clang/AST/OptionalDiagnostic.h"
  49. #include "clang/AST/RecordLayout.h"
  50. #include "clang/AST/StmtVisitor.h"
  51. #include "clang/AST/TypeLoc.h"
  52. #include "clang/Basic/Builtins.h"
  53. #include "clang/Basic/FixedPoint.h"
  54. #include "clang/Basic/TargetInfo.h"
  55. #include "llvm/ADT/Optional.h"
  56. #include "llvm/ADT/SmallBitVector.h"
  57. #include "llvm/Support/SaveAndRestore.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #define DEBUG_TYPE "exprconstant"
  60. using namespace clang;
  61. using llvm::APInt;
  62. using llvm::APSInt;
  63. using llvm::APFloat;
  64. using llvm::Optional;
  65. namespace {
  66. struct LValue;
  67. class CallStackFrame;
  68. class EvalInfo;
  69. using SourceLocExprScopeGuard =
  70. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  71. static QualType getType(APValue::LValueBase B) {
  72. if (!B) return QualType();
  73. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  74. // FIXME: It's unclear where we're supposed to take the type from, and
  75. // this actually matters for arrays of unknown bound. Eg:
  76. //
  77. // extern int arr[]; void f() { extern int arr[3]; };
  78. // constexpr int *p = &arr[1]; // valid?
  79. //
  80. // For now, we take the array bound from the most recent declaration.
  81. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  82. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  83. QualType T = Redecl->getType();
  84. if (!T->isIncompleteArrayType())
  85. return T;
  86. }
  87. return D->getType();
  88. }
  89. if (B.is<TypeInfoLValue>())
  90. return B.getTypeInfoType();
  91. if (B.is<DynamicAllocLValue>())
  92. return B.getDynamicAllocType();
  93. const Expr *Base = B.get<const Expr*>();
  94. // For a materialized temporary, the type of the temporary we materialized
  95. // may not be the type of the expression.
  96. if (const MaterializeTemporaryExpr *MTE =
  97. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  98. SmallVector<const Expr *, 2> CommaLHSs;
  99. SmallVector<SubobjectAdjustment, 2> Adjustments;
  100. const Expr *Temp = MTE->GetTemporaryExpr();
  101. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  102. Adjustments);
  103. // Keep any cv-qualifiers from the reference if we generated a temporary
  104. // for it directly. Otherwise use the type after adjustment.
  105. if (!Adjustments.empty())
  106. return Inner->getType();
  107. }
  108. return Base->getType();
  109. }
  110. /// Get an LValue path entry, which is known to not be an array index, as a
  111. /// field declaration.
  112. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  113. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  114. }
  115. /// Get an LValue path entry, which is known to not be an array index, as a
  116. /// base class declaration.
  117. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  118. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  119. }
  120. /// Determine whether this LValue path entry for a base class names a virtual
  121. /// base class.
  122. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  123. return E.getAsBaseOrMember().getInt();
  124. }
  125. /// Given an expression, determine the type used to store the result of
  126. /// evaluating that expression.
  127. static QualType getStorageType(ASTContext &Ctx, Expr *E) {
  128. if (E->isRValue())
  129. return E->getType();
  130. return Ctx.getLValueReferenceType(E->getType());
  131. }
  132. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  133. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  134. const FunctionDecl *Callee = CE->getDirectCallee();
  135. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  136. }
  137. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  138. /// This will look through a single cast.
  139. ///
  140. /// Returns null if we couldn't unwrap a function with alloc_size.
  141. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  142. if (!E->getType()->isPointerType())
  143. return nullptr;
  144. E = E->IgnoreParens();
  145. // If we're doing a variable assignment from e.g. malloc(N), there will
  146. // probably be a cast of some kind. In exotic cases, we might also see a
  147. // top-level ExprWithCleanups. Ignore them either way.
  148. if (const auto *FE = dyn_cast<FullExpr>(E))
  149. E = FE->getSubExpr()->IgnoreParens();
  150. if (const auto *Cast = dyn_cast<CastExpr>(E))
  151. E = Cast->getSubExpr()->IgnoreParens();
  152. if (const auto *CE = dyn_cast<CallExpr>(E))
  153. return getAllocSizeAttr(CE) ? CE : nullptr;
  154. return nullptr;
  155. }
  156. /// Determines whether or not the given Base contains a call to a function
  157. /// with the alloc_size attribute.
  158. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  159. const auto *E = Base.dyn_cast<const Expr *>();
  160. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  161. }
  162. /// The bound to claim that an array of unknown bound has.
  163. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  164. /// to an arbitrary value that's likely to loudly break things if it's used.
  165. static const uint64_t AssumedSizeForUnsizedArray =
  166. std::numeric_limits<uint64_t>::max() / 2;
  167. /// Determines if an LValue with the given LValueBase will have an unsized
  168. /// array in its designator.
  169. /// Find the path length and type of the most-derived subobject in the given
  170. /// path, and find the size of the containing array, if any.
  171. static unsigned
  172. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  173. ArrayRef<APValue::LValuePathEntry> Path,
  174. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  175. bool &FirstEntryIsUnsizedArray) {
  176. // This only accepts LValueBases from APValues, and APValues don't support
  177. // arrays that lack size info.
  178. assert(!isBaseAnAllocSizeCall(Base) &&
  179. "Unsized arrays shouldn't appear here");
  180. unsigned MostDerivedLength = 0;
  181. Type = getType(Base);
  182. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  183. if (Type->isArrayType()) {
  184. const ArrayType *AT = Ctx.getAsArrayType(Type);
  185. Type = AT->getElementType();
  186. MostDerivedLength = I + 1;
  187. IsArray = true;
  188. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  189. ArraySize = CAT->getSize().getZExtValue();
  190. } else {
  191. assert(I == 0 && "unexpected unsized array designator");
  192. FirstEntryIsUnsizedArray = true;
  193. ArraySize = AssumedSizeForUnsizedArray;
  194. }
  195. } else if (Type->isAnyComplexType()) {
  196. const ComplexType *CT = Type->castAs<ComplexType>();
  197. Type = CT->getElementType();
  198. ArraySize = 2;
  199. MostDerivedLength = I + 1;
  200. IsArray = true;
  201. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  202. Type = FD->getType();
  203. ArraySize = 0;
  204. MostDerivedLength = I + 1;
  205. IsArray = false;
  206. } else {
  207. // Path[I] describes a base class.
  208. ArraySize = 0;
  209. IsArray = false;
  210. }
  211. }
  212. return MostDerivedLength;
  213. }
  214. /// A path from a glvalue to a subobject of that glvalue.
  215. struct SubobjectDesignator {
  216. /// True if the subobject was named in a manner not supported by C++11. Such
  217. /// lvalues can still be folded, but they are not core constant expressions
  218. /// and we cannot perform lvalue-to-rvalue conversions on them.
  219. unsigned Invalid : 1;
  220. /// Is this a pointer one past the end of an object?
  221. unsigned IsOnePastTheEnd : 1;
  222. /// Indicator of whether the first entry is an unsized array.
  223. unsigned FirstEntryIsAnUnsizedArray : 1;
  224. /// Indicator of whether the most-derived object is an array element.
  225. unsigned MostDerivedIsArrayElement : 1;
  226. /// The length of the path to the most-derived object of which this is a
  227. /// subobject.
  228. unsigned MostDerivedPathLength : 28;
  229. /// The size of the array of which the most-derived object is an element.
  230. /// This will always be 0 if the most-derived object is not an array
  231. /// element. 0 is not an indicator of whether or not the most-derived object
  232. /// is an array, however, because 0-length arrays are allowed.
  233. ///
  234. /// If the current array is an unsized array, the value of this is
  235. /// undefined.
  236. uint64_t MostDerivedArraySize;
  237. /// The type of the most derived object referred to by this address.
  238. QualType MostDerivedType;
  239. typedef APValue::LValuePathEntry PathEntry;
  240. /// The entries on the path from the glvalue to the designated subobject.
  241. SmallVector<PathEntry, 8> Entries;
  242. SubobjectDesignator() : Invalid(true) {}
  243. explicit SubobjectDesignator(QualType T)
  244. : Invalid(false), IsOnePastTheEnd(false),
  245. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  246. MostDerivedPathLength(0), MostDerivedArraySize(0),
  247. MostDerivedType(T) {}
  248. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  249. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  250. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  251. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  252. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  253. if (!Invalid) {
  254. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  255. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  256. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  257. if (V.getLValueBase()) {
  258. bool IsArray = false;
  259. bool FirstIsUnsizedArray = false;
  260. MostDerivedPathLength = findMostDerivedSubobject(
  261. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  262. MostDerivedType, IsArray, FirstIsUnsizedArray);
  263. MostDerivedIsArrayElement = IsArray;
  264. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  265. }
  266. }
  267. }
  268. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  269. unsigned NewLength) {
  270. if (Invalid)
  271. return;
  272. assert(Base && "cannot truncate path for null pointer");
  273. assert(NewLength <= Entries.size() && "not a truncation");
  274. if (NewLength == Entries.size())
  275. return;
  276. Entries.resize(NewLength);
  277. bool IsArray = false;
  278. bool FirstIsUnsizedArray = false;
  279. MostDerivedPathLength = findMostDerivedSubobject(
  280. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  281. FirstIsUnsizedArray);
  282. MostDerivedIsArrayElement = IsArray;
  283. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  284. }
  285. void setInvalid() {
  286. Invalid = true;
  287. Entries.clear();
  288. }
  289. /// Determine whether the most derived subobject is an array without a
  290. /// known bound.
  291. bool isMostDerivedAnUnsizedArray() const {
  292. assert(!Invalid && "Calling this makes no sense on invalid designators");
  293. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  294. }
  295. /// Determine what the most derived array's size is. Results in an assertion
  296. /// failure if the most derived array lacks a size.
  297. uint64_t getMostDerivedArraySize() const {
  298. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  299. return MostDerivedArraySize;
  300. }
  301. /// Determine whether this is a one-past-the-end pointer.
  302. bool isOnePastTheEnd() const {
  303. assert(!Invalid);
  304. if (IsOnePastTheEnd)
  305. return true;
  306. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  307. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  308. MostDerivedArraySize)
  309. return true;
  310. return false;
  311. }
  312. /// Get the range of valid index adjustments in the form
  313. /// {maximum value that can be subtracted from this pointer,
  314. /// maximum value that can be added to this pointer}
  315. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  316. if (Invalid || isMostDerivedAnUnsizedArray())
  317. return {0, 0};
  318. // [expr.add]p4: For the purposes of these operators, a pointer to a
  319. // nonarray object behaves the same as a pointer to the first element of
  320. // an array of length one with the type of the object as its element type.
  321. bool IsArray = MostDerivedPathLength == Entries.size() &&
  322. MostDerivedIsArrayElement;
  323. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  324. : (uint64_t)IsOnePastTheEnd;
  325. uint64_t ArraySize =
  326. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  327. return {ArrayIndex, ArraySize - ArrayIndex};
  328. }
  329. /// Check that this refers to a valid subobject.
  330. bool isValidSubobject() const {
  331. if (Invalid)
  332. return false;
  333. return !isOnePastTheEnd();
  334. }
  335. /// Check that this refers to a valid subobject, and if not, produce a
  336. /// relevant diagnostic and set the designator as invalid.
  337. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  338. /// Get the type of the designated object.
  339. QualType getType(ASTContext &Ctx) const {
  340. assert(!Invalid && "invalid designator has no subobject type");
  341. return MostDerivedPathLength == Entries.size()
  342. ? MostDerivedType
  343. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  344. }
  345. /// Update this designator to refer to the first element within this array.
  346. void addArrayUnchecked(const ConstantArrayType *CAT) {
  347. Entries.push_back(PathEntry::ArrayIndex(0));
  348. // This is a most-derived object.
  349. MostDerivedType = CAT->getElementType();
  350. MostDerivedIsArrayElement = true;
  351. MostDerivedArraySize = CAT->getSize().getZExtValue();
  352. MostDerivedPathLength = Entries.size();
  353. }
  354. /// Update this designator to refer to the first element within the array of
  355. /// elements of type T. This is an array of unknown size.
  356. void addUnsizedArrayUnchecked(QualType ElemTy) {
  357. Entries.push_back(PathEntry::ArrayIndex(0));
  358. MostDerivedType = ElemTy;
  359. MostDerivedIsArrayElement = true;
  360. // The value in MostDerivedArraySize is undefined in this case. So, set it
  361. // to an arbitrary value that's likely to loudly break things if it's
  362. // used.
  363. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  364. MostDerivedPathLength = Entries.size();
  365. }
  366. /// Update this designator to refer to the given base or member of this
  367. /// object.
  368. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  369. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  370. // If this isn't a base class, it's a new most-derived object.
  371. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  372. MostDerivedType = FD->getType();
  373. MostDerivedIsArrayElement = false;
  374. MostDerivedArraySize = 0;
  375. MostDerivedPathLength = Entries.size();
  376. }
  377. }
  378. /// Update this designator to refer to the given complex component.
  379. void addComplexUnchecked(QualType EltTy, bool Imag) {
  380. Entries.push_back(PathEntry::ArrayIndex(Imag));
  381. // This is technically a most-derived object, though in practice this
  382. // is unlikely to matter.
  383. MostDerivedType = EltTy;
  384. MostDerivedIsArrayElement = true;
  385. MostDerivedArraySize = 2;
  386. MostDerivedPathLength = Entries.size();
  387. }
  388. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  389. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  390. const APSInt &N);
  391. /// Add N to the address of this subobject.
  392. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  393. if (Invalid || !N) return;
  394. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  395. if (isMostDerivedAnUnsizedArray()) {
  396. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  397. // Can't verify -- trust that the user is doing the right thing (or if
  398. // not, trust that the caller will catch the bad behavior).
  399. // FIXME: Should we reject if this overflows, at least?
  400. Entries.back() = PathEntry::ArrayIndex(
  401. Entries.back().getAsArrayIndex() + TruncatedN);
  402. return;
  403. }
  404. // [expr.add]p4: For the purposes of these operators, a pointer to a
  405. // nonarray object behaves the same as a pointer to the first element of
  406. // an array of length one with the type of the object as its element type.
  407. bool IsArray = MostDerivedPathLength == Entries.size() &&
  408. MostDerivedIsArrayElement;
  409. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  410. : (uint64_t)IsOnePastTheEnd;
  411. uint64_t ArraySize =
  412. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  413. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  414. // Calculate the actual index in a wide enough type, so we can include
  415. // it in the note.
  416. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  417. (llvm::APInt&)N += ArrayIndex;
  418. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  419. diagnosePointerArithmetic(Info, E, N);
  420. setInvalid();
  421. return;
  422. }
  423. ArrayIndex += TruncatedN;
  424. assert(ArrayIndex <= ArraySize &&
  425. "bounds check succeeded for out-of-bounds index");
  426. if (IsArray)
  427. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  428. else
  429. IsOnePastTheEnd = (ArrayIndex != 0);
  430. }
  431. };
  432. /// A stack frame in the constexpr call stack.
  433. class CallStackFrame : public interp::Frame {
  434. public:
  435. EvalInfo &Info;
  436. /// Parent - The caller of this stack frame.
  437. CallStackFrame *Caller;
  438. /// Callee - The function which was called.
  439. const FunctionDecl *Callee;
  440. /// This - The binding for the this pointer in this call, if any.
  441. const LValue *This;
  442. /// Arguments - Parameter bindings for this function call, indexed by
  443. /// parameters' function scope indices.
  444. APValue *Arguments;
  445. /// Source location information about the default argument or default
  446. /// initializer expression we're evaluating, if any.
  447. CurrentSourceLocExprScope CurSourceLocExprScope;
  448. // Note that we intentionally use std::map here so that references to
  449. // values are stable.
  450. typedef std::pair<const void *, unsigned> MapKeyTy;
  451. typedef std::map<MapKeyTy, APValue> MapTy;
  452. /// Temporaries - Temporary lvalues materialized within this stack frame.
  453. MapTy Temporaries;
  454. /// CallLoc - The location of the call expression for this call.
  455. SourceLocation CallLoc;
  456. /// Index - The call index of this call.
  457. unsigned Index;
  458. /// The stack of integers for tracking version numbers for temporaries.
  459. SmallVector<unsigned, 2> TempVersionStack = {1};
  460. unsigned CurTempVersion = TempVersionStack.back();
  461. unsigned getTempVersion() const { return TempVersionStack.back(); }
  462. void pushTempVersion() {
  463. TempVersionStack.push_back(++CurTempVersion);
  464. }
  465. void popTempVersion() {
  466. TempVersionStack.pop_back();
  467. }
  468. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  469. // on the overall stack usage of deeply-recursing constexpr evaluations.
  470. // (We should cache this map rather than recomputing it repeatedly.)
  471. // But let's try this and see how it goes; we can look into caching the map
  472. // as a later change.
  473. /// LambdaCaptureFields - Mapping from captured variables/this to
  474. /// corresponding data members in the closure class.
  475. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  476. FieldDecl *LambdaThisCaptureField;
  477. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  478. const FunctionDecl *Callee, const LValue *This,
  479. APValue *Arguments);
  480. ~CallStackFrame();
  481. // Return the temporary for Key whose version number is Version.
  482. APValue *getTemporary(const void *Key, unsigned Version) {
  483. MapKeyTy KV(Key, Version);
  484. auto LB = Temporaries.lower_bound(KV);
  485. if (LB != Temporaries.end() && LB->first == KV)
  486. return &LB->second;
  487. // Pair (Key,Version) wasn't found in the map. Check that no elements
  488. // in the map have 'Key' as their key.
  489. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  490. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  491. "Element with key 'Key' found in map");
  492. return nullptr;
  493. }
  494. // Return the current temporary for Key in the map.
  495. APValue *getCurrentTemporary(const void *Key) {
  496. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  497. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  498. return &std::prev(UB)->second;
  499. return nullptr;
  500. }
  501. // Return the version number of the current temporary for Key.
  502. unsigned getCurrentTemporaryVersion(const void *Key) const {
  503. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  504. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  505. return std::prev(UB)->first.second;
  506. return 0;
  507. }
  508. /// Allocate storage for an object of type T in this stack frame.
  509. /// Populates LV with a handle to the created object. Key identifies
  510. /// the temporary within the stack frame, and must not be reused without
  511. /// bumping the temporary version number.
  512. template<typename KeyT>
  513. APValue &createTemporary(const KeyT *Key, QualType T,
  514. bool IsLifetimeExtended, LValue &LV);
  515. void describe(llvm::raw_ostream &OS) override;
  516. Frame *getCaller() const override { return Caller; }
  517. SourceLocation getCallLocation() const override { return CallLoc; }
  518. const FunctionDecl *getCallee() const override { return Callee; }
  519. };
  520. /// Temporarily override 'this'.
  521. class ThisOverrideRAII {
  522. public:
  523. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  524. : Frame(Frame), OldThis(Frame.This) {
  525. if (Enable)
  526. Frame.This = NewThis;
  527. }
  528. ~ThisOverrideRAII() {
  529. Frame.This = OldThis;
  530. }
  531. private:
  532. CallStackFrame &Frame;
  533. const LValue *OldThis;
  534. };
  535. }
  536. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  537. const LValue &This, QualType ThisType);
  538. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  539. APValue::LValueBase LVBase, APValue &Value,
  540. QualType T);
  541. namespace {
  542. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  543. class Cleanup {
  544. llvm::PointerIntPair<APValue*, 1, bool> Value;
  545. APValue::LValueBase Base;
  546. QualType T;
  547. public:
  548. Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
  549. bool IsLifetimeExtended)
  550. : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
  551. bool isLifetimeExtended() const { return Value.getInt(); }
  552. bool endLifetime(EvalInfo &Info, bool RunDestructors) {
  553. if (RunDestructors) {
  554. SourceLocation Loc;
  555. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
  556. Loc = VD->getLocation();
  557. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  558. Loc = E->getExprLoc();
  559. return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
  560. }
  561. *Value.getPointer() = APValue();
  562. return true;
  563. }
  564. bool hasSideEffect() {
  565. return T.isDestructedType();
  566. }
  567. };
  568. /// A reference to an object whose construction we are currently evaluating.
  569. struct ObjectUnderConstruction {
  570. APValue::LValueBase Base;
  571. ArrayRef<APValue::LValuePathEntry> Path;
  572. friend bool operator==(const ObjectUnderConstruction &LHS,
  573. const ObjectUnderConstruction &RHS) {
  574. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  575. }
  576. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  577. return llvm::hash_combine(Obj.Base, Obj.Path);
  578. }
  579. };
  580. enum class ConstructionPhase {
  581. None,
  582. Bases,
  583. AfterBases,
  584. Destroying,
  585. DestroyingBases
  586. };
  587. }
  588. namespace llvm {
  589. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  590. using Base = DenseMapInfo<APValue::LValueBase>;
  591. static ObjectUnderConstruction getEmptyKey() {
  592. return {Base::getEmptyKey(), {}}; }
  593. static ObjectUnderConstruction getTombstoneKey() {
  594. return {Base::getTombstoneKey(), {}};
  595. }
  596. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  597. return hash_value(Object);
  598. }
  599. static bool isEqual(const ObjectUnderConstruction &LHS,
  600. const ObjectUnderConstruction &RHS) {
  601. return LHS == RHS;
  602. }
  603. };
  604. }
  605. namespace {
  606. /// EvalInfo - This is a private struct used by the evaluator to capture
  607. /// information about a subexpression as it is folded. It retains information
  608. /// about the AST context, but also maintains information about the folded
  609. /// expression.
  610. ///
  611. /// If an expression could be evaluated, it is still possible it is not a C
  612. /// "integer constant expression" or constant expression. If not, this struct
  613. /// captures information about how and why not.
  614. ///
  615. /// One bit of information passed *into* the request for constant folding
  616. /// indicates whether the subexpression is "evaluated" or not according to C
  617. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  618. /// evaluate the expression regardless of what the RHS is, but C only allows
  619. /// certain things in certain situations.
  620. class EvalInfo : public interp::State {
  621. public:
  622. ASTContext &Ctx;
  623. /// EvalStatus - Contains information about the evaluation.
  624. Expr::EvalStatus &EvalStatus;
  625. /// CurrentCall - The top of the constexpr call stack.
  626. CallStackFrame *CurrentCall;
  627. /// CallStackDepth - The number of calls in the call stack right now.
  628. unsigned CallStackDepth;
  629. /// NextCallIndex - The next call index to assign.
  630. unsigned NextCallIndex;
  631. /// StepsLeft - The remaining number of evaluation steps we're permitted
  632. /// to perform. This is essentially a limit for the number of statements
  633. /// we will evaluate.
  634. unsigned StepsLeft;
  635. /// Force the use of the experimental new constant interpreter, bailing out
  636. /// with an error if a feature is not supported.
  637. bool ForceNewConstInterp;
  638. /// Enable the experimental new constant interpreter.
  639. bool EnableNewConstInterp;
  640. /// BottomFrame - The frame in which evaluation started. This must be
  641. /// initialized after CurrentCall and CallStackDepth.
  642. CallStackFrame BottomFrame;
  643. /// A stack of values whose lifetimes end at the end of some surrounding
  644. /// evaluation frame.
  645. llvm::SmallVector<Cleanup, 16> CleanupStack;
  646. /// EvaluatingDecl - This is the declaration whose initializer is being
  647. /// evaluated, if any.
  648. APValue::LValueBase EvaluatingDecl;
  649. enum class EvaluatingDeclKind {
  650. None,
  651. /// We're evaluating the construction of EvaluatingDecl.
  652. Ctor,
  653. /// We're evaluating the destruction of EvaluatingDecl.
  654. Dtor,
  655. };
  656. EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
  657. /// EvaluatingDeclValue - This is the value being constructed for the
  658. /// declaration whose initializer is being evaluated, if any.
  659. APValue *EvaluatingDeclValue;
  660. /// Set of objects that are currently being constructed.
  661. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  662. ObjectsUnderConstruction;
  663. /// A dynamically-allocated heap object.
  664. struct DynAlloc {
  665. /// The value of this heap-allocated object.
  666. APValue Value;
  667. /// The allocating expression; used for diagnostics.
  668. const Expr *AllocExpr = nullptr;
  669. };
  670. struct DynAllocOrder {
  671. bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
  672. return L.getIndex() < R.getIndex();
  673. }
  674. };
  675. /// Current heap allocations, along with the location where each was
  676. /// allocated. We use std::map here because we need stable addresses
  677. /// for the stored APValues.
  678. std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
  679. /// The number of heap allocations performed so far in this evaluation.
  680. unsigned NumHeapAllocs = 0;
  681. struct EvaluatingConstructorRAII {
  682. EvalInfo &EI;
  683. ObjectUnderConstruction Object;
  684. bool DidInsert;
  685. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  686. bool HasBases)
  687. : EI(EI), Object(Object) {
  688. DidInsert =
  689. EI.ObjectsUnderConstruction
  690. .insert({Object, HasBases ? ConstructionPhase::Bases
  691. : ConstructionPhase::AfterBases})
  692. .second;
  693. }
  694. void finishedConstructingBases() {
  695. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  696. }
  697. ~EvaluatingConstructorRAII() {
  698. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  699. }
  700. };
  701. struct EvaluatingDestructorRAII {
  702. EvalInfo &EI;
  703. ObjectUnderConstruction Object;
  704. bool DidInsert;
  705. EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
  706. : EI(EI), Object(Object) {
  707. DidInsert = EI.ObjectsUnderConstruction
  708. .insert({Object, ConstructionPhase::Destroying})
  709. .second;
  710. }
  711. void startedDestroyingBases() {
  712. EI.ObjectsUnderConstruction[Object] =
  713. ConstructionPhase::DestroyingBases;
  714. }
  715. ~EvaluatingDestructorRAII() {
  716. if (DidInsert)
  717. EI.ObjectsUnderConstruction.erase(Object);
  718. }
  719. };
  720. ConstructionPhase
  721. isEvaluatingCtorDtor(APValue::LValueBase Base,
  722. ArrayRef<APValue::LValuePathEntry> Path) {
  723. return ObjectsUnderConstruction.lookup({Base, Path});
  724. }
  725. /// If we're currently speculatively evaluating, the outermost call stack
  726. /// depth at which we can mutate state, otherwise 0.
  727. unsigned SpeculativeEvaluationDepth = 0;
  728. /// The current array initialization index, if we're performing array
  729. /// initialization.
  730. uint64_t ArrayInitIndex = -1;
  731. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  732. /// notes attached to it will also be stored, otherwise they will not be.
  733. bool HasActiveDiagnostic;
  734. /// Have we emitted a diagnostic explaining why we couldn't constant
  735. /// fold (not just why it's not strictly a constant expression)?
  736. bool HasFoldFailureDiagnostic;
  737. /// Whether or not we're in a context where the front end requires a
  738. /// constant value.
  739. bool InConstantContext;
  740. /// Whether we're checking that an expression is a potential constant
  741. /// expression. If so, do not fail on constructs that could become constant
  742. /// later on (such as a use of an undefined global).
  743. bool CheckingPotentialConstantExpression = false;
  744. /// Whether we're checking for an expression that has undefined behavior.
  745. /// If so, we will produce warnings if we encounter an operation that is
  746. /// always undefined.
  747. bool CheckingForUndefinedBehavior = false;
  748. enum EvaluationMode {
  749. /// Evaluate as a constant expression. Stop if we find that the expression
  750. /// is not a constant expression.
  751. EM_ConstantExpression,
  752. /// Evaluate as a constant expression. Stop if we find that the expression
  753. /// is not a constant expression. Some expressions can be retried in the
  754. /// optimizer if we don't constant fold them here, but in an unevaluated
  755. /// context we try to fold them immediately since the optimizer never
  756. /// gets a chance to look at it.
  757. EM_ConstantExpressionUnevaluated,
  758. /// Fold the expression to a constant. Stop if we hit a side-effect that
  759. /// we can't model.
  760. EM_ConstantFold,
  761. /// Evaluate in any way we know how. Don't worry about side-effects that
  762. /// can't be modeled.
  763. EM_IgnoreSideEffects,
  764. } EvalMode;
  765. /// Are we checking whether the expression is a potential constant
  766. /// expression?
  767. bool checkingPotentialConstantExpression() const override {
  768. return CheckingPotentialConstantExpression;
  769. }
  770. /// Are we checking an expression for overflow?
  771. // FIXME: We should check for any kind of undefined or suspicious behavior
  772. // in such constructs, not just overflow.
  773. bool checkingForUndefinedBehavior() const override {
  774. return CheckingForUndefinedBehavior;
  775. }
  776. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  777. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  778. CallStackDepth(0), NextCallIndex(1),
  779. StepsLeft(getLangOpts().ConstexprStepLimit),
  780. ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
  781. EnableNewConstInterp(ForceNewConstInterp ||
  782. getLangOpts().EnableNewConstInterp),
  783. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  784. EvaluatingDecl((const ValueDecl *)nullptr),
  785. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  786. HasFoldFailureDiagnostic(false), InConstantContext(false),
  787. EvalMode(Mode) {}
  788. ~EvalInfo() {
  789. discardCleanups();
  790. }
  791. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
  792. EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
  793. EvaluatingDecl = Base;
  794. IsEvaluatingDecl = EDK;
  795. EvaluatingDeclValue = &Value;
  796. }
  797. bool CheckCallLimit(SourceLocation Loc) {
  798. // Don't perform any constexpr calls (other than the call we're checking)
  799. // when checking a potential constant expression.
  800. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  801. return false;
  802. if (NextCallIndex == 0) {
  803. // NextCallIndex has wrapped around.
  804. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  805. return false;
  806. }
  807. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  808. return true;
  809. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  810. << getLangOpts().ConstexprCallDepth;
  811. return false;
  812. }
  813. std::pair<CallStackFrame *, unsigned>
  814. getCallFrameAndDepth(unsigned CallIndex) {
  815. assert(CallIndex && "no call index in getCallFrameAndDepth");
  816. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  817. // be null in this loop.
  818. unsigned Depth = CallStackDepth;
  819. CallStackFrame *Frame = CurrentCall;
  820. while (Frame->Index > CallIndex) {
  821. Frame = Frame->Caller;
  822. --Depth;
  823. }
  824. if (Frame->Index == CallIndex)
  825. return {Frame, Depth};
  826. return {nullptr, 0};
  827. }
  828. bool nextStep(const Stmt *S) {
  829. if (!StepsLeft) {
  830. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  831. return false;
  832. }
  833. --StepsLeft;
  834. return true;
  835. }
  836. APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
  837. Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
  838. Optional<DynAlloc*> Result;
  839. auto It = HeapAllocs.find(DA);
  840. if (It != HeapAllocs.end())
  841. Result = &It->second;
  842. return Result;
  843. }
  844. void performLifetimeExtension() {
  845. // Disable the cleanups for lifetime-extended temporaries.
  846. CleanupStack.erase(
  847. std::remove_if(CleanupStack.begin(), CleanupStack.end(),
  848. [](Cleanup &C) { return C.isLifetimeExtended(); }),
  849. CleanupStack.end());
  850. }
  851. /// Throw away any remaining cleanups at the end of evaluation. If any
  852. /// cleanups would have had a side-effect, note that as an unmodeled
  853. /// side-effect and return false. Otherwise, return true.
  854. bool discardCleanups() {
  855. for (Cleanup &C : CleanupStack)
  856. if (C.hasSideEffect())
  857. if (!noteSideEffect())
  858. return false;
  859. return true;
  860. }
  861. private:
  862. interp::Frame *getCurrentFrame() override { return CurrentCall; }
  863. const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
  864. bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
  865. void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
  866. void setFoldFailureDiagnostic(bool Flag) override {
  867. HasFoldFailureDiagnostic = Flag;
  868. }
  869. Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
  870. ASTContext &getCtx() const override { return Ctx; }
  871. // If we have a prior diagnostic, it will be noting that the expression
  872. // isn't a constant expression. This diagnostic is more important,
  873. // unless we require this evaluation to produce a constant expression.
  874. //
  875. // FIXME: We might want to show both diagnostics to the user in
  876. // EM_ConstantFold mode.
  877. bool hasPriorDiagnostic() override {
  878. if (!EvalStatus.Diag->empty()) {
  879. switch (EvalMode) {
  880. case EM_ConstantFold:
  881. case EM_IgnoreSideEffects:
  882. if (!HasFoldFailureDiagnostic)
  883. break;
  884. // We've already failed to fold something. Keep that diagnostic.
  885. LLVM_FALLTHROUGH;
  886. case EM_ConstantExpression:
  887. case EM_ConstantExpressionUnevaluated:
  888. setActiveDiagnostic(false);
  889. return true;
  890. }
  891. }
  892. return false;
  893. }
  894. unsigned getCallStackDepth() override { return CallStackDepth; }
  895. public:
  896. /// Should we continue evaluation after encountering a side-effect that we
  897. /// couldn't model?
  898. bool keepEvaluatingAfterSideEffect() {
  899. switch (EvalMode) {
  900. case EM_IgnoreSideEffects:
  901. return true;
  902. case EM_ConstantExpression:
  903. case EM_ConstantExpressionUnevaluated:
  904. case EM_ConstantFold:
  905. // By default, assume any side effect might be valid in some other
  906. // evaluation of this expression from a different context.
  907. return checkingPotentialConstantExpression() ||
  908. checkingForUndefinedBehavior();
  909. }
  910. llvm_unreachable("Missed EvalMode case");
  911. }
  912. /// Note that we have had a side-effect, and determine whether we should
  913. /// keep evaluating.
  914. bool noteSideEffect() {
  915. EvalStatus.HasSideEffects = true;
  916. return keepEvaluatingAfterSideEffect();
  917. }
  918. /// Should we continue evaluation after encountering undefined behavior?
  919. bool keepEvaluatingAfterUndefinedBehavior() {
  920. switch (EvalMode) {
  921. case EM_IgnoreSideEffects:
  922. case EM_ConstantFold:
  923. return true;
  924. case EM_ConstantExpression:
  925. case EM_ConstantExpressionUnevaluated:
  926. return checkingForUndefinedBehavior();
  927. }
  928. llvm_unreachable("Missed EvalMode case");
  929. }
  930. /// Note that we hit something that was technically undefined behavior, but
  931. /// that we can evaluate past it (such as signed overflow or floating-point
  932. /// division by zero.)
  933. bool noteUndefinedBehavior() override {
  934. EvalStatus.HasUndefinedBehavior = true;
  935. return keepEvaluatingAfterUndefinedBehavior();
  936. }
  937. /// Should we continue evaluation as much as possible after encountering a
  938. /// construct which can't be reduced to a value?
  939. bool keepEvaluatingAfterFailure() const override {
  940. if (!StepsLeft)
  941. return false;
  942. switch (EvalMode) {
  943. case EM_ConstantExpression:
  944. case EM_ConstantExpressionUnevaluated:
  945. case EM_ConstantFold:
  946. case EM_IgnoreSideEffects:
  947. return checkingPotentialConstantExpression() ||
  948. checkingForUndefinedBehavior();
  949. }
  950. llvm_unreachable("Missed EvalMode case");
  951. }
  952. /// Notes that we failed to evaluate an expression that other expressions
  953. /// directly depend on, and determine if we should keep evaluating. This
  954. /// should only be called if we actually intend to keep evaluating.
  955. ///
  956. /// Call noteSideEffect() instead if we may be able to ignore the value that
  957. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  958. ///
  959. /// (Foo(), 1) // use noteSideEffect
  960. /// (Foo() || true) // use noteSideEffect
  961. /// Foo() + 1 // use noteFailure
  962. LLVM_NODISCARD bool noteFailure() {
  963. // Failure when evaluating some expression often means there is some
  964. // subexpression whose evaluation was skipped. Therefore, (because we
  965. // don't track whether we skipped an expression when unwinding after an
  966. // evaluation failure) every evaluation failure that bubbles up from a
  967. // subexpression implies that a side-effect has potentially happened. We
  968. // skip setting the HasSideEffects flag to true until we decide to
  969. // continue evaluating after that point, which happens here.
  970. bool KeepGoing = keepEvaluatingAfterFailure();
  971. EvalStatus.HasSideEffects |= KeepGoing;
  972. return KeepGoing;
  973. }
  974. class ArrayInitLoopIndex {
  975. EvalInfo &Info;
  976. uint64_t OuterIndex;
  977. public:
  978. ArrayInitLoopIndex(EvalInfo &Info)
  979. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  980. Info.ArrayInitIndex = 0;
  981. }
  982. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  983. operator uint64_t&() { return Info.ArrayInitIndex; }
  984. };
  985. };
  986. /// Object used to treat all foldable expressions as constant expressions.
  987. struct FoldConstant {
  988. EvalInfo &Info;
  989. bool Enabled;
  990. bool HadNoPriorDiags;
  991. EvalInfo::EvaluationMode OldMode;
  992. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  993. : Info(Info),
  994. Enabled(Enabled),
  995. HadNoPriorDiags(Info.EvalStatus.Diag &&
  996. Info.EvalStatus.Diag->empty() &&
  997. !Info.EvalStatus.HasSideEffects),
  998. OldMode(Info.EvalMode) {
  999. if (Enabled)
  1000. Info.EvalMode = EvalInfo::EM_ConstantFold;
  1001. }
  1002. void keepDiagnostics() { Enabled = false; }
  1003. ~FoldConstant() {
  1004. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  1005. !Info.EvalStatus.HasSideEffects)
  1006. Info.EvalStatus.Diag->clear();
  1007. Info.EvalMode = OldMode;
  1008. }
  1009. };
  1010. /// RAII object used to set the current evaluation mode to ignore
  1011. /// side-effects.
  1012. struct IgnoreSideEffectsRAII {
  1013. EvalInfo &Info;
  1014. EvalInfo::EvaluationMode OldMode;
  1015. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  1016. : Info(Info), OldMode(Info.EvalMode) {
  1017. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  1018. }
  1019. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  1020. };
  1021. /// RAII object used to optionally suppress diagnostics and side-effects from
  1022. /// a speculative evaluation.
  1023. class SpeculativeEvaluationRAII {
  1024. EvalInfo *Info = nullptr;
  1025. Expr::EvalStatus OldStatus;
  1026. unsigned OldSpeculativeEvaluationDepth;
  1027. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1028. Info = Other.Info;
  1029. OldStatus = Other.OldStatus;
  1030. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1031. Other.Info = nullptr;
  1032. }
  1033. void maybeRestoreState() {
  1034. if (!Info)
  1035. return;
  1036. Info->EvalStatus = OldStatus;
  1037. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1038. }
  1039. public:
  1040. SpeculativeEvaluationRAII() = default;
  1041. SpeculativeEvaluationRAII(
  1042. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1043. : Info(&Info), OldStatus(Info.EvalStatus),
  1044. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1045. Info.EvalStatus.Diag = NewDiag;
  1046. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1047. }
  1048. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1049. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1050. moveFromAndCancel(std::move(Other));
  1051. }
  1052. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1053. maybeRestoreState();
  1054. moveFromAndCancel(std::move(Other));
  1055. return *this;
  1056. }
  1057. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1058. };
  1059. /// RAII object wrapping a full-expression or block scope, and handling
  1060. /// the ending of the lifetime of temporaries created within it.
  1061. template<bool IsFullExpression>
  1062. class ScopeRAII {
  1063. EvalInfo &Info;
  1064. unsigned OldStackSize;
  1065. public:
  1066. ScopeRAII(EvalInfo &Info)
  1067. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1068. // Push a new temporary version. This is needed to distinguish between
  1069. // temporaries created in different iterations of a loop.
  1070. Info.CurrentCall->pushTempVersion();
  1071. }
  1072. bool destroy(bool RunDestructors = true) {
  1073. bool OK = cleanup(Info, RunDestructors, OldStackSize);
  1074. OldStackSize = -1U;
  1075. return OK;
  1076. }
  1077. ~ScopeRAII() {
  1078. if (OldStackSize != -1U)
  1079. destroy(false);
  1080. // Body moved to a static method to encourage the compiler to inline away
  1081. // instances of this class.
  1082. Info.CurrentCall->popTempVersion();
  1083. }
  1084. private:
  1085. static bool cleanup(EvalInfo &Info, bool RunDestructors,
  1086. unsigned OldStackSize) {
  1087. assert(OldStackSize <= Info.CleanupStack.size() &&
  1088. "running cleanups out of order?");
  1089. // Run all cleanups for a block scope, and non-lifetime-extended cleanups
  1090. // for a full-expression scope.
  1091. bool Success = true;
  1092. for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
  1093. if (!(IsFullExpression &&
  1094. Info.CleanupStack[I - 1].isLifetimeExtended())) {
  1095. if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
  1096. Success = false;
  1097. break;
  1098. }
  1099. }
  1100. }
  1101. // Compact lifetime-extended cleanups.
  1102. auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
  1103. if (IsFullExpression)
  1104. NewEnd =
  1105. std::remove_if(NewEnd, Info.CleanupStack.end(),
  1106. [](Cleanup &C) { return !C.isLifetimeExtended(); });
  1107. Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
  1108. return Success;
  1109. }
  1110. };
  1111. typedef ScopeRAII<false> BlockScopeRAII;
  1112. typedef ScopeRAII<true> FullExpressionRAII;
  1113. }
  1114. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1115. CheckSubobjectKind CSK) {
  1116. if (Invalid)
  1117. return false;
  1118. if (isOnePastTheEnd()) {
  1119. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1120. << CSK;
  1121. setInvalid();
  1122. return false;
  1123. }
  1124. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1125. // must actually be at least one array element; even a VLA cannot have a
  1126. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1127. return true;
  1128. }
  1129. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1130. const Expr *E) {
  1131. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1132. // Do not set the designator as invalid: we can represent this situation,
  1133. // and correct handling of __builtin_object_size requires us to do so.
  1134. }
  1135. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1136. const Expr *E,
  1137. const APSInt &N) {
  1138. // If we're complaining, we must be able to statically determine the size of
  1139. // the most derived array.
  1140. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1141. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1142. << N << /*array*/ 0
  1143. << static_cast<unsigned>(getMostDerivedArraySize());
  1144. else
  1145. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1146. << N << /*non-array*/ 1;
  1147. setInvalid();
  1148. }
  1149. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1150. const FunctionDecl *Callee, const LValue *This,
  1151. APValue *Arguments)
  1152. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1153. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1154. Info.CurrentCall = this;
  1155. ++Info.CallStackDepth;
  1156. }
  1157. CallStackFrame::~CallStackFrame() {
  1158. assert(Info.CurrentCall == this && "calls retired out of order");
  1159. --Info.CallStackDepth;
  1160. Info.CurrentCall = Caller;
  1161. }
  1162. static bool isRead(AccessKinds AK) {
  1163. return AK == AK_Read || AK == AK_ReadObjectRepresentation;
  1164. }
  1165. static bool isModification(AccessKinds AK) {
  1166. switch (AK) {
  1167. case AK_Read:
  1168. case AK_ReadObjectRepresentation:
  1169. case AK_MemberCall:
  1170. case AK_DynamicCast:
  1171. case AK_TypeId:
  1172. return false;
  1173. case AK_Assign:
  1174. case AK_Increment:
  1175. case AK_Decrement:
  1176. case AK_Destroy:
  1177. return true;
  1178. }
  1179. llvm_unreachable("unknown access kind");
  1180. }
  1181. static bool isAnyAccess(AccessKinds AK) {
  1182. return isRead(AK) || isModification(AK);
  1183. }
  1184. /// Is this an access per the C++ definition?
  1185. static bool isFormalAccess(AccessKinds AK) {
  1186. return isAnyAccess(AK) && AK != AK_Destroy;
  1187. }
  1188. namespace {
  1189. struct ComplexValue {
  1190. private:
  1191. bool IsInt;
  1192. public:
  1193. APSInt IntReal, IntImag;
  1194. APFloat FloatReal, FloatImag;
  1195. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1196. void makeComplexFloat() { IsInt = false; }
  1197. bool isComplexFloat() const { return !IsInt; }
  1198. APFloat &getComplexFloatReal() { return FloatReal; }
  1199. APFloat &getComplexFloatImag() { return FloatImag; }
  1200. void makeComplexInt() { IsInt = true; }
  1201. bool isComplexInt() const { return IsInt; }
  1202. APSInt &getComplexIntReal() { return IntReal; }
  1203. APSInt &getComplexIntImag() { return IntImag; }
  1204. void moveInto(APValue &v) const {
  1205. if (isComplexFloat())
  1206. v = APValue(FloatReal, FloatImag);
  1207. else
  1208. v = APValue(IntReal, IntImag);
  1209. }
  1210. void setFrom(const APValue &v) {
  1211. assert(v.isComplexFloat() || v.isComplexInt());
  1212. if (v.isComplexFloat()) {
  1213. makeComplexFloat();
  1214. FloatReal = v.getComplexFloatReal();
  1215. FloatImag = v.getComplexFloatImag();
  1216. } else {
  1217. makeComplexInt();
  1218. IntReal = v.getComplexIntReal();
  1219. IntImag = v.getComplexIntImag();
  1220. }
  1221. }
  1222. };
  1223. struct LValue {
  1224. APValue::LValueBase Base;
  1225. CharUnits Offset;
  1226. SubobjectDesignator Designator;
  1227. bool IsNullPtr : 1;
  1228. bool InvalidBase : 1;
  1229. const APValue::LValueBase getLValueBase() const { return Base; }
  1230. CharUnits &getLValueOffset() { return Offset; }
  1231. const CharUnits &getLValueOffset() const { return Offset; }
  1232. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1233. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1234. bool isNullPointer() const { return IsNullPtr;}
  1235. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1236. unsigned getLValueVersion() const { return Base.getVersion(); }
  1237. void moveInto(APValue &V) const {
  1238. if (Designator.Invalid)
  1239. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1240. else {
  1241. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1242. V = APValue(Base, Offset, Designator.Entries,
  1243. Designator.IsOnePastTheEnd, IsNullPtr);
  1244. }
  1245. }
  1246. void setFrom(ASTContext &Ctx, const APValue &V) {
  1247. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1248. Base = V.getLValueBase();
  1249. Offset = V.getLValueOffset();
  1250. InvalidBase = false;
  1251. Designator = SubobjectDesignator(Ctx, V);
  1252. IsNullPtr = V.isNullPointer();
  1253. }
  1254. void set(APValue::LValueBase B, bool BInvalid = false) {
  1255. #ifndef NDEBUG
  1256. // We only allow a few types of invalid bases. Enforce that here.
  1257. if (BInvalid) {
  1258. const auto *E = B.get<const Expr *>();
  1259. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1260. "Unexpected type of invalid base");
  1261. }
  1262. #endif
  1263. Base = B;
  1264. Offset = CharUnits::fromQuantity(0);
  1265. InvalidBase = BInvalid;
  1266. Designator = SubobjectDesignator(getType(B));
  1267. IsNullPtr = false;
  1268. }
  1269. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1270. Base = (Expr *)nullptr;
  1271. Offset = CharUnits::fromQuantity(TargetVal);
  1272. InvalidBase = false;
  1273. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1274. IsNullPtr = true;
  1275. }
  1276. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1277. set(B, true);
  1278. }
  1279. private:
  1280. // Check that this LValue is not based on a null pointer. If it is, produce
  1281. // a diagnostic and mark the designator as invalid.
  1282. template <typename GenDiagType>
  1283. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1284. if (Designator.Invalid)
  1285. return false;
  1286. if (IsNullPtr) {
  1287. GenDiag();
  1288. Designator.setInvalid();
  1289. return false;
  1290. }
  1291. return true;
  1292. }
  1293. public:
  1294. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1295. CheckSubobjectKind CSK) {
  1296. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1297. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1298. });
  1299. }
  1300. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1301. AccessKinds AK) {
  1302. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1303. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1304. });
  1305. }
  1306. // Check this LValue refers to an object. If not, set the designator to be
  1307. // invalid and emit a diagnostic.
  1308. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1309. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1310. Designator.checkSubobject(Info, E, CSK);
  1311. }
  1312. void addDecl(EvalInfo &Info, const Expr *E,
  1313. const Decl *D, bool Virtual = false) {
  1314. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1315. Designator.addDeclUnchecked(D, Virtual);
  1316. }
  1317. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1318. if (!Designator.Entries.empty()) {
  1319. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1320. Designator.setInvalid();
  1321. return;
  1322. }
  1323. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1324. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1325. Designator.FirstEntryIsAnUnsizedArray = true;
  1326. Designator.addUnsizedArrayUnchecked(ElemTy);
  1327. }
  1328. }
  1329. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1330. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1331. Designator.addArrayUnchecked(CAT);
  1332. }
  1333. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1334. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1335. Designator.addComplexUnchecked(EltTy, Imag);
  1336. }
  1337. void clearIsNullPointer() {
  1338. IsNullPtr = false;
  1339. }
  1340. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1341. const APSInt &Index, CharUnits ElementSize) {
  1342. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1343. // but we're not required to diagnose it and it's valid in C++.)
  1344. if (!Index)
  1345. return;
  1346. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1347. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1348. // offsets.
  1349. uint64_t Offset64 = Offset.getQuantity();
  1350. uint64_t ElemSize64 = ElementSize.getQuantity();
  1351. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1352. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1353. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1354. Designator.adjustIndex(Info, E, Index);
  1355. clearIsNullPointer();
  1356. }
  1357. void adjustOffset(CharUnits N) {
  1358. Offset += N;
  1359. if (N.getQuantity())
  1360. clearIsNullPointer();
  1361. }
  1362. };
  1363. struct MemberPtr {
  1364. MemberPtr() {}
  1365. explicit MemberPtr(const ValueDecl *Decl) :
  1366. DeclAndIsDerivedMember(Decl, false), Path() {}
  1367. /// The member or (direct or indirect) field referred to by this member
  1368. /// pointer, or 0 if this is a null member pointer.
  1369. const ValueDecl *getDecl() const {
  1370. return DeclAndIsDerivedMember.getPointer();
  1371. }
  1372. /// Is this actually a member of some type derived from the relevant class?
  1373. bool isDerivedMember() const {
  1374. return DeclAndIsDerivedMember.getInt();
  1375. }
  1376. /// Get the class which the declaration actually lives in.
  1377. const CXXRecordDecl *getContainingRecord() const {
  1378. return cast<CXXRecordDecl>(
  1379. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1380. }
  1381. void moveInto(APValue &V) const {
  1382. V = APValue(getDecl(), isDerivedMember(), Path);
  1383. }
  1384. void setFrom(const APValue &V) {
  1385. assert(V.isMemberPointer());
  1386. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1387. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1388. Path.clear();
  1389. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1390. Path.insert(Path.end(), P.begin(), P.end());
  1391. }
  1392. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1393. /// whether the member is a member of some class derived from the class type
  1394. /// of the member pointer.
  1395. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1396. /// Path - The path of base/derived classes from the member declaration's
  1397. /// class (exclusive) to the class type of the member pointer (inclusive).
  1398. SmallVector<const CXXRecordDecl*, 4> Path;
  1399. /// Perform a cast towards the class of the Decl (either up or down the
  1400. /// hierarchy).
  1401. bool castBack(const CXXRecordDecl *Class) {
  1402. assert(!Path.empty());
  1403. const CXXRecordDecl *Expected;
  1404. if (Path.size() >= 2)
  1405. Expected = Path[Path.size() - 2];
  1406. else
  1407. Expected = getContainingRecord();
  1408. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1409. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1410. // if B does not contain the original member and is not a base or
  1411. // derived class of the class containing the original member, the result
  1412. // of the cast is undefined.
  1413. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1414. // (D::*). We consider that to be a language defect.
  1415. return false;
  1416. }
  1417. Path.pop_back();
  1418. return true;
  1419. }
  1420. /// Perform a base-to-derived member pointer cast.
  1421. bool castToDerived(const CXXRecordDecl *Derived) {
  1422. if (!getDecl())
  1423. return true;
  1424. if (!isDerivedMember()) {
  1425. Path.push_back(Derived);
  1426. return true;
  1427. }
  1428. if (!castBack(Derived))
  1429. return false;
  1430. if (Path.empty())
  1431. DeclAndIsDerivedMember.setInt(false);
  1432. return true;
  1433. }
  1434. /// Perform a derived-to-base member pointer cast.
  1435. bool castToBase(const CXXRecordDecl *Base) {
  1436. if (!getDecl())
  1437. return true;
  1438. if (Path.empty())
  1439. DeclAndIsDerivedMember.setInt(true);
  1440. if (isDerivedMember()) {
  1441. Path.push_back(Base);
  1442. return true;
  1443. }
  1444. return castBack(Base);
  1445. }
  1446. };
  1447. /// Compare two member pointers, which are assumed to be of the same type.
  1448. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1449. if (!LHS.getDecl() || !RHS.getDecl())
  1450. return !LHS.getDecl() && !RHS.getDecl();
  1451. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1452. return false;
  1453. return LHS.Path == RHS.Path;
  1454. }
  1455. }
  1456. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1457. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1458. const LValue &This, const Expr *E,
  1459. bool AllowNonLiteralTypes = false);
  1460. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1461. bool InvalidBaseOK = false);
  1462. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1463. bool InvalidBaseOK = false);
  1464. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1465. EvalInfo &Info);
  1466. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1467. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1468. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1469. EvalInfo &Info);
  1470. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1471. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1472. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1473. EvalInfo &Info);
  1474. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1475. /// Evaluate an integer or fixed point expression into an APResult.
  1476. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1477. EvalInfo &Info);
  1478. /// Evaluate only a fixed point expression into an APResult.
  1479. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1480. EvalInfo &Info);
  1481. //===----------------------------------------------------------------------===//
  1482. // Misc utilities
  1483. //===----------------------------------------------------------------------===//
  1484. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1485. /// preserving its value (by extending by up to one bit as needed).
  1486. static void negateAsSigned(APSInt &Int) {
  1487. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1488. Int = Int.extend(Int.getBitWidth() + 1);
  1489. Int.setIsSigned(true);
  1490. }
  1491. Int = -Int;
  1492. }
  1493. template<typename KeyT>
  1494. APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
  1495. bool IsLifetimeExtended, LValue &LV) {
  1496. unsigned Version = getTempVersion();
  1497. APValue::LValueBase Base(Key, Index, Version);
  1498. LV.set(Base);
  1499. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1500. assert(Result.isAbsent() && "temporary created multiple times");
  1501. // If we're creating a temporary immediately in the operand of a speculative
  1502. // evaluation, don't register a cleanup to be run outside the speculative
  1503. // evaluation context, since we won't actually be able to initialize this
  1504. // object.
  1505. if (Index <= Info.SpeculativeEvaluationDepth) {
  1506. if (T.isDestructedType())
  1507. Info.noteSideEffect();
  1508. } else {
  1509. Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
  1510. }
  1511. return Result;
  1512. }
  1513. APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
  1514. if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
  1515. FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
  1516. return nullptr;
  1517. }
  1518. DynamicAllocLValue DA(NumHeapAllocs++);
  1519. LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
  1520. auto Result = HeapAllocs.emplace(std::piecewise_construct,
  1521. std::forward_as_tuple(DA), std::tuple<>());
  1522. assert(Result.second && "reused a heap alloc index?");
  1523. Result.first->second.AllocExpr = E;
  1524. return &Result.first->second.Value;
  1525. }
  1526. /// Produce a string describing the given constexpr call.
  1527. void CallStackFrame::describe(raw_ostream &Out) {
  1528. unsigned ArgIndex = 0;
  1529. bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
  1530. !isa<CXXConstructorDecl>(Callee) &&
  1531. cast<CXXMethodDecl>(Callee)->isInstance();
  1532. if (!IsMemberCall)
  1533. Out << *Callee << '(';
  1534. if (This && IsMemberCall) {
  1535. APValue Val;
  1536. This->moveInto(Val);
  1537. Val.printPretty(Out, Info.Ctx,
  1538. This->Designator.MostDerivedType);
  1539. // FIXME: Add parens around Val if needed.
  1540. Out << "->" << *Callee << '(';
  1541. IsMemberCall = false;
  1542. }
  1543. for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
  1544. E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1545. if (ArgIndex > (unsigned)IsMemberCall)
  1546. Out << ", ";
  1547. const ParmVarDecl *Param = *I;
  1548. const APValue &Arg = Arguments[ArgIndex];
  1549. Arg.printPretty(Out, Info.Ctx, Param->getType());
  1550. if (ArgIndex == 0 && IsMemberCall)
  1551. Out << "->" << *Callee << '(';
  1552. }
  1553. Out << ')';
  1554. }
  1555. /// Evaluate an expression to see if it had side-effects, and discard its
  1556. /// result.
  1557. /// \return \c true if the caller should keep evaluating.
  1558. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1559. APValue Scratch;
  1560. if (!Evaluate(Scratch, Info, E))
  1561. // We don't need the value, but we might have skipped a side effect here.
  1562. return Info.noteSideEffect();
  1563. return true;
  1564. }
  1565. /// Should this call expression be treated as a string literal?
  1566. static bool IsStringLiteralCall(const CallExpr *E) {
  1567. unsigned Builtin = E->getBuiltinCallee();
  1568. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1569. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1570. }
  1571. static bool IsGlobalLValue(APValue::LValueBase B) {
  1572. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1573. // constant expression of pointer type that evaluates to...
  1574. // ... a null pointer value, or a prvalue core constant expression of type
  1575. // std::nullptr_t.
  1576. if (!B) return true;
  1577. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1578. // ... the address of an object with static storage duration,
  1579. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1580. return VD->hasGlobalStorage();
  1581. // ... the address of a function,
  1582. return isa<FunctionDecl>(D);
  1583. }
  1584. if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
  1585. return true;
  1586. const Expr *E = B.get<const Expr*>();
  1587. switch (E->getStmtClass()) {
  1588. default:
  1589. return false;
  1590. case Expr::CompoundLiteralExprClass: {
  1591. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1592. return CLE->isFileScope() && CLE->isLValue();
  1593. }
  1594. case Expr::MaterializeTemporaryExprClass:
  1595. // A materialized temporary might have been lifetime-extended to static
  1596. // storage duration.
  1597. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1598. // A string literal has static storage duration.
  1599. case Expr::StringLiteralClass:
  1600. case Expr::PredefinedExprClass:
  1601. case Expr::ObjCStringLiteralClass:
  1602. case Expr::ObjCEncodeExprClass:
  1603. case Expr::CXXUuidofExprClass:
  1604. return true;
  1605. case Expr::ObjCBoxedExprClass:
  1606. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1607. case Expr::CallExprClass:
  1608. return IsStringLiteralCall(cast<CallExpr>(E));
  1609. // For GCC compatibility, &&label has static storage duration.
  1610. case Expr::AddrLabelExprClass:
  1611. return true;
  1612. // A Block literal expression may be used as the initialization value for
  1613. // Block variables at global or local static scope.
  1614. case Expr::BlockExprClass:
  1615. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1616. case Expr::ImplicitValueInitExprClass:
  1617. // FIXME:
  1618. // We can never form an lvalue with an implicit value initialization as its
  1619. // base through expression evaluation, so these only appear in one case: the
  1620. // implicit variable declaration we invent when checking whether a constexpr
  1621. // constructor can produce a constant expression. We must assume that such
  1622. // an expression might be a global lvalue.
  1623. return true;
  1624. }
  1625. }
  1626. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1627. return LVal.Base.dyn_cast<const ValueDecl*>();
  1628. }
  1629. static bool IsLiteralLValue(const LValue &Value) {
  1630. if (Value.getLValueCallIndex())
  1631. return false;
  1632. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1633. return E && !isa<MaterializeTemporaryExpr>(E);
  1634. }
  1635. static bool IsWeakLValue(const LValue &Value) {
  1636. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1637. return Decl && Decl->isWeak();
  1638. }
  1639. static bool isZeroSized(const LValue &Value) {
  1640. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1641. if (Decl && isa<VarDecl>(Decl)) {
  1642. QualType Ty = Decl->getType();
  1643. if (Ty->isArrayType())
  1644. return Ty->isIncompleteType() ||
  1645. Decl->getASTContext().getTypeSize(Ty) == 0;
  1646. }
  1647. return false;
  1648. }
  1649. static bool HasSameBase(const LValue &A, const LValue &B) {
  1650. if (!A.getLValueBase())
  1651. return !B.getLValueBase();
  1652. if (!B.getLValueBase())
  1653. return false;
  1654. if (A.getLValueBase().getOpaqueValue() !=
  1655. B.getLValueBase().getOpaqueValue()) {
  1656. const Decl *ADecl = GetLValueBaseDecl(A);
  1657. if (!ADecl)
  1658. return false;
  1659. const Decl *BDecl = GetLValueBaseDecl(B);
  1660. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1661. return false;
  1662. }
  1663. return IsGlobalLValue(A.getLValueBase()) ||
  1664. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1665. A.getLValueVersion() == B.getLValueVersion());
  1666. }
  1667. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1668. assert(Base && "no location for a null lvalue");
  1669. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1670. if (VD)
  1671. Info.Note(VD->getLocation(), diag::note_declared_at);
  1672. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1673. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1674. else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
  1675. // FIXME: Produce a note for dangling pointers too.
  1676. if (Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
  1677. Info.Note((*Alloc)->AllocExpr->getExprLoc(),
  1678. diag::note_constexpr_dynamic_alloc_here);
  1679. }
  1680. // We have no information to show for a typeid(T) object.
  1681. }
  1682. /// Check that this reference or pointer core constant expression is a valid
  1683. /// value for an address or reference constant expression. Return true if we
  1684. /// can fold this expression, whether or not it's a constant expression.
  1685. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1686. QualType Type, const LValue &LVal,
  1687. Expr::ConstExprUsage Usage) {
  1688. bool IsReferenceType = Type->isReferenceType();
  1689. APValue::LValueBase Base = LVal.getLValueBase();
  1690. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1691. // Check that the object is a global. Note that the fake 'this' object we
  1692. // manufacture when checking potential constant expressions is conservatively
  1693. // assumed to be global here.
  1694. if (!IsGlobalLValue(Base)) {
  1695. if (Info.getLangOpts().CPlusPlus11) {
  1696. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1697. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1698. << IsReferenceType << !Designator.Entries.empty()
  1699. << !!VD << VD;
  1700. NoteLValueLocation(Info, Base);
  1701. } else {
  1702. Info.FFDiag(Loc);
  1703. }
  1704. // Don't allow references to temporaries to escape.
  1705. return false;
  1706. }
  1707. assert((Info.checkingPotentialConstantExpression() ||
  1708. LVal.getLValueCallIndex() == 0) &&
  1709. "have call index for global lvalue");
  1710. if (Base.is<DynamicAllocLValue>()) {
  1711. Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
  1712. << IsReferenceType << !Designator.Entries.empty();
  1713. NoteLValueLocation(Info, Base);
  1714. return false;
  1715. }
  1716. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1717. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1718. // Check if this is a thread-local variable.
  1719. if (Var->getTLSKind())
  1720. // FIXME: Diagnostic!
  1721. return false;
  1722. // A dllimport variable never acts like a constant.
  1723. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1724. // FIXME: Diagnostic!
  1725. return false;
  1726. }
  1727. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1728. // __declspec(dllimport) must be handled very carefully:
  1729. // We must never initialize an expression with the thunk in C++.
  1730. // Doing otherwise would allow the same id-expression to yield
  1731. // different addresses for the same function in different translation
  1732. // units. However, this means that we must dynamically initialize the
  1733. // expression with the contents of the import address table at runtime.
  1734. //
  1735. // The C language has no notion of ODR; furthermore, it has no notion of
  1736. // dynamic initialization. This means that we are permitted to
  1737. // perform initialization with the address of the thunk.
  1738. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1739. FD->hasAttr<DLLImportAttr>())
  1740. // FIXME: Diagnostic!
  1741. return false;
  1742. }
  1743. }
  1744. // Allow address constant expressions to be past-the-end pointers. This is
  1745. // an extension: the standard requires them to point to an object.
  1746. if (!IsReferenceType)
  1747. return true;
  1748. // A reference constant expression must refer to an object.
  1749. if (!Base) {
  1750. // FIXME: diagnostic
  1751. Info.CCEDiag(Loc);
  1752. return true;
  1753. }
  1754. // Does this refer one past the end of some object?
  1755. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1756. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1757. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1758. << !Designator.Entries.empty() << !!VD << VD;
  1759. NoteLValueLocation(Info, Base);
  1760. }
  1761. return true;
  1762. }
  1763. /// Member pointers are constant expressions unless they point to a
  1764. /// non-virtual dllimport member function.
  1765. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1766. SourceLocation Loc,
  1767. QualType Type,
  1768. const APValue &Value,
  1769. Expr::ConstExprUsage Usage) {
  1770. const ValueDecl *Member = Value.getMemberPointerDecl();
  1771. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1772. if (!FD)
  1773. return true;
  1774. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1775. !FD->hasAttr<DLLImportAttr>();
  1776. }
  1777. /// Check that this core constant expression is of literal type, and if not,
  1778. /// produce an appropriate diagnostic.
  1779. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1780. const LValue *This = nullptr) {
  1781. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1782. return true;
  1783. // C++1y: A constant initializer for an object o [...] may also invoke
  1784. // constexpr constructors for o and its subobjects even if those objects
  1785. // are of non-literal class types.
  1786. //
  1787. // C++11 missed this detail for aggregates, so classes like this:
  1788. // struct foo_t { union { int i; volatile int j; } u; };
  1789. // are not (obviously) initializable like so:
  1790. // __attribute__((__require_constant_initialization__))
  1791. // static const foo_t x = {{0}};
  1792. // because "i" is a subobject with non-literal initialization (due to the
  1793. // volatile member of the union). See:
  1794. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1795. // Therefore, we use the C++1y behavior.
  1796. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1797. return true;
  1798. // Prvalue constant expressions must be of literal types.
  1799. if (Info.getLangOpts().CPlusPlus11)
  1800. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1801. << E->getType();
  1802. else
  1803. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1804. return false;
  1805. }
  1806. enum class CheckEvaluationResultKind {
  1807. ConstantExpression,
  1808. FullyInitialized,
  1809. };
  1810. static bool
  1811. CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info,
  1812. SourceLocation DiagLoc, QualType Type,
  1813. const APValue &Value, Expr::ConstExprUsage Usage,
  1814. SourceLocation SubobjectLoc = SourceLocation()) {
  1815. if (!Value.hasValue()) {
  1816. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1817. << true << Type;
  1818. if (SubobjectLoc.isValid())
  1819. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  1820. return false;
  1821. }
  1822. // We allow _Atomic(T) to be initialized from anything that T can be
  1823. // initialized from.
  1824. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1825. Type = AT->getValueType();
  1826. // Core issue 1454: For a literal constant expression of array or class type,
  1827. // each subobject of its value shall have been initialized by a constant
  1828. // expression.
  1829. if (Value.isArray()) {
  1830. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1831. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1832. if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  1833. Value.getArrayInitializedElt(I), Usage,
  1834. SubobjectLoc))
  1835. return false;
  1836. }
  1837. if (!Value.hasArrayFiller())
  1838. return true;
  1839. return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  1840. Value.getArrayFiller(), Usage, SubobjectLoc);
  1841. }
  1842. if (Value.isUnion() && Value.getUnionField()) {
  1843. return CheckEvaluationResult(
  1844. CERK, Info, DiagLoc, Value.getUnionField()->getType(),
  1845. Value.getUnionValue(), Usage, Value.getUnionField()->getLocation());
  1846. }
  1847. if (Value.isStruct()) {
  1848. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1849. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1850. unsigned BaseIndex = 0;
  1851. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1852. if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
  1853. Value.getStructBase(BaseIndex), Usage,
  1854. BS.getBeginLoc()))
  1855. return false;
  1856. ++BaseIndex;
  1857. }
  1858. }
  1859. for (const auto *I : RD->fields()) {
  1860. if (I->isUnnamedBitfield())
  1861. continue;
  1862. if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
  1863. Value.getStructField(I->getFieldIndex()),
  1864. Usage, I->getLocation()))
  1865. return false;
  1866. }
  1867. }
  1868. if (Value.isLValue() &&
  1869. CERK == CheckEvaluationResultKind::ConstantExpression) {
  1870. LValue LVal;
  1871. LVal.setFrom(Info.Ctx, Value);
  1872. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1873. }
  1874. if (Value.isMemberPointer() &&
  1875. CERK == CheckEvaluationResultKind::ConstantExpression)
  1876. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1877. // Everything else is fine.
  1878. return true;
  1879. }
  1880. /// Check that this core constant expression value is a valid value for a
  1881. /// constant expression. If not, report an appropriate diagnostic. Does not
  1882. /// check that the expression is of literal type.
  1883. static bool
  1884. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1885. const APValue &Value,
  1886. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1887. return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  1888. Info, DiagLoc, Type, Value, Usage);
  1889. }
  1890. /// Check that this evaluated value is fully-initialized and can be loaded by
  1891. /// an lvalue-to-rvalue conversion.
  1892. static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
  1893. QualType Type, const APValue &Value) {
  1894. return CheckEvaluationResult(CheckEvaluationResultKind::FullyInitialized,
  1895. Info, DiagLoc, Type, Value,
  1896. Expr::EvaluateForCodeGen);
  1897. }
  1898. /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
  1899. /// "the allocated storage is deallocated within the evaluation".
  1900. static bool CheckMemoryLeaks(EvalInfo &Info) {
  1901. if (!Info.HeapAllocs.empty()) {
  1902. // We can still fold to a constant despite a compile-time memory leak,
  1903. // so long as the heap allocation isn't referenced in the result (we check
  1904. // that in CheckConstantExpression).
  1905. Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
  1906. diag::note_constexpr_memory_leak)
  1907. << unsigned(Info.HeapAllocs.size() - 1);
  1908. }
  1909. return true;
  1910. }
  1911. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1912. // A null base expression indicates a null pointer. These are always
  1913. // evaluatable, and they are false unless the offset is zero.
  1914. if (!Value.getLValueBase()) {
  1915. Result = !Value.getLValueOffset().isZero();
  1916. return true;
  1917. }
  1918. // We have a non-null base. These are generally known to be true, but if it's
  1919. // a weak declaration it can be null at runtime.
  1920. Result = true;
  1921. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1922. return !Decl || !Decl->isWeak();
  1923. }
  1924. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1925. switch (Val.getKind()) {
  1926. case APValue::None:
  1927. case APValue::Indeterminate:
  1928. return false;
  1929. case APValue::Int:
  1930. Result = Val.getInt().getBoolValue();
  1931. return true;
  1932. case APValue::FixedPoint:
  1933. Result = Val.getFixedPoint().getBoolValue();
  1934. return true;
  1935. case APValue::Float:
  1936. Result = !Val.getFloat().isZero();
  1937. return true;
  1938. case APValue::ComplexInt:
  1939. Result = Val.getComplexIntReal().getBoolValue() ||
  1940. Val.getComplexIntImag().getBoolValue();
  1941. return true;
  1942. case APValue::ComplexFloat:
  1943. Result = !Val.getComplexFloatReal().isZero() ||
  1944. !Val.getComplexFloatImag().isZero();
  1945. return true;
  1946. case APValue::LValue:
  1947. return EvalPointerValueAsBool(Val, Result);
  1948. case APValue::MemberPointer:
  1949. Result = Val.getMemberPointerDecl();
  1950. return true;
  1951. case APValue::Vector:
  1952. case APValue::Array:
  1953. case APValue::Struct:
  1954. case APValue::Union:
  1955. case APValue::AddrLabelDiff:
  1956. return false;
  1957. }
  1958. llvm_unreachable("unknown APValue kind");
  1959. }
  1960. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1961. EvalInfo &Info) {
  1962. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1963. APValue Val;
  1964. if (!Evaluate(Val, Info, E))
  1965. return false;
  1966. return HandleConversionToBool(Val, Result);
  1967. }
  1968. template<typename T>
  1969. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1970. const T &SrcValue, QualType DestType) {
  1971. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1972. << SrcValue << DestType;
  1973. return Info.noteUndefinedBehavior();
  1974. }
  1975. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1976. QualType SrcType, const APFloat &Value,
  1977. QualType DestType, APSInt &Result) {
  1978. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1979. // Determine whether we are converting to unsigned or signed.
  1980. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1981. Result = APSInt(DestWidth, !DestSigned);
  1982. bool ignored;
  1983. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1984. & APFloat::opInvalidOp)
  1985. return HandleOverflow(Info, E, Value, DestType);
  1986. return true;
  1987. }
  1988. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1989. QualType SrcType, QualType DestType,
  1990. APFloat &Result) {
  1991. APFloat Value = Result;
  1992. bool ignored;
  1993. Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1994. APFloat::rmNearestTiesToEven, &ignored);
  1995. return true;
  1996. }
  1997. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1998. QualType DestType, QualType SrcType,
  1999. const APSInt &Value) {
  2000. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2001. // Figure out if this is a truncate, extend or noop cast.
  2002. // If the input is signed, do a sign extend, noop, or truncate.
  2003. APSInt Result = Value.extOrTrunc(DestWidth);
  2004. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  2005. if (DestType->isBooleanType())
  2006. Result = Value.getBoolValue();
  2007. return Result;
  2008. }
  2009. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  2010. QualType SrcType, const APSInt &Value,
  2011. QualType DestType, APFloat &Result) {
  2012. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  2013. Result.convertFromAPInt(Value, Value.isSigned(),
  2014. APFloat::rmNearestTiesToEven);
  2015. return true;
  2016. }
  2017. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  2018. APValue &Value, const FieldDecl *FD) {
  2019. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  2020. if (!Value.isInt()) {
  2021. // Trying to store a pointer-cast-to-integer into a bitfield.
  2022. // FIXME: In this case, we should provide the diagnostic for casting
  2023. // a pointer to an integer.
  2024. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  2025. Info.FFDiag(E);
  2026. return false;
  2027. }
  2028. APSInt &Int = Value.getInt();
  2029. unsigned OldBitWidth = Int.getBitWidth();
  2030. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  2031. if (NewBitWidth < OldBitWidth)
  2032. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  2033. return true;
  2034. }
  2035. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  2036. llvm::APInt &Res) {
  2037. APValue SVal;
  2038. if (!Evaluate(SVal, Info, E))
  2039. return false;
  2040. if (SVal.isInt()) {
  2041. Res = SVal.getInt();
  2042. return true;
  2043. }
  2044. if (SVal.isFloat()) {
  2045. Res = SVal.getFloat().bitcastToAPInt();
  2046. return true;
  2047. }
  2048. if (SVal.isVector()) {
  2049. QualType VecTy = E->getType();
  2050. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  2051. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  2052. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  2053. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  2054. Res = llvm::APInt::getNullValue(VecSize);
  2055. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  2056. APValue &Elt = SVal.getVectorElt(i);
  2057. llvm::APInt EltAsInt;
  2058. if (Elt.isInt()) {
  2059. EltAsInt = Elt.getInt();
  2060. } else if (Elt.isFloat()) {
  2061. EltAsInt = Elt.getFloat().bitcastToAPInt();
  2062. } else {
  2063. // Don't try to handle vectors of anything other than int or float
  2064. // (not sure if it's possible to hit this case).
  2065. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2066. return false;
  2067. }
  2068. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2069. if (BigEndian)
  2070. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2071. else
  2072. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2073. }
  2074. return true;
  2075. }
  2076. // Give up if the input isn't an int, float, or vector. For example, we
  2077. // reject "(v4i16)(intptr_t)&a".
  2078. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2079. return false;
  2080. }
  2081. /// Perform the given integer operation, which is known to need at most BitWidth
  2082. /// bits, and check for overflow in the original type (if that type was not an
  2083. /// unsigned type).
  2084. template<typename Operation>
  2085. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2086. const APSInt &LHS, const APSInt &RHS,
  2087. unsigned BitWidth, Operation Op,
  2088. APSInt &Result) {
  2089. if (LHS.isUnsigned()) {
  2090. Result = Op(LHS, RHS);
  2091. return true;
  2092. }
  2093. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2094. Result = Value.trunc(LHS.getBitWidth());
  2095. if (Result.extend(BitWidth) != Value) {
  2096. if (Info.checkingForUndefinedBehavior())
  2097. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2098. diag::warn_integer_constant_overflow)
  2099. << Result.toString(10) << E->getType();
  2100. else
  2101. return HandleOverflow(Info, E, Value, E->getType());
  2102. }
  2103. return true;
  2104. }
  2105. /// Perform the given binary integer operation.
  2106. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2107. BinaryOperatorKind Opcode, APSInt RHS,
  2108. APSInt &Result) {
  2109. switch (Opcode) {
  2110. default:
  2111. Info.FFDiag(E);
  2112. return false;
  2113. case BO_Mul:
  2114. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2115. std::multiplies<APSInt>(), Result);
  2116. case BO_Add:
  2117. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2118. std::plus<APSInt>(), Result);
  2119. case BO_Sub:
  2120. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2121. std::minus<APSInt>(), Result);
  2122. case BO_And: Result = LHS & RHS; return true;
  2123. case BO_Xor: Result = LHS ^ RHS; return true;
  2124. case BO_Or: Result = LHS | RHS; return true;
  2125. case BO_Div:
  2126. case BO_Rem:
  2127. if (RHS == 0) {
  2128. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2129. return false;
  2130. }
  2131. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2132. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2133. // this operation and gives the two's complement result.
  2134. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  2135. LHS.isSigned() && LHS.isMinSignedValue())
  2136. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  2137. E->getType());
  2138. return true;
  2139. case BO_Shl: {
  2140. if (Info.getLangOpts().OpenCL)
  2141. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2142. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2143. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2144. RHS.isUnsigned());
  2145. else if (RHS.isSigned() && RHS.isNegative()) {
  2146. // During constant-folding, a negative shift is an opposite shift. Such
  2147. // a shift is not a constant expression.
  2148. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2149. RHS = -RHS;
  2150. goto shift_right;
  2151. }
  2152. shift_left:
  2153. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2154. // the shifted type.
  2155. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2156. if (SA != RHS) {
  2157. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2158. << RHS << E->getType() << LHS.getBitWidth();
  2159. } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
  2160. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2161. // operand, and must not overflow the corresponding unsigned type.
  2162. // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
  2163. // E1 x 2^E2 module 2^N.
  2164. if (LHS.isNegative())
  2165. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2166. else if (LHS.countLeadingZeros() < SA)
  2167. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2168. }
  2169. Result = LHS << SA;
  2170. return true;
  2171. }
  2172. case BO_Shr: {
  2173. if (Info.getLangOpts().OpenCL)
  2174. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2175. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2176. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2177. RHS.isUnsigned());
  2178. else if (RHS.isSigned() && RHS.isNegative()) {
  2179. // During constant-folding, a negative shift is an opposite shift. Such a
  2180. // shift is not a constant expression.
  2181. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2182. RHS = -RHS;
  2183. goto shift_left;
  2184. }
  2185. shift_right:
  2186. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2187. // shifted type.
  2188. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2189. if (SA != RHS)
  2190. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2191. << RHS << E->getType() << LHS.getBitWidth();
  2192. Result = LHS >> SA;
  2193. return true;
  2194. }
  2195. case BO_LT: Result = LHS < RHS; return true;
  2196. case BO_GT: Result = LHS > RHS; return true;
  2197. case BO_LE: Result = LHS <= RHS; return true;
  2198. case BO_GE: Result = LHS >= RHS; return true;
  2199. case BO_EQ: Result = LHS == RHS; return true;
  2200. case BO_NE: Result = LHS != RHS; return true;
  2201. case BO_Cmp:
  2202. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2203. }
  2204. }
  2205. /// Perform the given binary floating-point operation, in-place, on LHS.
  2206. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2207. APFloat &LHS, BinaryOperatorKind Opcode,
  2208. const APFloat &RHS) {
  2209. switch (Opcode) {
  2210. default:
  2211. Info.FFDiag(E);
  2212. return false;
  2213. case BO_Mul:
  2214. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2215. break;
  2216. case BO_Add:
  2217. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2218. break;
  2219. case BO_Sub:
  2220. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2221. break;
  2222. case BO_Div:
  2223. // [expr.mul]p4:
  2224. // If the second operand of / or % is zero the behavior is undefined.
  2225. if (RHS.isZero())
  2226. Info.CCEDiag(E, diag::note_expr_divide_by_zero);
  2227. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2228. break;
  2229. }
  2230. // [expr.pre]p4:
  2231. // If during the evaluation of an expression, the result is not
  2232. // mathematically defined [...], the behavior is undefined.
  2233. // FIXME: C++ rules require us to not conform to IEEE 754 here.
  2234. if (LHS.isNaN()) {
  2235. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2236. return Info.noteUndefinedBehavior();
  2237. }
  2238. return true;
  2239. }
  2240. /// Cast an lvalue referring to a base subobject to a derived class, by
  2241. /// truncating the lvalue's path to the given length.
  2242. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2243. const RecordDecl *TruncatedType,
  2244. unsigned TruncatedElements) {
  2245. SubobjectDesignator &D = Result.Designator;
  2246. // Check we actually point to a derived class object.
  2247. if (TruncatedElements == D.Entries.size())
  2248. return true;
  2249. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2250. "not casting to a derived class");
  2251. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2252. return false;
  2253. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2254. const RecordDecl *RD = TruncatedType;
  2255. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2256. if (RD->isInvalidDecl()) return false;
  2257. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2258. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2259. if (isVirtualBaseClass(D.Entries[I]))
  2260. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2261. else
  2262. Result.Offset -= Layout.getBaseClassOffset(Base);
  2263. RD = Base;
  2264. }
  2265. D.Entries.resize(TruncatedElements);
  2266. return true;
  2267. }
  2268. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2269. const CXXRecordDecl *Derived,
  2270. const CXXRecordDecl *Base,
  2271. const ASTRecordLayout *RL = nullptr) {
  2272. if (!RL) {
  2273. if (Derived->isInvalidDecl()) return false;
  2274. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2275. }
  2276. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2277. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2278. return true;
  2279. }
  2280. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2281. const CXXRecordDecl *DerivedDecl,
  2282. const CXXBaseSpecifier *Base) {
  2283. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2284. if (!Base->isVirtual())
  2285. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2286. SubobjectDesignator &D = Obj.Designator;
  2287. if (D.Invalid)
  2288. return false;
  2289. // Extract most-derived object and corresponding type.
  2290. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2291. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2292. return false;
  2293. // Find the virtual base class.
  2294. if (DerivedDecl->isInvalidDecl()) return false;
  2295. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2296. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2297. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2298. return true;
  2299. }
  2300. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2301. QualType Type, LValue &Result) {
  2302. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2303. PathE = E->path_end();
  2304. PathI != PathE; ++PathI) {
  2305. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2306. *PathI))
  2307. return false;
  2308. Type = (*PathI)->getType();
  2309. }
  2310. return true;
  2311. }
  2312. /// Cast an lvalue referring to a derived class to a known base subobject.
  2313. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2314. const CXXRecordDecl *DerivedRD,
  2315. const CXXRecordDecl *BaseRD) {
  2316. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2317. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2318. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2319. llvm_unreachable("Class must be derived from the passed in base class!");
  2320. for (CXXBasePathElement &Elem : Paths.front())
  2321. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2322. return false;
  2323. return true;
  2324. }
  2325. /// Update LVal to refer to the given field, which must be a member of the type
  2326. /// currently described by LVal.
  2327. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2328. const FieldDecl *FD,
  2329. const ASTRecordLayout *RL = nullptr) {
  2330. if (!RL) {
  2331. if (FD->getParent()->isInvalidDecl()) return false;
  2332. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2333. }
  2334. unsigned I = FD->getFieldIndex();
  2335. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2336. LVal.addDecl(Info, E, FD);
  2337. return true;
  2338. }
  2339. /// Update LVal to refer to the given indirect field.
  2340. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2341. LValue &LVal,
  2342. const IndirectFieldDecl *IFD) {
  2343. for (const auto *C : IFD->chain())
  2344. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2345. return false;
  2346. return true;
  2347. }
  2348. /// Get the size of the given type in char units.
  2349. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2350. QualType Type, CharUnits &Size) {
  2351. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2352. // extension.
  2353. if (Type->isVoidType() || Type->isFunctionType()) {
  2354. Size = CharUnits::One();
  2355. return true;
  2356. }
  2357. if (Type->isDependentType()) {
  2358. Info.FFDiag(Loc);
  2359. return false;
  2360. }
  2361. if (!Type->isConstantSizeType()) {
  2362. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2363. // FIXME: Better diagnostic.
  2364. Info.FFDiag(Loc);
  2365. return false;
  2366. }
  2367. Size = Info.Ctx.getTypeSizeInChars(Type);
  2368. return true;
  2369. }
  2370. /// Update a pointer value to model pointer arithmetic.
  2371. /// \param Info - Information about the ongoing evaluation.
  2372. /// \param E - The expression being evaluated, for diagnostic purposes.
  2373. /// \param LVal - The pointer value to be updated.
  2374. /// \param EltTy - The pointee type represented by LVal.
  2375. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2376. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2377. LValue &LVal, QualType EltTy,
  2378. APSInt Adjustment) {
  2379. CharUnits SizeOfPointee;
  2380. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2381. return false;
  2382. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2383. return true;
  2384. }
  2385. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2386. LValue &LVal, QualType EltTy,
  2387. int64_t Adjustment) {
  2388. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2389. APSInt::get(Adjustment));
  2390. }
  2391. /// Update an lvalue to refer to a component of a complex number.
  2392. /// \param Info - Information about the ongoing evaluation.
  2393. /// \param LVal - The lvalue to be updated.
  2394. /// \param EltTy - The complex number's component type.
  2395. /// \param Imag - False for the real component, true for the imaginary.
  2396. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2397. LValue &LVal, QualType EltTy,
  2398. bool Imag) {
  2399. if (Imag) {
  2400. CharUnits SizeOfComponent;
  2401. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2402. return false;
  2403. LVal.Offset += SizeOfComponent;
  2404. }
  2405. LVal.addComplex(Info, E, EltTy, Imag);
  2406. return true;
  2407. }
  2408. /// Try to evaluate the initializer for a variable declaration.
  2409. ///
  2410. /// \param Info Information about the ongoing evaluation.
  2411. /// \param E An expression to be used when printing diagnostics.
  2412. /// \param VD The variable whose initializer should be obtained.
  2413. /// \param Frame The frame in which the variable was created. Must be null
  2414. /// if this variable is not local to the evaluation.
  2415. /// \param Result Filled in with a pointer to the value of the variable.
  2416. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2417. const VarDecl *VD, CallStackFrame *Frame,
  2418. APValue *&Result, const LValue *LVal) {
  2419. // If this is a parameter to an active constexpr function call, perform
  2420. // argument substitution.
  2421. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2422. // Assume arguments of a potential constant expression are unknown
  2423. // constant expressions.
  2424. if (Info.checkingPotentialConstantExpression())
  2425. return false;
  2426. if (!Frame || !Frame->Arguments) {
  2427. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2428. return false;
  2429. }
  2430. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2431. return true;
  2432. }
  2433. // If this is a local variable, dig out its value.
  2434. if (Frame) {
  2435. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2436. : Frame->getCurrentTemporary(VD);
  2437. if (!Result) {
  2438. // Assume variables referenced within a lambda's call operator that were
  2439. // not declared within the call operator are captures and during checking
  2440. // of a potential constant expression, assume they are unknown constant
  2441. // expressions.
  2442. assert(isLambdaCallOperator(Frame->Callee) &&
  2443. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2444. "missing value for local variable");
  2445. if (Info.checkingPotentialConstantExpression())
  2446. return false;
  2447. // FIXME: implement capture evaluation during constant expr evaluation.
  2448. Info.FFDiag(E->getBeginLoc(),
  2449. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2450. << "captures not currently allowed";
  2451. return false;
  2452. }
  2453. return true;
  2454. }
  2455. // Dig out the initializer, and use the declaration which it's attached to.
  2456. const Expr *Init = VD->getAnyInitializer(VD);
  2457. if (!Init || Init->isValueDependent()) {
  2458. // If we're checking a potential constant expression, the variable could be
  2459. // initialized later.
  2460. if (!Info.checkingPotentialConstantExpression())
  2461. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2462. return false;
  2463. }
  2464. // If we're currently evaluating the initializer of this declaration, use that
  2465. // in-flight value.
  2466. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2467. Result = Info.EvaluatingDeclValue;
  2468. return true;
  2469. }
  2470. // Never evaluate the initializer of a weak variable. We can't be sure that
  2471. // this is the definition which will be used.
  2472. if (VD->isWeak()) {
  2473. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2474. return false;
  2475. }
  2476. // Check that we can fold the initializer. In C++, we will have already done
  2477. // this in the cases where it matters for conformance.
  2478. SmallVector<PartialDiagnosticAt, 8> Notes;
  2479. if (!VD->evaluateValue(Notes)) {
  2480. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2481. Notes.size() + 1) << VD;
  2482. Info.Note(VD->getLocation(), diag::note_declared_at);
  2483. Info.addNotes(Notes);
  2484. return false;
  2485. } else if (!VD->checkInitIsICE()) {
  2486. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2487. Notes.size() + 1) << VD;
  2488. Info.Note(VD->getLocation(), diag::note_declared_at);
  2489. Info.addNotes(Notes);
  2490. }
  2491. Result = VD->getEvaluatedValue();
  2492. return true;
  2493. }
  2494. static bool IsConstNonVolatile(QualType T) {
  2495. Qualifiers Quals = T.getQualifiers();
  2496. return Quals.hasConst() && !Quals.hasVolatile();
  2497. }
  2498. /// Get the base index of the given base class within an APValue representing
  2499. /// the given derived class.
  2500. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2501. const CXXRecordDecl *Base) {
  2502. Base = Base->getCanonicalDecl();
  2503. unsigned Index = 0;
  2504. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2505. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2506. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2507. return Index;
  2508. }
  2509. llvm_unreachable("base class missing from derived class's bases list");
  2510. }
  2511. /// Extract the value of a character from a string literal.
  2512. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2513. uint64_t Index) {
  2514. assert(!isa<SourceLocExpr>(Lit) &&
  2515. "SourceLocExpr should have already been converted to a StringLiteral");
  2516. // FIXME: Support MakeStringConstant
  2517. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2518. std::string Str;
  2519. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2520. assert(Index <= Str.size() && "Index too large");
  2521. return APSInt::getUnsigned(Str.c_str()[Index]);
  2522. }
  2523. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2524. Lit = PE->getFunctionName();
  2525. const StringLiteral *S = cast<StringLiteral>(Lit);
  2526. const ConstantArrayType *CAT =
  2527. Info.Ctx.getAsConstantArrayType(S->getType());
  2528. assert(CAT && "string literal isn't an array");
  2529. QualType CharType = CAT->getElementType();
  2530. assert(CharType->isIntegerType() && "unexpected character type");
  2531. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2532. CharType->isUnsignedIntegerType());
  2533. if (Index < S->getLength())
  2534. Value = S->getCodeUnit(Index);
  2535. return Value;
  2536. }
  2537. // Expand a string literal into an array of characters.
  2538. //
  2539. // FIXME: This is inefficient; we should probably introduce something similar
  2540. // to the LLVM ConstantDataArray to make this cheaper.
  2541. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  2542. APValue &Result,
  2543. QualType AllocType = QualType()) {
  2544. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  2545. AllocType.isNull() ? S->getType() : AllocType);
  2546. assert(CAT && "string literal isn't an array");
  2547. QualType CharType = CAT->getElementType();
  2548. assert(CharType->isIntegerType() && "unexpected character type");
  2549. unsigned Elts = CAT->getSize().getZExtValue();
  2550. Result = APValue(APValue::UninitArray(),
  2551. std::min(S->getLength(), Elts), Elts);
  2552. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2553. CharType->isUnsignedIntegerType());
  2554. if (Result.hasArrayFiller())
  2555. Result.getArrayFiller() = APValue(Value);
  2556. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2557. Value = S->getCodeUnit(I);
  2558. Result.getArrayInitializedElt(I) = APValue(Value);
  2559. }
  2560. }
  2561. // Expand an array so that it has more than Index filled elements.
  2562. static void expandArray(APValue &Array, unsigned Index) {
  2563. unsigned Size = Array.getArraySize();
  2564. assert(Index < Size);
  2565. // Always at least double the number of elements for which we store a value.
  2566. unsigned OldElts = Array.getArrayInitializedElts();
  2567. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2568. NewElts = std::min(Size, std::max(NewElts, 8u));
  2569. // Copy the data across.
  2570. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2571. for (unsigned I = 0; I != OldElts; ++I)
  2572. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2573. for (unsigned I = OldElts; I != NewElts; ++I)
  2574. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2575. if (NewValue.hasArrayFiller())
  2576. NewValue.getArrayFiller() = Array.getArrayFiller();
  2577. Array.swap(NewValue);
  2578. }
  2579. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2580. /// conversion. If it's of class type, we may assume that the copy operation
  2581. /// is trivial. Note that this is never true for a union type with fields
  2582. /// (because the copy always "reads" the active member) and always true for
  2583. /// a non-class type.
  2584. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2585. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2586. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2587. return true;
  2588. if (RD->isEmpty())
  2589. return false;
  2590. for (auto *Field : RD->fields())
  2591. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2592. return true;
  2593. for (auto &BaseSpec : RD->bases())
  2594. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2595. return true;
  2596. return false;
  2597. }
  2598. /// Diagnose an attempt to read from any unreadable field within the specified
  2599. /// type, which might be a class type.
  2600. static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
  2601. QualType T) {
  2602. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2603. if (!RD)
  2604. return false;
  2605. if (!RD->hasMutableFields())
  2606. return false;
  2607. for (auto *Field : RD->fields()) {
  2608. // If we're actually going to read this field in some way, then it can't
  2609. // be mutable. If we're in a union, then assigning to a mutable field
  2610. // (even an empty one) can change the active member, so that's not OK.
  2611. // FIXME: Add core issue number for the union case.
  2612. if (Field->isMutable() &&
  2613. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2614. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
  2615. Info.Note(Field->getLocation(), diag::note_declared_at);
  2616. return true;
  2617. }
  2618. if (diagnoseMutableFields(Info, E, AK, Field->getType()))
  2619. return true;
  2620. }
  2621. for (auto &BaseSpec : RD->bases())
  2622. if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
  2623. return true;
  2624. // All mutable fields were empty, and thus not actually read.
  2625. return false;
  2626. }
  2627. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  2628. APValue::LValueBase Base,
  2629. bool MutableSubobject = false) {
  2630. // A temporary we created.
  2631. if (Base.getCallIndex())
  2632. return true;
  2633. auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2634. if (!Evaluating)
  2635. return false;
  2636. auto *BaseD = Base.dyn_cast<const ValueDecl*>();
  2637. switch (Info.IsEvaluatingDecl) {
  2638. case EvalInfo::EvaluatingDeclKind::None:
  2639. return false;
  2640. case EvalInfo::EvaluatingDeclKind::Ctor:
  2641. // The variable whose initializer we're evaluating.
  2642. if (BaseD)
  2643. return declaresSameEntity(Evaluating, BaseD);
  2644. // A temporary lifetime-extended by the variable whose initializer we're
  2645. // evaluating.
  2646. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  2647. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  2648. return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
  2649. return false;
  2650. case EvalInfo::EvaluatingDeclKind::Dtor:
  2651. // C++2a [expr.const]p6:
  2652. // [during constant destruction] the lifetime of a and its non-mutable
  2653. // subobjects (but not its mutable subobjects) [are] considered to start
  2654. // within e.
  2655. //
  2656. // FIXME: We can meaningfully extend this to cover non-const objects, but
  2657. // we will need special handling: we should be able to access only
  2658. // subobjects of such objects that are themselves declared const.
  2659. if (!BaseD ||
  2660. !(BaseD->getType().isConstQualified() ||
  2661. BaseD->getType()->isReferenceType()) ||
  2662. MutableSubobject)
  2663. return false;
  2664. return declaresSameEntity(Evaluating, BaseD);
  2665. }
  2666. llvm_unreachable("unknown evaluating decl kind");
  2667. }
  2668. namespace {
  2669. /// A handle to a complete object (an object that is not a subobject of
  2670. /// another object).
  2671. struct CompleteObject {
  2672. /// The identity of the object.
  2673. APValue::LValueBase Base;
  2674. /// The value of the complete object.
  2675. APValue *Value;
  2676. /// The type of the complete object.
  2677. QualType Type;
  2678. CompleteObject() : Value(nullptr) {}
  2679. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  2680. : Base(Base), Value(Value), Type(Type) {}
  2681. bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
  2682. // In C++14 onwards, it is permitted to read a mutable member whose
  2683. // lifetime began within the evaluation.
  2684. // FIXME: Should we also allow this in C++11?
  2685. if (!Info.getLangOpts().CPlusPlus14)
  2686. return false;
  2687. return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
  2688. }
  2689. explicit operator bool() const { return !Type.isNull(); }
  2690. };
  2691. } // end anonymous namespace
  2692. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  2693. bool IsMutable = false) {
  2694. // C++ [basic.type.qualifier]p1:
  2695. // - A const object is an object of type const T or a non-mutable subobject
  2696. // of a const object.
  2697. if (ObjType.isConstQualified() && !IsMutable)
  2698. SubobjType.addConst();
  2699. // - A volatile object is an object of type const T or a subobject of a
  2700. // volatile object.
  2701. if (ObjType.isVolatileQualified())
  2702. SubobjType.addVolatile();
  2703. return SubobjType;
  2704. }
  2705. /// Find the designated sub-object of an rvalue.
  2706. template<typename SubobjectHandler>
  2707. typename SubobjectHandler::result_type
  2708. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2709. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2710. if (Sub.Invalid)
  2711. // A diagnostic will have already been produced.
  2712. return handler.failed();
  2713. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2714. if (Info.getLangOpts().CPlusPlus11)
  2715. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2716. ? diag::note_constexpr_access_past_end
  2717. : diag::note_constexpr_access_unsized_array)
  2718. << handler.AccessKind;
  2719. else
  2720. Info.FFDiag(E);
  2721. return handler.failed();
  2722. }
  2723. APValue *O = Obj.Value;
  2724. QualType ObjType = Obj.Type;
  2725. const FieldDecl *LastField = nullptr;
  2726. const FieldDecl *VolatileField = nullptr;
  2727. // Walk the designator's path to find the subobject.
  2728. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2729. // Reading an indeterminate value is undefined, but assigning over one is OK.
  2730. if (O->isAbsent() ||
  2731. (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
  2732. handler.AccessKind != AK_ReadObjectRepresentation)) {
  2733. if (!Info.checkingPotentialConstantExpression())
  2734. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  2735. << handler.AccessKind << O->isIndeterminate();
  2736. return handler.failed();
  2737. }
  2738. // C++ [class.ctor]p5, C++ [class.dtor]p5:
  2739. // const and volatile semantics are not applied on an object under
  2740. // {con,de}struction.
  2741. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  2742. ObjType->isRecordType() &&
  2743. Info.isEvaluatingCtorDtor(
  2744. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  2745. Sub.Entries.begin() + I)) !=
  2746. ConstructionPhase::None) {
  2747. ObjType = Info.Ctx.getCanonicalType(ObjType);
  2748. ObjType.removeLocalConst();
  2749. ObjType.removeLocalVolatile();
  2750. }
  2751. // If this is our last pass, check that the final object type is OK.
  2752. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  2753. // Accesses to volatile objects are prohibited.
  2754. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  2755. if (Info.getLangOpts().CPlusPlus) {
  2756. int DiagKind;
  2757. SourceLocation Loc;
  2758. const NamedDecl *Decl = nullptr;
  2759. if (VolatileField) {
  2760. DiagKind = 2;
  2761. Loc = VolatileField->getLocation();
  2762. Decl = VolatileField;
  2763. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  2764. DiagKind = 1;
  2765. Loc = VD->getLocation();
  2766. Decl = VD;
  2767. } else {
  2768. DiagKind = 0;
  2769. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  2770. Loc = E->getExprLoc();
  2771. }
  2772. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2773. << handler.AccessKind << DiagKind << Decl;
  2774. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  2775. } else {
  2776. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2777. }
  2778. return handler.failed();
  2779. }
  2780. // If we are reading an object of class type, there may still be more
  2781. // things we need to check: if there are any mutable subobjects, we
  2782. // cannot perform this read. (This only happens when performing a trivial
  2783. // copy or assignment.)
  2784. if (ObjType->isRecordType() &&
  2785. !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
  2786. diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
  2787. return handler.failed();
  2788. }
  2789. if (I == N) {
  2790. if (!handler.found(*O, ObjType))
  2791. return false;
  2792. // If we modified a bit-field, truncate it to the right width.
  2793. if (isModification(handler.AccessKind) &&
  2794. LastField && LastField->isBitField() &&
  2795. !truncateBitfieldValue(Info, E, *O, LastField))
  2796. return false;
  2797. return true;
  2798. }
  2799. LastField = nullptr;
  2800. if (ObjType->isArrayType()) {
  2801. // Next subobject is an array element.
  2802. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2803. assert(CAT && "vla in literal type?");
  2804. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2805. if (CAT->getSize().ule(Index)) {
  2806. // Note, it should not be possible to form a pointer with a valid
  2807. // designator which points more than one past the end of the array.
  2808. if (Info.getLangOpts().CPlusPlus11)
  2809. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2810. << handler.AccessKind;
  2811. else
  2812. Info.FFDiag(E);
  2813. return handler.failed();
  2814. }
  2815. ObjType = CAT->getElementType();
  2816. if (O->getArrayInitializedElts() > Index)
  2817. O = &O->getArrayInitializedElt(Index);
  2818. else if (!isRead(handler.AccessKind)) {
  2819. expandArray(*O, Index);
  2820. O = &O->getArrayInitializedElt(Index);
  2821. } else
  2822. O = &O->getArrayFiller();
  2823. } else if (ObjType->isAnyComplexType()) {
  2824. // Next subobject is a complex number.
  2825. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2826. if (Index > 1) {
  2827. if (Info.getLangOpts().CPlusPlus11)
  2828. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2829. << handler.AccessKind;
  2830. else
  2831. Info.FFDiag(E);
  2832. return handler.failed();
  2833. }
  2834. ObjType = getSubobjectType(
  2835. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  2836. assert(I == N - 1 && "extracting subobject of scalar?");
  2837. if (O->isComplexInt()) {
  2838. return handler.found(Index ? O->getComplexIntImag()
  2839. : O->getComplexIntReal(), ObjType);
  2840. } else {
  2841. assert(O->isComplexFloat());
  2842. return handler.found(Index ? O->getComplexFloatImag()
  2843. : O->getComplexFloatReal(), ObjType);
  2844. }
  2845. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2846. if (Field->isMutable() &&
  2847. !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
  2848. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
  2849. << handler.AccessKind << Field;
  2850. Info.Note(Field->getLocation(), diag::note_declared_at);
  2851. return handler.failed();
  2852. }
  2853. // Next subobject is a class, struct or union field.
  2854. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2855. if (RD->isUnion()) {
  2856. const FieldDecl *UnionField = O->getUnionField();
  2857. if (!UnionField ||
  2858. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2859. // FIXME: If O->getUnionValue() is absent, report that there's no
  2860. // active union member rather than reporting the prior active union
  2861. // member. We'll need to fix nullptr_t to not use APValue() as its
  2862. // representation first.
  2863. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2864. << handler.AccessKind << Field << !UnionField << UnionField;
  2865. return handler.failed();
  2866. }
  2867. O = &O->getUnionValue();
  2868. } else
  2869. O = &O->getStructField(Field->getFieldIndex());
  2870. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  2871. LastField = Field;
  2872. if (Field->getType().isVolatileQualified())
  2873. VolatileField = Field;
  2874. } else {
  2875. // Next subobject is a base class.
  2876. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2877. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2878. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2879. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  2880. }
  2881. }
  2882. }
  2883. namespace {
  2884. struct ExtractSubobjectHandler {
  2885. EvalInfo &Info;
  2886. const Expr *E;
  2887. APValue &Result;
  2888. const AccessKinds AccessKind;
  2889. typedef bool result_type;
  2890. bool failed() { return false; }
  2891. bool found(APValue &Subobj, QualType SubobjType) {
  2892. Result = Subobj;
  2893. if (AccessKind == AK_ReadObjectRepresentation)
  2894. return true;
  2895. return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
  2896. }
  2897. bool found(APSInt &Value, QualType SubobjType) {
  2898. Result = APValue(Value);
  2899. return true;
  2900. }
  2901. bool found(APFloat &Value, QualType SubobjType) {
  2902. Result = APValue(Value);
  2903. return true;
  2904. }
  2905. };
  2906. } // end anonymous namespace
  2907. /// Extract the designated sub-object of an rvalue.
  2908. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2909. const CompleteObject &Obj,
  2910. const SubobjectDesignator &Sub, APValue &Result,
  2911. AccessKinds AK = AK_Read) {
  2912. assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
  2913. ExtractSubobjectHandler Handler = {Info, E, Result, AK};
  2914. return findSubobject(Info, E, Obj, Sub, Handler);
  2915. }
  2916. namespace {
  2917. struct ModifySubobjectHandler {
  2918. EvalInfo &Info;
  2919. APValue &NewVal;
  2920. const Expr *E;
  2921. typedef bool result_type;
  2922. static const AccessKinds AccessKind = AK_Assign;
  2923. bool checkConst(QualType QT) {
  2924. // Assigning to a const object has undefined behavior.
  2925. if (QT.isConstQualified()) {
  2926. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2927. return false;
  2928. }
  2929. return true;
  2930. }
  2931. bool failed() { return false; }
  2932. bool found(APValue &Subobj, QualType SubobjType) {
  2933. if (!checkConst(SubobjType))
  2934. return false;
  2935. // We've been given ownership of NewVal, so just swap it in.
  2936. Subobj.swap(NewVal);
  2937. return true;
  2938. }
  2939. bool found(APSInt &Value, QualType SubobjType) {
  2940. if (!checkConst(SubobjType))
  2941. return false;
  2942. if (!NewVal.isInt()) {
  2943. // Maybe trying to write a cast pointer value into a complex?
  2944. Info.FFDiag(E);
  2945. return false;
  2946. }
  2947. Value = NewVal.getInt();
  2948. return true;
  2949. }
  2950. bool found(APFloat &Value, QualType SubobjType) {
  2951. if (!checkConst(SubobjType))
  2952. return false;
  2953. Value = NewVal.getFloat();
  2954. return true;
  2955. }
  2956. };
  2957. } // end anonymous namespace
  2958. const AccessKinds ModifySubobjectHandler::AccessKind;
  2959. /// Update the designated sub-object of an rvalue to the given value.
  2960. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2961. const CompleteObject &Obj,
  2962. const SubobjectDesignator &Sub,
  2963. APValue &NewVal) {
  2964. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2965. return findSubobject(Info, E, Obj, Sub, Handler);
  2966. }
  2967. /// Find the position where two subobject designators diverge, or equivalently
  2968. /// the length of the common initial subsequence.
  2969. static unsigned FindDesignatorMismatch(QualType ObjType,
  2970. const SubobjectDesignator &A,
  2971. const SubobjectDesignator &B,
  2972. bool &WasArrayIndex) {
  2973. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2974. for (/**/; I != N; ++I) {
  2975. if (!ObjType.isNull() &&
  2976. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2977. // Next subobject is an array element.
  2978. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  2979. WasArrayIndex = true;
  2980. return I;
  2981. }
  2982. if (ObjType->isAnyComplexType())
  2983. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2984. else
  2985. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2986. } else {
  2987. if (A.Entries[I].getAsBaseOrMember() !=
  2988. B.Entries[I].getAsBaseOrMember()) {
  2989. WasArrayIndex = false;
  2990. return I;
  2991. }
  2992. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2993. // Next subobject is a field.
  2994. ObjType = FD->getType();
  2995. else
  2996. // Next subobject is a base class.
  2997. ObjType = QualType();
  2998. }
  2999. }
  3000. WasArrayIndex = false;
  3001. return I;
  3002. }
  3003. /// Determine whether the given subobject designators refer to elements of the
  3004. /// same array object.
  3005. static bool AreElementsOfSameArray(QualType ObjType,
  3006. const SubobjectDesignator &A,
  3007. const SubobjectDesignator &B) {
  3008. if (A.Entries.size() != B.Entries.size())
  3009. return false;
  3010. bool IsArray = A.MostDerivedIsArrayElement;
  3011. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  3012. // A is a subobject of the array element.
  3013. return false;
  3014. // If A (and B) designates an array element, the last entry will be the array
  3015. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  3016. // of length 1' case, and the entire path must match.
  3017. bool WasArrayIndex;
  3018. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  3019. return CommonLength >= A.Entries.size() - IsArray;
  3020. }
  3021. /// Find the complete object to which an LValue refers.
  3022. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  3023. AccessKinds AK, const LValue &LVal,
  3024. QualType LValType) {
  3025. if (LVal.InvalidBase) {
  3026. Info.FFDiag(E);
  3027. return CompleteObject();
  3028. }
  3029. if (!LVal.Base) {
  3030. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  3031. return CompleteObject();
  3032. }
  3033. CallStackFrame *Frame = nullptr;
  3034. unsigned Depth = 0;
  3035. if (LVal.getLValueCallIndex()) {
  3036. std::tie(Frame, Depth) =
  3037. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  3038. if (!Frame) {
  3039. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  3040. << AK << LVal.Base.is<const ValueDecl*>();
  3041. NoteLValueLocation(Info, LVal.Base);
  3042. return CompleteObject();
  3043. }
  3044. }
  3045. bool IsAccess = isAnyAccess(AK);
  3046. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  3047. // is not a constant expression (even if the object is non-volatile). We also
  3048. // apply this rule to C++98, in order to conform to the expected 'volatile'
  3049. // semantics.
  3050. if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
  3051. if (Info.getLangOpts().CPlusPlus)
  3052. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  3053. << AK << LValType;
  3054. else
  3055. Info.FFDiag(E);
  3056. return CompleteObject();
  3057. }
  3058. // Compute value storage location and type of base object.
  3059. APValue *BaseVal = nullptr;
  3060. QualType BaseType = getType(LVal.Base);
  3061. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  3062. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  3063. // In C++11, constexpr, non-volatile variables initialized with constant
  3064. // expressions are constant expressions too. Inside constexpr functions,
  3065. // parameters are constant expressions even if they're non-const.
  3066. // In C++1y, objects local to a constant expression (those with a Frame) are
  3067. // both readable and writable inside constant expressions.
  3068. // In C, such things can also be folded, although they are not ICEs.
  3069. const VarDecl *VD = dyn_cast<VarDecl>(D);
  3070. if (VD) {
  3071. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  3072. VD = VDef;
  3073. }
  3074. if (!VD || VD->isInvalidDecl()) {
  3075. Info.FFDiag(E);
  3076. return CompleteObject();
  3077. }
  3078. // Unless we're looking at a local variable or argument in a constexpr call,
  3079. // the variable we're reading must be const.
  3080. if (!Frame) {
  3081. if (Info.getLangOpts().CPlusPlus14 &&
  3082. lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3083. // OK, we can read and modify an object if we're in the process of
  3084. // evaluating its initializer, because its lifetime began in this
  3085. // evaluation.
  3086. } else if (isModification(AK)) {
  3087. // All the remaining cases do not permit modification of the object.
  3088. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3089. return CompleteObject();
  3090. } else if (VD->isConstexpr()) {
  3091. // OK, we can read this variable.
  3092. } else if (BaseType->isIntegralOrEnumerationType()) {
  3093. // In OpenCL if a variable is in constant address space it is a const
  3094. // value.
  3095. if (!(BaseType.isConstQualified() ||
  3096. (Info.getLangOpts().OpenCL &&
  3097. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  3098. if (!IsAccess)
  3099. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3100. if (Info.getLangOpts().CPlusPlus) {
  3101. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  3102. Info.Note(VD->getLocation(), diag::note_declared_at);
  3103. } else {
  3104. Info.FFDiag(E);
  3105. }
  3106. return CompleteObject();
  3107. }
  3108. } else if (!IsAccess) {
  3109. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3110. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  3111. // We support folding of const floating-point types, in order to make
  3112. // static const data members of such types (supported as an extension)
  3113. // more useful.
  3114. if (Info.getLangOpts().CPlusPlus11) {
  3115. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3116. Info.Note(VD->getLocation(), diag::note_declared_at);
  3117. } else {
  3118. Info.CCEDiag(E);
  3119. }
  3120. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  3121. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  3122. // Keep evaluating to see what we can do.
  3123. } else {
  3124. // FIXME: Allow folding of values of any literal type in all languages.
  3125. if (Info.checkingPotentialConstantExpression() &&
  3126. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  3127. // The definition of this variable could be constexpr. We can't
  3128. // access it right now, but may be able to in future.
  3129. } else if (Info.getLangOpts().CPlusPlus11) {
  3130. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3131. Info.Note(VD->getLocation(), diag::note_declared_at);
  3132. } else {
  3133. Info.FFDiag(E);
  3134. }
  3135. return CompleteObject();
  3136. }
  3137. }
  3138. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  3139. return CompleteObject();
  3140. } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
  3141. Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
  3142. if (!Alloc) {
  3143. Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
  3144. return CompleteObject();
  3145. }
  3146. return CompleteObject(LVal.Base, &(*Alloc)->Value,
  3147. LVal.Base.getDynamicAllocType());
  3148. } else {
  3149. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3150. if (!Frame) {
  3151. if (const MaterializeTemporaryExpr *MTE =
  3152. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  3153. assert(MTE->getStorageDuration() == SD_Static &&
  3154. "should have a frame for a non-global materialized temporary");
  3155. // Per C++1y [expr.const]p2:
  3156. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3157. // - a [...] glvalue of integral or enumeration type that refers to
  3158. // a non-volatile const object [...]
  3159. // [...]
  3160. // - a [...] glvalue of literal type that refers to a non-volatile
  3161. // object whose lifetime began within the evaluation of e.
  3162. //
  3163. // C++11 misses the 'began within the evaluation of e' check and
  3164. // instead allows all temporaries, including things like:
  3165. // int &&r = 1;
  3166. // int x = ++r;
  3167. // constexpr int k = r;
  3168. // Therefore we use the C++14 rules in C++11 too.
  3169. //
  3170. // Note that temporaries whose lifetimes began while evaluating a
  3171. // variable's constructor are not usable while evaluating the
  3172. // corresponding destructor, not even if they're of const-qualified
  3173. // types.
  3174. if (!(BaseType.isConstQualified() &&
  3175. BaseType->isIntegralOrEnumerationType()) &&
  3176. !lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3177. if (!IsAccess)
  3178. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3179. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3180. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3181. return CompleteObject();
  3182. }
  3183. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  3184. assert(BaseVal && "got reference to unevaluated temporary");
  3185. } else {
  3186. if (!IsAccess)
  3187. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3188. APValue Val;
  3189. LVal.moveInto(Val);
  3190. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  3191. << AK
  3192. << Val.getAsString(Info.Ctx,
  3193. Info.Ctx.getLValueReferenceType(LValType));
  3194. NoteLValueLocation(Info, LVal.Base);
  3195. return CompleteObject();
  3196. }
  3197. } else {
  3198. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3199. assert(BaseVal && "missing value for temporary");
  3200. }
  3201. }
  3202. // In C++14, we can't safely access any mutable state when we might be
  3203. // evaluating after an unmodeled side effect.
  3204. //
  3205. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3206. // to be read here (but take care with 'mutable' fields).
  3207. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3208. Info.EvalStatus.HasSideEffects) ||
  3209. (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
  3210. return CompleteObject();
  3211. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3212. }
  3213. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3214. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3215. /// glvalue referred to by an entity of reference type.
  3216. ///
  3217. /// \param Info - Information about the ongoing evaluation.
  3218. /// \param Conv - The expression for which we are performing the conversion.
  3219. /// Used for diagnostics.
  3220. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3221. /// case of a non-class type).
  3222. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3223. /// \param RVal - The produced value will be placed here.
  3224. /// \param WantObjectRepresentation - If true, we're looking for the object
  3225. /// representation rather than the value, and in particular,
  3226. /// there is no requirement that the result be fully initialized.
  3227. static bool
  3228. handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
  3229. const LValue &LVal, APValue &RVal,
  3230. bool WantObjectRepresentation = false) {
  3231. if (LVal.Designator.Invalid)
  3232. return false;
  3233. // Check for special cases where there is no existing APValue to look at.
  3234. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3235. AccessKinds AK =
  3236. WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
  3237. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3238. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3239. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3240. // initializer until now for such expressions. Such an expression can't be
  3241. // an ICE in C, so this only matters for fold.
  3242. if (Type.isVolatileQualified()) {
  3243. Info.FFDiag(Conv);
  3244. return false;
  3245. }
  3246. APValue Lit;
  3247. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3248. return false;
  3249. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3250. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
  3251. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3252. // Special-case character extraction so we don't have to construct an
  3253. // APValue for the whole string.
  3254. assert(LVal.Designator.Entries.size() <= 1 &&
  3255. "Can only read characters from string literals");
  3256. if (LVal.Designator.Entries.empty()) {
  3257. // Fail for now for LValue to RValue conversion of an array.
  3258. // (This shouldn't show up in C/C++, but it could be triggered by a
  3259. // weird EvaluateAsRValue call from a tool.)
  3260. Info.FFDiag(Conv);
  3261. return false;
  3262. }
  3263. if (LVal.Designator.isOnePastTheEnd()) {
  3264. if (Info.getLangOpts().CPlusPlus11)
  3265. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
  3266. else
  3267. Info.FFDiag(Conv);
  3268. return false;
  3269. }
  3270. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3271. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3272. return true;
  3273. }
  3274. }
  3275. CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
  3276. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
  3277. }
  3278. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3279. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3280. QualType LValType, APValue &Val) {
  3281. if (LVal.Designator.Invalid)
  3282. return false;
  3283. if (!Info.getLangOpts().CPlusPlus14) {
  3284. Info.FFDiag(E);
  3285. return false;
  3286. }
  3287. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3288. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3289. }
  3290. namespace {
  3291. struct CompoundAssignSubobjectHandler {
  3292. EvalInfo &Info;
  3293. const Expr *E;
  3294. QualType PromotedLHSType;
  3295. BinaryOperatorKind Opcode;
  3296. const APValue &RHS;
  3297. static const AccessKinds AccessKind = AK_Assign;
  3298. typedef bool result_type;
  3299. bool checkConst(QualType QT) {
  3300. // Assigning to a const object has undefined behavior.
  3301. if (QT.isConstQualified()) {
  3302. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3303. return false;
  3304. }
  3305. return true;
  3306. }
  3307. bool failed() { return false; }
  3308. bool found(APValue &Subobj, QualType SubobjType) {
  3309. switch (Subobj.getKind()) {
  3310. case APValue::Int:
  3311. return found(Subobj.getInt(), SubobjType);
  3312. case APValue::Float:
  3313. return found(Subobj.getFloat(), SubobjType);
  3314. case APValue::ComplexInt:
  3315. case APValue::ComplexFloat:
  3316. // FIXME: Implement complex compound assignment.
  3317. Info.FFDiag(E);
  3318. return false;
  3319. case APValue::LValue:
  3320. return foundPointer(Subobj, SubobjType);
  3321. default:
  3322. // FIXME: can this happen?
  3323. Info.FFDiag(E);
  3324. return false;
  3325. }
  3326. }
  3327. bool found(APSInt &Value, QualType SubobjType) {
  3328. if (!checkConst(SubobjType))
  3329. return false;
  3330. if (!SubobjType->isIntegerType()) {
  3331. // We don't support compound assignment on integer-cast-to-pointer
  3332. // values.
  3333. Info.FFDiag(E);
  3334. return false;
  3335. }
  3336. if (RHS.isInt()) {
  3337. APSInt LHS =
  3338. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3339. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3340. return false;
  3341. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3342. return true;
  3343. } else if (RHS.isFloat()) {
  3344. APFloat FValue(0.0);
  3345. return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
  3346. FValue) &&
  3347. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3348. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3349. Value);
  3350. }
  3351. Info.FFDiag(E);
  3352. return false;
  3353. }
  3354. bool found(APFloat &Value, QualType SubobjType) {
  3355. return checkConst(SubobjType) &&
  3356. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3357. Value) &&
  3358. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3359. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3360. }
  3361. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3362. if (!checkConst(SubobjType))
  3363. return false;
  3364. QualType PointeeType;
  3365. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3366. PointeeType = PT->getPointeeType();
  3367. if (PointeeType.isNull() || !RHS.isInt() ||
  3368. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3369. Info.FFDiag(E);
  3370. return false;
  3371. }
  3372. APSInt Offset = RHS.getInt();
  3373. if (Opcode == BO_Sub)
  3374. negateAsSigned(Offset);
  3375. LValue LVal;
  3376. LVal.setFrom(Info.Ctx, Subobj);
  3377. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3378. return false;
  3379. LVal.moveInto(Subobj);
  3380. return true;
  3381. }
  3382. };
  3383. } // end anonymous namespace
  3384. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3385. /// Perform a compound assignment of LVal <op>= RVal.
  3386. static bool handleCompoundAssignment(
  3387. EvalInfo &Info, const Expr *E,
  3388. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3389. BinaryOperatorKind Opcode, const APValue &RVal) {
  3390. if (LVal.Designator.Invalid)
  3391. return false;
  3392. if (!Info.getLangOpts().CPlusPlus14) {
  3393. Info.FFDiag(E);
  3394. return false;
  3395. }
  3396. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3397. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3398. RVal };
  3399. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3400. }
  3401. namespace {
  3402. struct IncDecSubobjectHandler {
  3403. EvalInfo &Info;
  3404. const UnaryOperator *E;
  3405. AccessKinds AccessKind;
  3406. APValue *Old;
  3407. typedef bool result_type;
  3408. bool checkConst(QualType QT) {
  3409. // Assigning to a const object has undefined behavior.
  3410. if (QT.isConstQualified()) {
  3411. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3412. return false;
  3413. }
  3414. return true;
  3415. }
  3416. bool failed() { return false; }
  3417. bool found(APValue &Subobj, QualType SubobjType) {
  3418. // Stash the old value. Also clear Old, so we don't clobber it later
  3419. // if we're post-incrementing a complex.
  3420. if (Old) {
  3421. *Old = Subobj;
  3422. Old = nullptr;
  3423. }
  3424. switch (Subobj.getKind()) {
  3425. case APValue::Int:
  3426. return found(Subobj.getInt(), SubobjType);
  3427. case APValue::Float:
  3428. return found(Subobj.getFloat(), SubobjType);
  3429. case APValue::ComplexInt:
  3430. return found(Subobj.getComplexIntReal(),
  3431. SubobjType->castAs<ComplexType>()->getElementType()
  3432. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3433. case APValue::ComplexFloat:
  3434. return found(Subobj.getComplexFloatReal(),
  3435. SubobjType->castAs<ComplexType>()->getElementType()
  3436. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3437. case APValue::LValue:
  3438. return foundPointer(Subobj, SubobjType);
  3439. default:
  3440. // FIXME: can this happen?
  3441. Info.FFDiag(E);
  3442. return false;
  3443. }
  3444. }
  3445. bool found(APSInt &Value, QualType SubobjType) {
  3446. if (!checkConst(SubobjType))
  3447. return false;
  3448. if (!SubobjType->isIntegerType()) {
  3449. // We don't support increment / decrement on integer-cast-to-pointer
  3450. // values.
  3451. Info.FFDiag(E);
  3452. return false;
  3453. }
  3454. if (Old) *Old = APValue(Value);
  3455. // bool arithmetic promotes to int, and the conversion back to bool
  3456. // doesn't reduce mod 2^n, so special-case it.
  3457. if (SubobjType->isBooleanType()) {
  3458. if (AccessKind == AK_Increment)
  3459. Value = 1;
  3460. else
  3461. Value = !Value;
  3462. return true;
  3463. }
  3464. bool WasNegative = Value.isNegative();
  3465. if (AccessKind == AK_Increment) {
  3466. ++Value;
  3467. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3468. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3469. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3470. }
  3471. } else {
  3472. --Value;
  3473. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3474. unsigned BitWidth = Value.getBitWidth();
  3475. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3476. ActualValue.setBit(BitWidth);
  3477. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3478. }
  3479. }
  3480. return true;
  3481. }
  3482. bool found(APFloat &Value, QualType SubobjType) {
  3483. if (!checkConst(SubobjType))
  3484. return false;
  3485. if (Old) *Old = APValue(Value);
  3486. APFloat One(Value.getSemantics(), 1);
  3487. if (AccessKind == AK_Increment)
  3488. Value.add(One, APFloat::rmNearestTiesToEven);
  3489. else
  3490. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3491. return true;
  3492. }
  3493. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3494. if (!checkConst(SubobjType))
  3495. return false;
  3496. QualType PointeeType;
  3497. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3498. PointeeType = PT->getPointeeType();
  3499. else {
  3500. Info.FFDiag(E);
  3501. return false;
  3502. }
  3503. LValue LVal;
  3504. LVal.setFrom(Info.Ctx, Subobj);
  3505. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3506. AccessKind == AK_Increment ? 1 : -1))
  3507. return false;
  3508. LVal.moveInto(Subobj);
  3509. return true;
  3510. }
  3511. };
  3512. } // end anonymous namespace
  3513. /// Perform an increment or decrement on LVal.
  3514. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3515. QualType LValType, bool IsIncrement, APValue *Old) {
  3516. if (LVal.Designator.Invalid)
  3517. return false;
  3518. if (!Info.getLangOpts().CPlusPlus14) {
  3519. Info.FFDiag(E);
  3520. return false;
  3521. }
  3522. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3523. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3524. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3525. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3526. }
  3527. /// Build an lvalue for the object argument of a member function call.
  3528. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3529. LValue &This) {
  3530. if (Object->getType()->isPointerType())
  3531. return EvaluatePointer(Object, This, Info);
  3532. if (Object->isGLValue())
  3533. return EvaluateLValue(Object, This, Info);
  3534. if (Object->getType()->isLiteralType(Info.Ctx))
  3535. return EvaluateTemporary(Object, This, Info);
  3536. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3537. return false;
  3538. }
  3539. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3540. /// lvalue referring to the result.
  3541. ///
  3542. /// \param Info - Information about the ongoing evaluation.
  3543. /// \param LV - An lvalue referring to the base of the member pointer.
  3544. /// \param RHS - The member pointer expression.
  3545. /// \param IncludeMember - Specifies whether the member itself is included in
  3546. /// the resulting LValue subobject designator. This is not possible when
  3547. /// creating a bound member function.
  3548. /// \return The field or method declaration to which the member pointer refers,
  3549. /// or 0 if evaluation fails.
  3550. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3551. QualType LVType,
  3552. LValue &LV,
  3553. const Expr *RHS,
  3554. bool IncludeMember = true) {
  3555. MemberPtr MemPtr;
  3556. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3557. return nullptr;
  3558. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3559. // member value, the behavior is undefined.
  3560. if (!MemPtr.getDecl()) {
  3561. // FIXME: Specific diagnostic.
  3562. Info.FFDiag(RHS);
  3563. return nullptr;
  3564. }
  3565. if (MemPtr.isDerivedMember()) {
  3566. // This is a member of some derived class. Truncate LV appropriately.
  3567. // The end of the derived-to-base path for the base object must match the
  3568. // derived-to-base path for the member pointer.
  3569. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3570. LV.Designator.Entries.size()) {
  3571. Info.FFDiag(RHS);
  3572. return nullptr;
  3573. }
  3574. unsigned PathLengthToMember =
  3575. LV.Designator.Entries.size() - MemPtr.Path.size();
  3576. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3577. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3578. LV.Designator.Entries[PathLengthToMember + I]);
  3579. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3580. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3581. Info.FFDiag(RHS);
  3582. return nullptr;
  3583. }
  3584. }
  3585. // Truncate the lvalue to the appropriate derived class.
  3586. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3587. PathLengthToMember))
  3588. return nullptr;
  3589. } else if (!MemPtr.Path.empty()) {
  3590. // Extend the LValue path with the member pointer's path.
  3591. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3592. MemPtr.Path.size() + IncludeMember);
  3593. // Walk down to the appropriate base class.
  3594. if (const PointerType *PT = LVType->getAs<PointerType>())
  3595. LVType = PT->getPointeeType();
  3596. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3597. assert(RD && "member pointer access on non-class-type expression");
  3598. // The first class in the path is that of the lvalue.
  3599. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3600. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3601. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3602. return nullptr;
  3603. RD = Base;
  3604. }
  3605. // Finally cast to the class containing the member.
  3606. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3607. MemPtr.getContainingRecord()))
  3608. return nullptr;
  3609. }
  3610. // Add the member. Note that we cannot build bound member functions here.
  3611. if (IncludeMember) {
  3612. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3613. if (!HandleLValueMember(Info, RHS, LV, FD))
  3614. return nullptr;
  3615. } else if (const IndirectFieldDecl *IFD =
  3616. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3617. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3618. return nullptr;
  3619. } else {
  3620. llvm_unreachable("can't construct reference to bound member function");
  3621. }
  3622. }
  3623. return MemPtr.getDecl();
  3624. }
  3625. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3626. const BinaryOperator *BO,
  3627. LValue &LV,
  3628. bool IncludeMember = true) {
  3629. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3630. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3631. if (Info.noteFailure()) {
  3632. MemberPtr MemPtr;
  3633. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3634. }
  3635. return nullptr;
  3636. }
  3637. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3638. BO->getRHS(), IncludeMember);
  3639. }
  3640. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3641. /// the provided lvalue, which currently refers to the base object.
  3642. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3643. LValue &Result) {
  3644. SubobjectDesignator &D = Result.Designator;
  3645. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3646. return false;
  3647. QualType TargetQT = E->getType();
  3648. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3649. TargetQT = PT->getPointeeType();
  3650. // Check this cast lands within the final derived-to-base subobject path.
  3651. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3652. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3653. << D.MostDerivedType << TargetQT;
  3654. return false;
  3655. }
  3656. // Check the type of the final cast. We don't need to check the path,
  3657. // since a cast can only be formed if the path is unique.
  3658. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3659. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3660. const CXXRecordDecl *FinalType;
  3661. if (NewEntriesSize == D.MostDerivedPathLength)
  3662. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3663. else
  3664. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3665. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3666. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3667. << D.MostDerivedType << TargetQT;
  3668. return false;
  3669. }
  3670. // Truncate the lvalue to the appropriate derived class.
  3671. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3672. }
  3673. /// Get the value to use for a default-initialized object of type T.
  3674. static APValue getDefaultInitValue(QualType T) {
  3675. if (auto *RD = T->getAsCXXRecordDecl()) {
  3676. if (RD->isUnion())
  3677. return APValue((const FieldDecl*)nullptr);
  3678. APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
  3679. std::distance(RD->field_begin(), RD->field_end()));
  3680. unsigned Index = 0;
  3681. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  3682. End = RD->bases_end(); I != End; ++I, ++Index)
  3683. Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
  3684. for (const auto *I : RD->fields()) {
  3685. if (I->isUnnamedBitfield())
  3686. continue;
  3687. Struct.getStructField(I->getFieldIndex()) =
  3688. getDefaultInitValue(I->getType());
  3689. }
  3690. return Struct;
  3691. }
  3692. if (auto *AT =
  3693. dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
  3694. APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  3695. if (Array.hasArrayFiller())
  3696. Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
  3697. return Array;
  3698. }
  3699. return APValue::IndeterminateValue();
  3700. }
  3701. namespace {
  3702. enum EvalStmtResult {
  3703. /// Evaluation failed.
  3704. ESR_Failed,
  3705. /// Hit a 'return' statement.
  3706. ESR_Returned,
  3707. /// Evaluation succeeded.
  3708. ESR_Succeeded,
  3709. /// Hit a 'continue' statement.
  3710. ESR_Continue,
  3711. /// Hit a 'break' statement.
  3712. ESR_Break,
  3713. /// Still scanning for 'case' or 'default' statement.
  3714. ESR_CaseNotFound
  3715. };
  3716. }
  3717. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3718. // We don't need to evaluate the initializer for a static local.
  3719. if (!VD->hasLocalStorage())
  3720. return true;
  3721. LValue Result;
  3722. APValue &Val =
  3723. Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
  3724. const Expr *InitE = VD->getInit();
  3725. if (!InitE) {
  3726. Val = getDefaultInitValue(VD->getType());
  3727. return true;
  3728. }
  3729. if (InitE->isValueDependent())
  3730. return false;
  3731. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3732. // Wipe out any partially-computed value, to allow tracking that this
  3733. // evaluation failed.
  3734. Val = APValue();
  3735. return false;
  3736. }
  3737. return true;
  3738. }
  3739. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3740. bool OK = true;
  3741. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3742. OK &= EvaluateVarDecl(Info, VD);
  3743. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3744. for (auto *BD : DD->bindings())
  3745. if (auto *VD = BD->getHoldingVar())
  3746. OK &= EvaluateDecl(Info, VD);
  3747. return OK;
  3748. }
  3749. /// Evaluate a condition (either a variable declaration or an expression).
  3750. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3751. const Expr *Cond, bool &Result) {
  3752. FullExpressionRAII Scope(Info);
  3753. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3754. return false;
  3755. if (!EvaluateAsBooleanCondition(Cond, Result, Info))
  3756. return false;
  3757. return Scope.destroy();
  3758. }
  3759. namespace {
  3760. /// A location where the result (returned value) of evaluating a
  3761. /// statement should be stored.
  3762. struct StmtResult {
  3763. /// The APValue that should be filled in with the returned value.
  3764. APValue &Value;
  3765. /// The location containing the result, if any (used to support RVO).
  3766. const LValue *Slot;
  3767. };
  3768. struct TempVersionRAII {
  3769. CallStackFrame &Frame;
  3770. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3771. Frame.pushTempVersion();
  3772. }
  3773. ~TempVersionRAII() {
  3774. Frame.popTempVersion();
  3775. }
  3776. };
  3777. }
  3778. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3779. const Stmt *S,
  3780. const SwitchCase *SC = nullptr);
  3781. /// Evaluate the body of a loop, and translate the result as appropriate.
  3782. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3783. const Stmt *Body,
  3784. const SwitchCase *Case = nullptr) {
  3785. BlockScopeRAII Scope(Info);
  3786. EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
  3787. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  3788. ESR = ESR_Failed;
  3789. switch (ESR) {
  3790. case ESR_Break:
  3791. return ESR_Succeeded;
  3792. case ESR_Succeeded:
  3793. case ESR_Continue:
  3794. return ESR_Continue;
  3795. case ESR_Failed:
  3796. case ESR_Returned:
  3797. case ESR_CaseNotFound:
  3798. return ESR;
  3799. }
  3800. llvm_unreachable("Invalid EvalStmtResult!");
  3801. }
  3802. /// Evaluate a switch statement.
  3803. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3804. const SwitchStmt *SS) {
  3805. BlockScopeRAII Scope(Info);
  3806. // Evaluate the switch condition.
  3807. APSInt Value;
  3808. {
  3809. if (const Stmt *Init = SS->getInit()) {
  3810. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3811. if (ESR != ESR_Succeeded) {
  3812. if (ESR != ESR_Failed && !Scope.destroy())
  3813. ESR = ESR_Failed;
  3814. return ESR;
  3815. }
  3816. }
  3817. FullExpressionRAII CondScope(Info);
  3818. if (SS->getConditionVariable() &&
  3819. !EvaluateDecl(Info, SS->getConditionVariable()))
  3820. return ESR_Failed;
  3821. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3822. return ESR_Failed;
  3823. if (!CondScope.destroy())
  3824. return ESR_Failed;
  3825. }
  3826. // Find the switch case corresponding to the value of the condition.
  3827. // FIXME: Cache this lookup.
  3828. const SwitchCase *Found = nullptr;
  3829. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3830. SC = SC->getNextSwitchCase()) {
  3831. if (isa<DefaultStmt>(SC)) {
  3832. Found = SC;
  3833. continue;
  3834. }
  3835. const CaseStmt *CS = cast<CaseStmt>(SC);
  3836. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3837. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3838. : LHS;
  3839. if (LHS <= Value && Value <= RHS) {
  3840. Found = SC;
  3841. break;
  3842. }
  3843. }
  3844. if (!Found)
  3845. return Scope.destroy() ? ESR_Failed : ESR_Succeeded;
  3846. // Search the switch body for the switch case and evaluate it from there.
  3847. EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
  3848. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  3849. return ESR_Failed;
  3850. switch (ESR) {
  3851. case ESR_Break:
  3852. return ESR_Succeeded;
  3853. case ESR_Succeeded:
  3854. case ESR_Continue:
  3855. case ESR_Failed:
  3856. case ESR_Returned:
  3857. return ESR;
  3858. case ESR_CaseNotFound:
  3859. // This can only happen if the switch case is nested within a statement
  3860. // expression. We have no intention of supporting that.
  3861. Info.FFDiag(Found->getBeginLoc(),
  3862. diag::note_constexpr_stmt_expr_unsupported);
  3863. return ESR_Failed;
  3864. }
  3865. llvm_unreachable("Invalid EvalStmtResult!");
  3866. }
  3867. // Evaluate a statement.
  3868. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3869. const Stmt *S, const SwitchCase *Case) {
  3870. if (!Info.nextStep(S))
  3871. return ESR_Failed;
  3872. // If we're hunting down a 'case' or 'default' label, recurse through
  3873. // substatements until we hit the label.
  3874. if (Case) {
  3875. switch (S->getStmtClass()) {
  3876. case Stmt::CompoundStmtClass:
  3877. // FIXME: Precompute which substatement of a compound statement we
  3878. // would jump to, and go straight there rather than performing a
  3879. // linear scan each time.
  3880. case Stmt::LabelStmtClass:
  3881. case Stmt::AttributedStmtClass:
  3882. case Stmt::DoStmtClass:
  3883. break;
  3884. case Stmt::CaseStmtClass:
  3885. case Stmt::DefaultStmtClass:
  3886. if (Case == S)
  3887. Case = nullptr;
  3888. break;
  3889. case Stmt::IfStmtClass: {
  3890. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3891. // straight there rather than scanning both sides.
  3892. const IfStmt *IS = cast<IfStmt>(S);
  3893. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3894. // preceded by our switch label.
  3895. BlockScopeRAII Scope(Info);
  3896. // Step into the init statement in case it brings an (uninitialized)
  3897. // variable into scope.
  3898. if (const Stmt *Init = IS->getInit()) {
  3899. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  3900. if (ESR != ESR_CaseNotFound) {
  3901. assert(ESR != ESR_Succeeded);
  3902. return ESR;
  3903. }
  3904. }
  3905. // Condition variable must be initialized if it exists.
  3906. // FIXME: We can skip evaluating the body if there's a condition
  3907. // variable, as there can't be any case labels within it.
  3908. // (The same is true for 'for' statements.)
  3909. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3910. if (ESR == ESR_Failed)
  3911. return ESR;
  3912. if (ESR != ESR_CaseNotFound)
  3913. return Scope.destroy() ? ESR : ESR_Failed;
  3914. if (!IS->getElse())
  3915. return ESR_CaseNotFound;
  3916. ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
  3917. if (ESR == ESR_Failed)
  3918. return ESR;
  3919. if (ESR != ESR_CaseNotFound)
  3920. return Scope.destroy() ? ESR : ESR_Failed;
  3921. return ESR_CaseNotFound;
  3922. }
  3923. case Stmt::WhileStmtClass: {
  3924. EvalStmtResult ESR =
  3925. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3926. if (ESR != ESR_Continue)
  3927. return ESR;
  3928. break;
  3929. }
  3930. case Stmt::ForStmtClass: {
  3931. const ForStmt *FS = cast<ForStmt>(S);
  3932. BlockScopeRAII Scope(Info);
  3933. // Step into the init statement in case it brings an (uninitialized)
  3934. // variable into scope.
  3935. if (const Stmt *Init = FS->getInit()) {
  3936. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  3937. if (ESR != ESR_CaseNotFound) {
  3938. assert(ESR != ESR_Succeeded);
  3939. return ESR;
  3940. }
  3941. }
  3942. EvalStmtResult ESR =
  3943. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3944. if (ESR != ESR_Continue)
  3945. return ESR;
  3946. if (FS->getInc()) {
  3947. FullExpressionRAII IncScope(Info);
  3948. if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
  3949. return ESR_Failed;
  3950. }
  3951. break;
  3952. }
  3953. case Stmt::DeclStmtClass: {
  3954. // Start the lifetime of any uninitialized variables we encounter. They
  3955. // might be used by the selected branch of the switch.
  3956. const DeclStmt *DS = cast<DeclStmt>(S);
  3957. for (const auto *D : DS->decls()) {
  3958. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  3959. if (VD->hasLocalStorage() && !VD->getInit())
  3960. if (!EvaluateVarDecl(Info, VD))
  3961. return ESR_Failed;
  3962. // FIXME: If the variable has initialization that can't be jumped
  3963. // over, bail out of any immediately-surrounding compound-statement
  3964. // too. There can't be any case labels here.
  3965. }
  3966. }
  3967. return ESR_CaseNotFound;
  3968. }
  3969. default:
  3970. return ESR_CaseNotFound;
  3971. }
  3972. }
  3973. switch (S->getStmtClass()) {
  3974. default:
  3975. if (const Expr *E = dyn_cast<Expr>(S)) {
  3976. // Don't bother evaluating beyond an expression-statement which couldn't
  3977. // be evaluated.
  3978. // FIXME: Do we need the FullExpressionRAII object here?
  3979. // VisitExprWithCleanups should create one when necessary.
  3980. FullExpressionRAII Scope(Info);
  3981. if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
  3982. return ESR_Failed;
  3983. return ESR_Succeeded;
  3984. }
  3985. Info.FFDiag(S->getBeginLoc());
  3986. return ESR_Failed;
  3987. case Stmt::NullStmtClass:
  3988. return ESR_Succeeded;
  3989. case Stmt::DeclStmtClass: {
  3990. const DeclStmt *DS = cast<DeclStmt>(S);
  3991. for (const auto *D : DS->decls()) {
  3992. // Each declaration initialization is its own full-expression.
  3993. FullExpressionRAII Scope(Info);
  3994. if (!EvaluateDecl(Info, D) && !Info.noteFailure())
  3995. return ESR_Failed;
  3996. if (!Scope.destroy())
  3997. return ESR_Failed;
  3998. }
  3999. return ESR_Succeeded;
  4000. }
  4001. case Stmt::ReturnStmtClass: {
  4002. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  4003. FullExpressionRAII Scope(Info);
  4004. if (RetExpr &&
  4005. !(Result.Slot
  4006. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  4007. : Evaluate(Result.Value, Info, RetExpr)))
  4008. return ESR_Failed;
  4009. return Scope.destroy() ? ESR_Returned : ESR_Failed;
  4010. }
  4011. case Stmt::CompoundStmtClass: {
  4012. BlockScopeRAII Scope(Info);
  4013. const CompoundStmt *CS = cast<CompoundStmt>(S);
  4014. for (const auto *BI : CS->body()) {
  4015. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  4016. if (ESR == ESR_Succeeded)
  4017. Case = nullptr;
  4018. else if (ESR != ESR_CaseNotFound) {
  4019. if (ESR != ESR_Failed && !Scope.destroy())
  4020. return ESR_Failed;
  4021. return ESR;
  4022. }
  4023. }
  4024. if (Case)
  4025. return ESR_CaseNotFound;
  4026. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4027. }
  4028. case Stmt::IfStmtClass: {
  4029. const IfStmt *IS = cast<IfStmt>(S);
  4030. // Evaluate the condition, as either a var decl or as an expression.
  4031. BlockScopeRAII Scope(Info);
  4032. if (const Stmt *Init = IS->getInit()) {
  4033. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  4034. if (ESR != ESR_Succeeded) {
  4035. if (ESR != ESR_Failed && !Scope.destroy())
  4036. return ESR_Failed;
  4037. return ESR;
  4038. }
  4039. }
  4040. bool Cond;
  4041. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  4042. return ESR_Failed;
  4043. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  4044. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  4045. if (ESR != ESR_Succeeded) {
  4046. if (ESR != ESR_Failed && !Scope.destroy())
  4047. return ESR_Failed;
  4048. return ESR;
  4049. }
  4050. }
  4051. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4052. }
  4053. case Stmt::WhileStmtClass: {
  4054. const WhileStmt *WS = cast<WhileStmt>(S);
  4055. while (true) {
  4056. BlockScopeRAII Scope(Info);
  4057. bool Continue;
  4058. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  4059. Continue))
  4060. return ESR_Failed;
  4061. if (!Continue)
  4062. break;
  4063. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  4064. if (ESR != ESR_Continue) {
  4065. if (ESR != ESR_Failed && !Scope.destroy())
  4066. return ESR_Failed;
  4067. return ESR;
  4068. }
  4069. if (!Scope.destroy())
  4070. return ESR_Failed;
  4071. }
  4072. return ESR_Succeeded;
  4073. }
  4074. case Stmt::DoStmtClass: {
  4075. const DoStmt *DS = cast<DoStmt>(S);
  4076. bool Continue;
  4077. do {
  4078. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  4079. if (ESR != ESR_Continue)
  4080. return ESR;
  4081. Case = nullptr;
  4082. FullExpressionRAII CondScope(Info);
  4083. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
  4084. !CondScope.destroy())
  4085. return ESR_Failed;
  4086. } while (Continue);
  4087. return ESR_Succeeded;
  4088. }
  4089. case Stmt::ForStmtClass: {
  4090. const ForStmt *FS = cast<ForStmt>(S);
  4091. BlockScopeRAII ForScope(Info);
  4092. if (FS->getInit()) {
  4093. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4094. if (ESR != ESR_Succeeded) {
  4095. if (ESR != ESR_Failed && !ForScope.destroy())
  4096. return ESR_Failed;
  4097. return ESR;
  4098. }
  4099. }
  4100. while (true) {
  4101. BlockScopeRAII IterScope(Info);
  4102. bool Continue = true;
  4103. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  4104. FS->getCond(), Continue))
  4105. return ESR_Failed;
  4106. if (!Continue)
  4107. break;
  4108. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4109. if (ESR != ESR_Continue) {
  4110. if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
  4111. return ESR_Failed;
  4112. return ESR;
  4113. }
  4114. if (FS->getInc()) {
  4115. FullExpressionRAII IncScope(Info);
  4116. if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
  4117. return ESR_Failed;
  4118. }
  4119. if (!IterScope.destroy())
  4120. return ESR_Failed;
  4121. }
  4122. return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
  4123. }
  4124. case Stmt::CXXForRangeStmtClass: {
  4125. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  4126. BlockScopeRAII Scope(Info);
  4127. // Evaluate the init-statement if present.
  4128. if (FS->getInit()) {
  4129. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4130. if (ESR != ESR_Succeeded) {
  4131. if (ESR != ESR_Failed && !Scope.destroy())
  4132. return ESR_Failed;
  4133. return ESR;
  4134. }
  4135. }
  4136. // Initialize the __range variable.
  4137. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  4138. if (ESR != ESR_Succeeded) {
  4139. if (ESR != ESR_Failed && !Scope.destroy())
  4140. return ESR_Failed;
  4141. return ESR;
  4142. }
  4143. // Create the __begin and __end iterators.
  4144. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  4145. if (ESR != ESR_Succeeded) {
  4146. if (ESR != ESR_Failed && !Scope.destroy())
  4147. return ESR_Failed;
  4148. return ESR;
  4149. }
  4150. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  4151. if (ESR != ESR_Succeeded) {
  4152. if (ESR != ESR_Failed && !Scope.destroy())
  4153. return ESR_Failed;
  4154. return ESR;
  4155. }
  4156. while (true) {
  4157. // Condition: __begin != __end.
  4158. {
  4159. bool Continue = true;
  4160. FullExpressionRAII CondExpr(Info);
  4161. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  4162. return ESR_Failed;
  4163. if (!Continue)
  4164. break;
  4165. }
  4166. // User's variable declaration, initialized by *__begin.
  4167. BlockScopeRAII InnerScope(Info);
  4168. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  4169. if (ESR != ESR_Succeeded) {
  4170. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4171. return ESR_Failed;
  4172. return ESR;
  4173. }
  4174. // Loop body.
  4175. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4176. if (ESR != ESR_Continue) {
  4177. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4178. return ESR_Failed;
  4179. return ESR;
  4180. }
  4181. // Increment: ++__begin
  4182. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  4183. return ESR_Failed;
  4184. if (!InnerScope.destroy())
  4185. return ESR_Failed;
  4186. }
  4187. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4188. }
  4189. case Stmt::SwitchStmtClass:
  4190. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  4191. case Stmt::ContinueStmtClass:
  4192. return ESR_Continue;
  4193. case Stmt::BreakStmtClass:
  4194. return ESR_Break;
  4195. case Stmt::LabelStmtClass:
  4196. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  4197. case Stmt::AttributedStmtClass:
  4198. // As a general principle, C++11 attributes can be ignored without
  4199. // any semantic impact.
  4200. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  4201. Case);
  4202. case Stmt::CaseStmtClass:
  4203. case Stmt::DefaultStmtClass:
  4204. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  4205. case Stmt::CXXTryStmtClass:
  4206. // Evaluate try blocks by evaluating all sub statements.
  4207. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  4208. }
  4209. }
  4210. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  4211. /// default constructor. If so, we'll fold it whether or not it's marked as
  4212. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  4213. /// so we need special handling.
  4214. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  4215. const CXXConstructorDecl *CD,
  4216. bool IsValueInitialization) {
  4217. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  4218. return false;
  4219. // Value-initialization does not call a trivial default constructor, so such a
  4220. // call is a core constant expression whether or not the constructor is
  4221. // constexpr.
  4222. if (!CD->isConstexpr() && !IsValueInitialization) {
  4223. if (Info.getLangOpts().CPlusPlus11) {
  4224. // FIXME: If DiagDecl is an implicitly-declared special member function,
  4225. // we should be much more explicit about why it's not constexpr.
  4226. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  4227. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  4228. Info.Note(CD->getLocation(), diag::note_declared_at);
  4229. } else {
  4230. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  4231. }
  4232. }
  4233. return true;
  4234. }
  4235. /// CheckConstexprFunction - Check that a function can be called in a constant
  4236. /// expression.
  4237. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  4238. const FunctionDecl *Declaration,
  4239. const FunctionDecl *Definition,
  4240. const Stmt *Body) {
  4241. // Potential constant expressions can contain calls to declared, but not yet
  4242. // defined, constexpr functions.
  4243. if (Info.checkingPotentialConstantExpression() && !Definition &&
  4244. Declaration->isConstexpr())
  4245. return false;
  4246. // Bail out if the function declaration itself is invalid. We will
  4247. // have produced a relevant diagnostic while parsing it, so just
  4248. // note the problematic sub-expression.
  4249. if (Declaration->isInvalidDecl()) {
  4250. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4251. return false;
  4252. }
  4253. // DR1872: An instantiated virtual constexpr function can't be called in a
  4254. // constant expression (prior to C++20). We can still constant-fold such a
  4255. // call.
  4256. if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
  4257. cast<CXXMethodDecl>(Declaration)->isVirtual())
  4258. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  4259. if (Definition && Definition->isInvalidDecl()) {
  4260. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4261. return false;
  4262. }
  4263. // Can we evaluate this function call?
  4264. if (Definition && Definition->isConstexpr() && Body)
  4265. return true;
  4266. if (Info.getLangOpts().CPlusPlus11) {
  4267. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4268. // If this function is not constexpr because it is an inherited
  4269. // non-constexpr constructor, diagnose that directly.
  4270. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4271. if (CD && CD->isInheritingConstructor()) {
  4272. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4273. if (!Inherited->isConstexpr())
  4274. DiagDecl = CD = Inherited;
  4275. }
  4276. // FIXME: If DiagDecl is an implicitly-declared special member function
  4277. // or an inheriting constructor, we should be much more explicit about why
  4278. // it's not constexpr.
  4279. if (CD && CD->isInheritingConstructor())
  4280. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4281. << CD->getInheritedConstructor().getConstructor()->getParent();
  4282. else
  4283. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4284. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4285. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4286. } else {
  4287. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4288. }
  4289. return false;
  4290. }
  4291. namespace {
  4292. struct CheckDynamicTypeHandler {
  4293. AccessKinds AccessKind;
  4294. typedef bool result_type;
  4295. bool failed() { return false; }
  4296. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4297. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4298. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4299. };
  4300. } // end anonymous namespace
  4301. /// Check that we can access the notional vptr of an object / determine its
  4302. /// dynamic type.
  4303. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4304. AccessKinds AK, bool Polymorphic) {
  4305. if (This.Designator.Invalid)
  4306. return false;
  4307. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4308. if (!Obj)
  4309. return false;
  4310. if (!Obj.Value) {
  4311. // The object is not usable in constant expressions, so we can't inspect
  4312. // its value to see if it's in-lifetime or what the active union members
  4313. // are. We can still check for a one-past-the-end lvalue.
  4314. if (This.Designator.isOnePastTheEnd() ||
  4315. This.Designator.isMostDerivedAnUnsizedArray()) {
  4316. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4317. ? diag::note_constexpr_access_past_end
  4318. : diag::note_constexpr_access_unsized_array)
  4319. << AK;
  4320. return false;
  4321. } else if (Polymorphic) {
  4322. // Conservatively refuse to perform a polymorphic operation if we would
  4323. // not be able to read a notional 'vptr' value.
  4324. APValue Val;
  4325. This.moveInto(Val);
  4326. QualType StarThisType =
  4327. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  4328. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  4329. << AK << Val.getAsString(Info.Ctx, StarThisType);
  4330. return false;
  4331. }
  4332. return true;
  4333. }
  4334. CheckDynamicTypeHandler Handler{AK};
  4335. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  4336. }
  4337. /// Check that the pointee of the 'this' pointer in a member function call is
  4338. /// either within its lifetime or in its period of construction or destruction.
  4339. static bool
  4340. checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  4341. const LValue &This,
  4342. const CXXMethodDecl *NamedMember) {
  4343. return checkDynamicType(
  4344. Info, E, This,
  4345. isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
  4346. }
  4347. struct DynamicType {
  4348. /// The dynamic class type of the object.
  4349. const CXXRecordDecl *Type;
  4350. /// The corresponding path length in the lvalue.
  4351. unsigned PathLength;
  4352. };
  4353. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  4354. unsigned PathLength) {
  4355. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  4356. Designator.Entries.size() && "invalid path length");
  4357. return (PathLength == Designator.MostDerivedPathLength)
  4358. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4359. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4360. }
  4361. /// Determine the dynamic type of an object.
  4362. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4363. LValue &This, AccessKinds AK) {
  4364. // If we don't have an lvalue denoting an object of class type, there is no
  4365. // meaningful dynamic type. (We consider objects of non-class type to have no
  4366. // dynamic type.)
  4367. if (!checkDynamicType(Info, E, This, AK, true))
  4368. return None;
  4369. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4370. // shouldn't happen other than in constant-folding situations, since literal
  4371. // types can't have virtual bases.
  4372. //
  4373. // Note that consumers of DynamicType assume that the type has no virtual
  4374. // bases, and will need modifications if this restriction is relaxed.
  4375. const CXXRecordDecl *Class =
  4376. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  4377. if (!Class || Class->getNumVBases()) {
  4378. Info.FFDiag(E);
  4379. return None;
  4380. }
  4381. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  4382. // binary search here instead. But the overwhelmingly common case is that
  4383. // we're not in the middle of a constructor, so it probably doesn't matter
  4384. // in practice.
  4385. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  4386. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  4387. PathLength <= Path.size(); ++PathLength) {
  4388. switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
  4389. Path.slice(0, PathLength))) {
  4390. case ConstructionPhase::Bases:
  4391. case ConstructionPhase::DestroyingBases:
  4392. // We're constructing or destroying a base class. This is not the dynamic
  4393. // type.
  4394. break;
  4395. case ConstructionPhase::None:
  4396. case ConstructionPhase::AfterBases:
  4397. case ConstructionPhase::Destroying:
  4398. // We've finished constructing the base classes and not yet started
  4399. // destroying them again, so this is the dynamic type.
  4400. return DynamicType{getBaseClassType(This.Designator, PathLength),
  4401. PathLength};
  4402. }
  4403. }
  4404. // CWG issue 1517: we're constructing a base class of the object described by
  4405. // 'This', so that object has not yet begun its period of construction and
  4406. // any polymorphic operation on it results in undefined behavior.
  4407. Info.FFDiag(E);
  4408. return None;
  4409. }
  4410. /// Perform virtual dispatch.
  4411. static const CXXMethodDecl *HandleVirtualDispatch(
  4412. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  4413. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  4414. Optional<DynamicType> DynType = ComputeDynamicType(
  4415. Info, E, This,
  4416. isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
  4417. if (!DynType)
  4418. return nullptr;
  4419. // Find the final overrider. It must be declared in one of the classes on the
  4420. // path from the dynamic type to the static type.
  4421. // FIXME: If we ever allow literal types to have virtual base classes, that
  4422. // won't be true.
  4423. const CXXMethodDecl *Callee = Found;
  4424. unsigned PathLength = DynType->PathLength;
  4425. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  4426. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  4427. const CXXMethodDecl *Overrider =
  4428. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  4429. if (Overrider) {
  4430. Callee = Overrider;
  4431. break;
  4432. }
  4433. }
  4434. // C++2a [class.abstract]p6:
  4435. // the effect of making a virtual call to a pure virtual function [...] is
  4436. // undefined
  4437. if (Callee->isPure()) {
  4438. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  4439. Info.Note(Callee->getLocation(), diag::note_declared_at);
  4440. return nullptr;
  4441. }
  4442. // If necessary, walk the rest of the path to determine the sequence of
  4443. // covariant adjustment steps to apply.
  4444. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  4445. Found->getReturnType())) {
  4446. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  4447. for (unsigned CovariantPathLength = PathLength + 1;
  4448. CovariantPathLength != This.Designator.Entries.size();
  4449. ++CovariantPathLength) {
  4450. const CXXRecordDecl *NextClass =
  4451. getBaseClassType(This.Designator, CovariantPathLength);
  4452. const CXXMethodDecl *Next =
  4453. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  4454. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  4455. Next->getReturnType(), CovariantAdjustmentPath.back()))
  4456. CovariantAdjustmentPath.push_back(Next->getReturnType());
  4457. }
  4458. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  4459. CovariantAdjustmentPath.back()))
  4460. CovariantAdjustmentPath.push_back(Found->getReturnType());
  4461. }
  4462. // Perform 'this' adjustment.
  4463. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  4464. return nullptr;
  4465. return Callee;
  4466. }
  4467. /// Perform the adjustment from a value returned by a virtual function to
  4468. /// a value of the statically expected type, which may be a pointer or
  4469. /// reference to a base class of the returned type.
  4470. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  4471. APValue &Result,
  4472. ArrayRef<QualType> Path) {
  4473. assert(Result.isLValue() &&
  4474. "unexpected kind of APValue for covariant return");
  4475. if (Result.isNullPointer())
  4476. return true;
  4477. LValue LVal;
  4478. LVal.setFrom(Info.Ctx, Result);
  4479. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  4480. for (unsigned I = 1; I != Path.size(); ++I) {
  4481. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  4482. assert(OldClass && NewClass && "unexpected kind of covariant return");
  4483. if (OldClass != NewClass &&
  4484. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  4485. return false;
  4486. OldClass = NewClass;
  4487. }
  4488. LVal.moveInto(Result);
  4489. return true;
  4490. }
  4491. /// Determine whether \p Base, which is known to be a direct base class of
  4492. /// \p Derived, is a public base class.
  4493. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  4494. const CXXRecordDecl *Base) {
  4495. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  4496. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  4497. if (BaseClass && declaresSameEntity(BaseClass, Base))
  4498. return BaseSpec.getAccessSpecifier() == AS_public;
  4499. }
  4500. llvm_unreachable("Base is not a direct base of Derived");
  4501. }
  4502. /// Apply the given dynamic cast operation on the provided lvalue.
  4503. ///
  4504. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  4505. /// to find a suitable target subobject.
  4506. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  4507. LValue &Ptr) {
  4508. // We can't do anything with a non-symbolic pointer value.
  4509. SubobjectDesignator &D = Ptr.Designator;
  4510. if (D.Invalid)
  4511. return false;
  4512. // C++ [expr.dynamic.cast]p6:
  4513. // If v is a null pointer value, the result is a null pointer value.
  4514. if (Ptr.isNullPointer() && !E->isGLValue())
  4515. return true;
  4516. // For all the other cases, we need the pointer to point to an object within
  4517. // its lifetime / period of construction / destruction, and we need to know
  4518. // its dynamic type.
  4519. Optional<DynamicType> DynType =
  4520. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  4521. if (!DynType)
  4522. return false;
  4523. // C++ [expr.dynamic.cast]p7:
  4524. // If T is "pointer to cv void", then the result is a pointer to the most
  4525. // derived object
  4526. if (E->getType()->isVoidPointerType())
  4527. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  4528. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  4529. assert(C && "dynamic_cast target is not void pointer nor class");
  4530. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  4531. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  4532. // C++ [expr.dynamic.cast]p9:
  4533. if (!E->isGLValue()) {
  4534. // The value of a failed cast to pointer type is the null pointer value
  4535. // of the required result type.
  4536. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  4537. Ptr.setNull(E->getType(), TargetVal);
  4538. return true;
  4539. }
  4540. // A failed cast to reference type throws [...] std::bad_cast.
  4541. unsigned DiagKind;
  4542. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  4543. DynType->Type->isDerivedFrom(C)))
  4544. DiagKind = 0;
  4545. else if (!Paths || Paths->begin() == Paths->end())
  4546. DiagKind = 1;
  4547. else if (Paths->isAmbiguous(CQT))
  4548. DiagKind = 2;
  4549. else {
  4550. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  4551. DiagKind = 3;
  4552. }
  4553. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  4554. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  4555. << Info.Ctx.getRecordType(DynType->Type)
  4556. << E->getType().getUnqualifiedType();
  4557. return false;
  4558. };
  4559. // Runtime check, phase 1:
  4560. // Walk from the base subobject towards the derived object looking for the
  4561. // target type.
  4562. for (int PathLength = Ptr.Designator.Entries.size();
  4563. PathLength >= (int)DynType->PathLength; --PathLength) {
  4564. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  4565. if (declaresSameEntity(Class, C))
  4566. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  4567. // We can only walk across public inheritance edges.
  4568. if (PathLength > (int)DynType->PathLength &&
  4569. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  4570. Class))
  4571. return RuntimeCheckFailed(nullptr);
  4572. }
  4573. // Runtime check, phase 2:
  4574. // Search the dynamic type for an unambiguous public base of type C.
  4575. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  4576. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  4577. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  4578. Paths.front().Access == AS_public) {
  4579. // Downcast to the dynamic type...
  4580. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  4581. return false;
  4582. // ... then upcast to the chosen base class subobject.
  4583. for (CXXBasePathElement &Elem : Paths.front())
  4584. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  4585. return false;
  4586. return true;
  4587. }
  4588. // Otherwise, the runtime check fails.
  4589. return RuntimeCheckFailed(&Paths);
  4590. }
  4591. namespace {
  4592. struct StartLifetimeOfUnionMemberHandler {
  4593. const FieldDecl *Field;
  4594. static const AccessKinds AccessKind = AK_Assign;
  4595. typedef bool result_type;
  4596. bool failed() { return false; }
  4597. bool found(APValue &Subobj, QualType SubobjType) {
  4598. // We are supposed to perform no initialization but begin the lifetime of
  4599. // the object. We interpret that as meaning to do what default
  4600. // initialization of the object would do if all constructors involved were
  4601. // trivial:
  4602. // * All base, non-variant member, and array element subobjects' lifetimes
  4603. // begin
  4604. // * No variant members' lifetimes begin
  4605. // * All scalar subobjects whose lifetimes begin have indeterminate values
  4606. assert(SubobjType->isUnionType());
  4607. if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
  4608. !Subobj.getUnionValue().hasValue())
  4609. Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
  4610. return true;
  4611. }
  4612. bool found(APSInt &Value, QualType SubobjType) {
  4613. llvm_unreachable("wrong value kind for union object");
  4614. }
  4615. bool found(APFloat &Value, QualType SubobjType) {
  4616. llvm_unreachable("wrong value kind for union object");
  4617. }
  4618. };
  4619. } // end anonymous namespace
  4620. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  4621. /// Handle a builtin simple-assignment or a call to a trivial assignment
  4622. /// operator whose left-hand side might involve a union member access. If it
  4623. /// does, implicitly start the lifetime of any accessed union elements per
  4624. /// C++20 [class.union]5.
  4625. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  4626. const LValue &LHS) {
  4627. if (LHS.InvalidBase || LHS.Designator.Invalid)
  4628. return false;
  4629. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  4630. // C++ [class.union]p5:
  4631. // define the set S(E) of subexpressions of E as follows:
  4632. unsigned PathLength = LHS.Designator.Entries.size();
  4633. for (const Expr *E = LHSExpr; E != nullptr;) {
  4634. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  4635. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  4636. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  4637. if (!FD)
  4638. break;
  4639. // ... and also contains A.B if B names a union member
  4640. if (FD->getParent()->isUnion())
  4641. UnionPathLengths.push_back({PathLength - 1, FD});
  4642. E = ME->getBase();
  4643. --PathLength;
  4644. assert(declaresSameEntity(FD,
  4645. LHS.Designator.Entries[PathLength]
  4646. .getAsBaseOrMember().getPointer()));
  4647. // -- If E is of the form A[B] and is interpreted as a built-in array
  4648. // subscripting operator, S(E) is [S(the array operand, if any)].
  4649. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  4650. // Step over an ArrayToPointerDecay implicit cast.
  4651. auto *Base = ASE->getBase()->IgnoreImplicit();
  4652. if (!Base->getType()->isArrayType())
  4653. break;
  4654. E = Base;
  4655. --PathLength;
  4656. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4657. // Step over a derived-to-base conversion.
  4658. E = ICE->getSubExpr();
  4659. if (ICE->getCastKind() == CK_NoOp)
  4660. continue;
  4661. if (ICE->getCastKind() != CK_DerivedToBase &&
  4662. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  4663. break;
  4664. // Walk path backwards as we walk up from the base to the derived class.
  4665. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  4666. --PathLength;
  4667. (void)Elt;
  4668. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  4669. LHS.Designator.Entries[PathLength]
  4670. .getAsBaseOrMember().getPointer()));
  4671. }
  4672. // -- Otherwise, S(E) is empty.
  4673. } else {
  4674. break;
  4675. }
  4676. }
  4677. // Common case: no unions' lifetimes are started.
  4678. if (UnionPathLengths.empty())
  4679. return true;
  4680. // if modification of X [would access an inactive union member], an object
  4681. // of the type of X is implicitly created
  4682. CompleteObject Obj =
  4683. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  4684. if (!Obj)
  4685. return false;
  4686. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  4687. llvm::reverse(UnionPathLengths)) {
  4688. // Form a designator for the union object.
  4689. SubobjectDesignator D = LHS.Designator;
  4690. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  4691. StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
  4692. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  4693. return false;
  4694. }
  4695. return true;
  4696. }
  4697. /// Determine if a class has any fields that might need to be copied by a
  4698. /// trivial copy or move operation.
  4699. static bool hasFields(const CXXRecordDecl *RD) {
  4700. if (!RD || RD->isEmpty())
  4701. return false;
  4702. for (auto *FD : RD->fields()) {
  4703. if (FD->isUnnamedBitfield())
  4704. continue;
  4705. return true;
  4706. }
  4707. for (auto &Base : RD->bases())
  4708. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  4709. return true;
  4710. return false;
  4711. }
  4712. namespace {
  4713. typedef SmallVector<APValue, 8> ArgVector;
  4714. }
  4715. /// EvaluateArgs - Evaluate the arguments to a function call.
  4716. static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
  4717. EvalInfo &Info, const FunctionDecl *Callee) {
  4718. bool Success = true;
  4719. llvm::SmallBitVector ForbiddenNullArgs;
  4720. if (Callee->hasAttr<NonNullAttr>()) {
  4721. ForbiddenNullArgs.resize(Args.size());
  4722. for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
  4723. if (!Attr->args_size()) {
  4724. ForbiddenNullArgs.set();
  4725. break;
  4726. } else
  4727. for (auto Idx : Attr->args()) {
  4728. unsigned ASTIdx = Idx.getASTIndex();
  4729. if (ASTIdx >= Args.size())
  4730. continue;
  4731. ForbiddenNullArgs[ASTIdx] = 1;
  4732. }
  4733. }
  4734. }
  4735. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  4736. I != E; ++I) {
  4737. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  4738. // If we're checking for a potential constant expression, evaluate all
  4739. // initializers even if some of them fail.
  4740. if (!Info.noteFailure())
  4741. return false;
  4742. Success = false;
  4743. } else if (!ForbiddenNullArgs.empty() &&
  4744. ForbiddenNullArgs[I - Args.begin()] &&
  4745. ArgValues[I - Args.begin()].isNullPointer()) {
  4746. Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
  4747. if (!Info.noteFailure())
  4748. return false;
  4749. Success = false;
  4750. }
  4751. }
  4752. return Success;
  4753. }
  4754. /// Evaluate a function call.
  4755. static bool HandleFunctionCall(SourceLocation CallLoc,
  4756. const FunctionDecl *Callee, const LValue *This,
  4757. ArrayRef<const Expr*> Args, const Stmt *Body,
  4758. EvalInfo &Info, APValue &Result,
  4759. const LValue *ResultSlot) {
  4760. ArgVector ArgValues(Args.size());
  4761. if (!EvaluateArgs(Args, ArgValues, Info, Callee))
  4762. return false;
  4763. if (!Info.CheckCallLimit(CallLoc))
  4764. return false;
  4765. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  4766. // For a trivial copy or move assignment, perform an APValue copy. This is
  4767. // essential for unions, where the operations performed by the assignment
  4768. // operator cannot be represented as statements.
  4769. //
  4770. // Skip this for non-union classes with no fields; in that case, the defaulted
  4771. // copy/move does not actually read the object.
  4772. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  4773. if (MD && MD->isDefaulted() &&
  4774. (MD->getParent()->isUnion() ||
  4775. (MD->isTrivial() && hasFields(MD->getParent())))) {
  4776. assert(This &&
  4777. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  4778. LValue RHS;
  4779. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4780. APValue RHSValue;
  4781. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
  4782. RHSValue, MD->getParent()->isUnion()))
  4783. return false;
  4784. if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
  4785. !HandleUnionActiveMemberChange(Info, Args[0], *This))
  4786. return false;
  4787. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  4788. RHSValue))
  4789. return false;
  4790. This->moveInto(Result);
  4791. return true;
  4792. } else if (MD && isLambdaCallOperator(MD)) {
  4793. // We're in a lambda; determine the lambda capture field maps unless we're
  4794. // just constexpr checking a lambda's call operator. constexpr checking is
  4795. // done before the captures have been added to the closure object (unless
  4796. // we're inferring constexpr-ness), so we don't have access to them in this
  4797. // case. But since we don't need the captures to constexpr check, we can
  4798. // just ignore them.
  4799. if (!Info.checkingPotentialConstantExpression())
  4800. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  4801. Frame.LambdaThisCaptureField);
  4802. }
  4803. StmtResult Ret = {Result, ResultSlot};
  4804. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  4805. if (ESR == ESR_Succeeded) {
  4806. if (Callee->getReturnType()->isVoidType())
  4807. return true;
  4808. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  4809. }
  4810. return ESR == ESR_Returned;
  4811. }
  4812. /// Evaluate a constructor call.
  4813. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4814. APValue *ArgValues,
  4815. const CXXConstructorDecl *Definition,
  4816. EvalInfo &Info, APValue &Result) {
  4817. SourceLocation CallLoc = E->getExprLoc();
  4818. if (!Info.CheckCallLimit(CallLoc))
  4819. return false;
  4820. const CXXRecordDecl *RD = Definition->getParent();
  4821. if (RD->getNumVBases()) {
  4822. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  4823. return false;
  4824. }
  4825. EvalInfo::EvaluatingConstructorRAII EvalObj(
  4826. Info,
  4827. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  4828. RD->getNumBases());
  4829. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  4830. // FIXME: Creating an APValue just to hold a nonexistent return value is
  4831. // wasteful.
  4832. APValue RetVal;
  4833. StmtResult Ret = {RetVal, nullptr};
  4834. // If it's a delegating constructor, delegate.
  4835. if (Definition->isDelegatingConstructor()) {
  4836. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  4837. {
  4838. FullExpressionRAII InitScope(Info);
  4839. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
  4840. !InitScope.destroy())
  4841. return false;
  4842. }
  4843. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4844. }
  4845. // For a trivial copy or move constructor, perform an APValue copy. This is
  4846. // essential for unions (or classes with anonymous union members), where the
  4847. // operations performed by the constructor cannot be represented by
  4848. // ctor-initializers.
  4849. //
  4850. // Skip this for empty non-union classes; we should not perform an
  4851. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4852. // actually read them.
  4853. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4854. (Definition->getParent()->isUnion() ||
  4855. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4856. LValue RHS;
  4857. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4858. return handleLValueToRValueConversion(
  4859. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4860. RHS, Result, Definition->getParent()->isUnion());
  4861. }
  4862. // Reserve space for the struct members.
  4863. if (!RD->isUnion() && !Result.hasValue())
  4864. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4865. std::distance(RD->field_begin(), RD->field_end()));
  4866. if (RD->isInvalidDecl()) return false;
  4867. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4868. // A scope for temporaries lifetime-extended by reference members.
  4869. BlockScopeRAII LifetimeExtendedScope(Info);
  4870. bool Success = true;
  4871. unsigned BasesSeen = 0;
  4872. #ifndef NDEBUG
  4873. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4874. #endif
  4875. CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
  4876. auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
  4877. // We might be initializing the same field again if this is an indirect
  4878. // field initialization.
  4879. if (FieldIt == RD->field_end() ||
  4880. FieldIt->getFieldIndex() > FD->getFieldIndex()) {
  4881. assert(Indirect && "fields out of order?");
  4882. return;
  4883. }
  4884. // Default-initialize any fields with no explicit initializer.
  4885. for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
  4886. assert(FieldIt != RD->field_end() && "missing field?");
  4887. if (!FieldIt->isUnnamedBitfield())
  4888. Result.getStructField(FieldIt->getFieldIndex()) =
  4889. getDefaultInitValue(FieldIt->getType());
  4890. }
  4891. ++FieldIt;
  4892. };
  4893. for (const auto *I : Definition->inits()) {
  4894. LValue Subobject = This;
  4895. LValue SubobjectParent = This;
  4896. APValue *Value = &Result;
  4897. // Determine the subobject to initialize.
  4898. FieldDecl *FD = nullptr;
  4899. if (I->isBaseInitializer()) {
  4900. QualType BaseType(I->getBaseClass(), 0);
  4901. #ifndef NDEBUG
  4902. // Non-virtual base classes are initialized in the order in the class
  4903. // definition. We have already checked for virtual base classes.
  4904. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4905. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4906. "base class initializers not in expected order");
  4907. ++BaseIt;
  4908. #endif
  4909. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4910. BaseType->getAsCXXRecordDecl(), &Layout))
  4911. return false;
  4912. Value = &Result.getStructBase(BasesSeen++);
  4913. } else if ((FD = I->getMember())) {
  4914. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4915. return false;
  4916. if (RD->isUnion()) {
  4917. Result = APValue(FD);
  4918. Value = &Result.getUnionValue();
  4919. } else {
  4920. SkipToField(FD, false);
  4921. Value = &Result.getStructField(FD->getFieldIndex());
  4922. }
  4923. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4924. // Walk the indirect field decl's chain to find the object to initialize,
  4925. // and make sure we've initialized every step along it.
  4926. auto IndirectFieldChain = IFD->chain();
  4927. for (auto *C : IndirectFieldChain) {
  4928. FD = cast<FieldDecl>(C);
  4929. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4930. // Switch the union field if it differs. This happens if we had
  4931. // preceding zero-initialization, and we're now initializing a union
  4932. // subobject other than the first.
  4933. // FIXME: In this case, the values of the other subobjects are
  4934. // specified, since zero-initialization sets all padding bits to zero.
  4935. if (!Value->hasValue() ||
  4936. (Value->isUnion() && Value->getUnionField() != FD)) {
  4937. if (CD->isUnion())
  4938. *Value = APValue(FD);
  4939. else
  4940. // FIXME: This immediately starts the lifetime of all members of an
  4941. // anonymous struct. It would be preferable to strictly start member
  4942. // lifetime in initialization order.
  4943. *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
  4944. }
  4945. // Store Subobject as its parent before updating it for the last element
  4946. // in the chain.
  4947. if (C == IndirectFieldChain.back())
  4948. SubobjectParent = Subobject;
  4949. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4950. return false;
  4951. if (CD->isUnion())
  4952. Value = &Value->getUnionValue();
  4953. else {
  4954. if (C == IndirectFieldChain.front() && !RD->isUnion())
  4955. SkipToField(FD, true);
  4956. Value = &Value->getStructField(FD->getFieldIndex());
  4957. }
  4958. }
  4959. } else {
  4960. llvm_unreachable("unknown base initializer kind");
  4961. }
  4962. // Need to override This for implicit field initializers as in this case
  4963. // This refers to innermost anonymous struct/union containing initializer,
  4964. // not to currently constructed class.
  4965. const Expr *Init = I->getInit();
  4966. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4967. isa<CXXDefaultInitExpr>(Init));
  4968. FullExpressionRAII InitScope(Info);
  4969. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4970. (FD && FD->isBitField() &&
  4971. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4972. // If we're checking for a potential constant expression, evaluate all
  4973. // initializers even if some of them fail.
  4974. if (!Info.noteFailure())
  4975. return false;
  4976. Success = false;
  4977. }
  4978. // This is the point at which the dynamic type of the object becomes this
  4979. // class type.
  4980. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  4981. EvalObj.finishedConstructingBases();
  4982. }
  4983. // Default-initialize any remaining fields.
  4984. if (!RD->isUnion()) {
  4985. for (; FieldIt != RD->field_end(); ++FieldIt) {
  4986. if (!FieldIt->isUnnamedBitfield())
  4987. Result.getStructField(FieldIt->getFieldIndex()) =
  4988. getDefaultInitValue(FieldIt->getType());
  4989. }
  4990. }
  4991. return Success &&
  4992. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
  4993. LifetimeExtendedScope.destroy();
  4994. }
  4995. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4996. ArrayRef<const Expr*> Args,
  4997. const CXXConstructorDecl *Definition,
  4998. EvalInfo &Info, APValue &Result) {
  4999. ArgVector ArgValues(Args.size());
  5000. if (!EvaluateArgs(Args, ArgValues, Info, Definition))
  5001. return false;
  5002. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  5003. Info, Result);
  5004. }
  5005. static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
  5006. const LValue &This, APValue &Value,
  5007. QualType T) {
  5008. // Objects can only be destroyed while they're within their lifetimes.
  5009. // FIXME: We have no representation for whether an object of type nullptr_t
  5010. // is in its lifetime; it usually doesn't matter. Perhaps we should model it
  5011. // as indeterminate instead?
  5012. if (Value.isAbsent() && !T->isNullPtrType()) {
  5013. APValue Printable;
  5014. This.moveInto(Printable);
  5015. Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
  5016. << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
  5017. return false;
  5018. }
  5019. // Invent an expression for location purposes.
  5020. // FIXME: We shouldn't need to do this.
  5021. OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
  5022. // For arrays, destroy elements right-to-left.
  5023. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
  5024. uint64_t Size = CAT->getSize().getZExtValue();
  5025. QualType ElemT = CAT->getElementType();
  5026. LValue ElemLV = This;
  5027. ElemLV.addArray(Info, &LocE, CAT);
  5028. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
  5029. return false;
  5030. // Ensure that we have actual array elements available to destroy; the
  5031. // destructors might mutate the value, so we can't run them on the array
  5032. // filler.
  5033. if (Size && Size > Value.getArrayInitializedElts())
  5034. expandArray(Value, Value.getArraySize() - 1);
  5035. for (; Size != 0; --Size) {
  5036. APValue &Elem = Value.getArrayInitializedElt(Size - 1);
  5037. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
  5038. !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
  5039. return false;
  5040. }
  5041. // End the lifetime of this array now.
  5042. Value = APValue();
  5043. return true;
  5044. }
  5045. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  5046. if (!RD) {
  5047. if (T.isDestructedType()) {
  5048. Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
  5049. return false;
  5050. }
  5051. Value = APValue();
  5052. return true;
  5053. }
  5054. if (RD->getNumVBases()) {
  5055. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  5056. return false;
  5057. }
  5058. const CXXDestructorDecl *DD = RD->getDestructor();
  5059. if (!DD && !RD->hasTrivialDestructor()) {
  5060. Info.FFDiag(CallLoc);
  5061. return false;
  5062. }
  5063. if (!DD || DD->isTrivial() ||
  5064. (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
  5065. // A trivial destructor just ends the lifetime of the object. Check for
  5066. // this case before checking for a body, because we might not bother
  5067. // building a body for a trivial destructor. Note that it doesn't matter
  5068. // whether the destructor is constexpr in this case; all trivial
  5069. // destructors are constexpr.
  5070. //
  5071. // If an anonymous union would be destroyed, some enclosing destructor must
  5072. // have been explicitly defined, and the anonymous union destruction should
  5073. // have no effect.
  5074. Value = APValue();
  5075. return true;
  5076. }
  5077. if (!Info.CheckCallLimit(CallLoc))
  5078. return false;
  5079. const FunctionDecl *Definition = nullptr;
  5080. const Stmt *Body = DD->getBody(Definition);
  5081. if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
  5082. return false;
  5083. CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
  5084. // We're now in the period of destruction of this object.
  5085. unsigned BasesLeft = RD->getNumBases();
  5086. EvalInfo::EvaluatingDestructorRAII EvalObj(
  5087. Info,
  5088. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
  5089. if (!EvalObj.DidInsert) {
  5090. // C++2a [class.dtor]p19:
  5091. // the behavior is undefined if the destructor is invoked for an object
  5092. // whose lifetime has ended
  5093. // (Note that formally the lifetime ends when the period of destruction
  5094. // begins, even though certain uses of the object remain valid until the
  5095. // period of destruction ends.)
  5096. Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
  5097. return false;
  5098. }
  5099. // FIXME: Creating an APValue just to hold a nonexistent return value is
  5100. // wasteful.
  5101. APValue RetVal;
  5102. StmtResult Ret = {RetVal, nullptr};
  5103. if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
  5104. return false;
  5105. // A union destructor does not implicitly destroy its members.
  5106. if (RD->isUnion())
  5107. return true;
  5108. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5109. // We don't have a good way to iterate fields in reverse, so collect all the
  5110. // fields first and then walk them backwards.
  5111. SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
  5112. for (const FieldDecl *FD : llvm::reverse(Fields)) {
  5113. if (FD->isUnnamedBitfield())
  5114. continue;
  5115. LValue Subobject = This;
  5116. if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
  5117. return false;
  5118. APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
  5119. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5120. FD->getType()))
  5121. return false;
  5122. }
  5123. if (BasesLeft != 0)
  5124. EvalObj.startedDestroyingBases();
  5125. // Destroy base classes in reverse order.
  5126. for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
  5127. --BasesLeft;
  5128. QualType BaseType = Base.getType();
  5129. LValue Subobject = This;
  5130. if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
  5131. BaseType->getAsCXXRecordDecl(), &Layout))
  5132. return false;
  5133. APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
  5134. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5135. BaseType))
  5136. return false;
  5137. }
  5138. assert(BasesLeft == 0 && "NumBases was wrong?");
  5139. // The period of destruction ends now. The object is gone.
  5140. Value = APValue();
  5141. return true;
  5142. }
  5143. namespace {
  5144. struct DestroyObjectHandler {
  5145. EvalInfo &Info;
  5146. const Expr *E;
  5147. const LValue &This;
  5148. const AccessKinds AccessKind;
  5149. typedef bool result_type;
  5150. bool failed() { return false; }
  5151. bool found(APValue &Subobj, QualType SubobjType) {
  5152. return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
  5153. SubobjType);
  5154. }
  5155. bool found(APSInt &Value, QualType SubobjType) {
  5156. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5157. return false;
  5158. }
  5159. bool found(APFloat &Value, QualType SubobjType) {
  5160. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5161. return false;
  5162. }
  5163. };
  5164. }
  5165. /// Perform a destructor or pseudo-destructor call on the given object, which
  5166. /// might in general not be a complete object.
  5167. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  5168. const LValue &This, QualType ThisType) {
  5169. CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
  5170. DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
  5171. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  5172. }
  5173. /// Destroy and end the lifetime of the given complete object.
  5174. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  5175. APValue::LValueBase LVBase, APValue &Value,
  5176. QualType T) {
  5177. // If we've had an unmodeled side-effect, we can't rely on mutable state
  5178. // (such as the object we're about to destroy) being correct.
  5179. if (Info.EvalStatus.HasSideEffects)
  5180. return false;
  5181. LValue LV;
  5182. LV.set({LVBase});
  5183. return HandleDestructionImpl(Info, Loc, LV, Value, T);
  5184. }
  5185. //===----------------------------------------------------------------------===//
  5186. // Generic Evaluation
  5187. //===----------------------------------------------------------------------===//
  5188. namespace {
  5189. class BitCastBuffer {
  5190. // FIXME: We're going to need bit-level granularity when we support
  5191. // bit-fields.
  5192. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  5193. // we don't support a host or target where that is the case. Still, we should
  5194. // use a more generic type in case we ever do.
  5195. SmallVector<Optional<unsigned char>, 32> Bytes;
  5196. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  5197. "Need at least 8 bit unsigned char");
  5198. bool TargetIsLittleEndian;
  5199. public:
  5200. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  5201. : Bytes(Width.getQuantity()),
  5202. TargetIsLittleEndian(TargetIsLittleEndian) {}
  5203. LLVM_NODISCARD
  5204. bool readObject(CharUnits Offset, CharUnits Width,
  5205. SmallVectorImpl<unsigned char> &Output) const {
  5206. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  5207. // If a byte of an integer is uninitialized, then the whole integer is
  5208. // uninitalized.
  5209. if (!Bytes[I.getQuantity()])
  5210. return false;
  5211. Output.push_back(*Bytes[I.getQuantity()]);
  5212. }
  5213. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5214. std::reverse(Output.begin(), Output.end());
  5215. return true;
  5216. }
  5217. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  5218. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5219. std::reverse(Input.begin(), Input.end());
  5220. size_t Index = 0;
  5221. for (unsigned char Byte : Input) {
  5222. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  5223. Bytes[Offset.getQuantity() + Index] = Byte;
  5224. ++Index;
  5225. }
  5226. }
  5227. size_t size() { return Bytes.size(); }
  5228. };
  5229. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  5230. /// target would represent the value at runtime.
  5231. class APValueToBufferConverter {
  5232. EvalInfo &Info;
  5233. BitCastBuffer Buffer;
  5234. const CastExpr *BCE;
  5235. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  5236. const CastExpr *BCE)
  5237. : Info(Info),
  5238. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  5239. BCE(BCE) {}
  5240. bool visit(const APValue &Val, QualType Ty) {
  5241. return visit(Val, Ty, CharUnits::fromQuantity(0));
  5242. }
  5243. // Write out Val with type Ty into Buffer starting at Offset.
  5244. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  5245. assert((size_t)Offset.getQuantity() <= Buffer.size());
  5246. // As a special case, nullptr_t has an indeterminate value.
  5247. if (Ty->isNullPtrType())
  5248. return true;
  5249. // Dig through Src to find the byte at SrcOffset.
  5250. switch (Val.getKind()) {
  5251. case APValue::Indeterminate:
  5252. case APValue::None:
  5253. return true;
  5254. case APValue::Int:
  5255. return visitInt(Val.getInt(), Ty, Offset);
  5256. case APValue::Float:
  5257. return visitFloat(Val.getFloat(), Ty, Offset);
  5258. case APValue::Array:
  5259. return visitArray(Val, Ty, Offset);
  5260. case APValue::Struct:
  5261. return visitRecord(Val, Ty, Offset);
  5262. case APValue::ComplexInt:
  5263. case APValue::ComplexFloat:
  5264. case APValue::Vector:
  5265. case APValue::FixedPoint:
  5266. // FIXME: We should support these.
  5267. case APValue::Union:
  5268. case APValue::MemberPointer:
  5269. case APValue::AddrLabelDiff: {
  5270. Info.FFDiag(BCE->getBeginLoc(),
  5271. diag::note_constexpr_bit_cast_unsupported_type)
  5272. << Ty;
  5273. return false;
  5274. }
  5275. case APValue::LValue:
  5276. llvm_unreachable("LValue subobject in bit_cast?");
  5277. }
  5278. llvm_unreachable("Unhandled APValue::ValueKind");
  5279. }
  5280. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  5281. const RecordDecl *RD = Ty->getAsRecordDecl();
  5282. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5283. // Visit the base classes.
  5284. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5285. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5286. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5287. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5288. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  5289. Layout.getBaseClassOffset(BaseDecl) + Offset))
  5290. return false;
  5291. }
  5292. }
  5293. // Visit the fields.
  5294. unsigned FieldIdx = 0;
  5295. for (FieldDecl *FD : RD->fields()) {
  5296. if (FD->isBitField()) {
  5297. Info.FFDiag(BCE->getBeginLoc(),
  5298. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5299. return false;
  5300. }
  5301. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5302. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  5303. "only bit-fields can have sub-char alignment");
  5304. CharUnits FieldOffset =
  5305. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  5306. QualType FieldTy = FD->getType();
  5307. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  5308. return false;
  5309. ++FieldIdx;
  5310. }
  5311. return true;
  5312. }
  5313. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  5314. const auto *CAT =
  5315. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  5316. if (!CAT)
  5317. return false;
  5318. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  5319. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  5320. unsigned ArraySize = Val.getArraySize();
  5321. // First, initialize the initialized elements.
  5322. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  5323. const APValue &SubObj = Val.getArrayInitializedElt(I);
  5324. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  5325. return false;
  5326. }
  5327. // Next, initialize the rest of the array using the filler.
  5328. if (Val.hasArrayFiller()) {
  5329. const APValue &Filler = Val.getArrayFiller();
  5330. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  5331. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  5332. return false;
  5333. }
  5334. }
  5335. return true;
  5336. }
  5337. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  5338. CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
  5339. SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
  5340. llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
  5341. Buffer.writeObject(Offset, Bytes);
  5342. return true;
  5343. }
  5344. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  5345. APSInt AsInt(Val.bitcastToAPInt());
  5346. return visitInt(AsInt, Ty, Offset);
  5347. }
  5348. public:
  5349. static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
  5350. const CastExpr *BCE) {
  5351. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  5352. APValueToBufferConverter Converter(Info, DstSize, BCE);
  5353. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  5354. return None;
  5355. return Converter.Buffer;
  5356. }
  5357. };
  5358. /// Write an BitCastBuffer into an APValue.
  5359. class BufferToAPValueConverter {
  5360. EvalInfo &Info;
  5361. const BitCastBuffer &Buffer;
  5362. const CastExpr *BCE;
  5363. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  5364. const CastExpr *BCE)
  5365. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  5366. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  5367. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  5368. // Ideally this will be unreachable.
  5369. llvm::NoneType unsupportedType(QualType Ty) {
  5370. Info.FFDiag(BCE->getBeginLoc(),
  5371. diag::note_constexpr_bit_cast_unsupported_type)
  5372. << Ty;
  5373. return None;
  5374. }
  5375. Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  5376. const EnumType *EnumSugar = nullptr) {
  5377. if (T->isNullPtrType()) {
  5378. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  5379. return APValue((Expr *)nullptr,
  5380. /*Offset=*/CharUnits::fromQuantity(NullValue),
  5381. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  5382. }
  5383. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  5384. SmallVector<uint8_t, 8> Bytes;
  5385. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  5386. // If this is std::byte or unsigned char, then its okay to store an
  5387. // indeterminate value.
  5388. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  5389. bool IsUChar =
  5390. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  5391. T->isSpecificBuiltinType(BuiltinType::Char_U));
  5392. if (!IsStdByte && !IsUChar) {
  5393. QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
  5394. Info.FFDiag(BCE->getExprLoc(),
  5395. diag::note_constexpr_bit_cast_indet_dest)
  5396. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  5397. return None;
  5398. }
  5399. return APValue::IndeterminateValue();
  5400. }
  5401. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  5402. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  5403. if (T->isIntegralOrEnumerationType()) {
  5404. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  5405. return APValue(Val);
  5406. }
  5407. if (T->isRealFloatingType()) {
  5408. const llvm::fltSemantics &Semantics =
  5409. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  5410. return APValue(APFloat(Semantics, Val));
  5411. }
  5412. return unsupportedType(QualType(T, 0));
  5413. }
  5414. Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  5415. const RecordDecl *RD = RTy->getAsRecordDecl();
  5416. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5417. unsigned NumBases = 0;
  5418. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  5419. NumBases = CXXRD->getNumBases();
  5420. APValue ResultVal(APValue::UninitStruct(), NumBases,
  5421. std::distance(RD->field_begin(), RD->field_end()));
  5422. // Visit the base classes.
  5423. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5424. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5425. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5426. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5427. if (BaseDecl->isEmpty() ||
  5428. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  5429. continue;
  5430. Optional<APValue> SubObj = visitType(
  5431. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  5432. if (!SubObj)
  5433. return None;
  5434. ResultVal.getStructBase(I) = *SubObj;
  5435. }
  5436. }
  5437. // Visit the fields.
  5438. unsigned FieldIdx = 0;
  5439. for (FieldDecl *FD : RD->fields()) {
  5440. // FIXME: We don't currently support bit-fields. A lot of the logic for
  5441. // this is in CodeGen, so we need to factor it around.
  5442. if (FD->isBitField()) {
  5443. Info.FFDiag(BCE->getBeginLoc(),
  5444. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5445. return None;
  5446. }
  5447. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5448. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  5449. CharUnits FieldOffset =
  5450. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  5451. Offset;
  5452. QualType FieldTy = FD->getType();
  5453. Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  5454. if (!SubObj)
  5455. return None;
  5456. ResultVal.getStructField(FieldIdx) = *SubObj;
  5457. ++FieldIdx;
  5458. }
  5459. return ResultVal;
  5460. }
  5461. Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  5462. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  5463. assert(!RepresentationType.isNull() &&
  5464. "enum forward decl should be caught by Sema");
  5465. const BuiltinType *AsBuiltin =
  5466. RepresentationType.getCanonicalType()->getAs<BuiltinType>();
  5467. assert(AsBuiltin && "non-integral enum underlying type?");
  5468. // Recurse into the underlying type. Treat std::byte transparently as
  5469. // unsigned char.
  5470. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  5471. }
  5472. Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  5473. size_t Size = Ty->getSize().getLimitedValue();
  5474. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  5475. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  5476. for (size_t I = 0; I != Size; ++I) {
  5477. Optional<APValue> ElementValue =
  5478. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  5479. if (!ElementValue)
  5480. return None;
  5481. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  5482. }
  5483. return ArrayValue;
  5484. }
  5485. Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  5486. return unsupportedType(QualType(Ty, 0));
  5487. }
  5488. Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  5489. QualType Can = Ty.getCanonicalType();
  5490. switch (Can->getTypeClass()) {
  5491. #define TYPE(Class, Base) \
  5492. case Type::Class: \
  5493. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  5494. #define ABSTRACT_TYPE(Class, Base)
  5495. #define NON_CANONICAL_TYPE(Class, Base) \
  5496. case Type::Class: \
  5497. llvm_unreachable("non-canonical type should be impossible!");
  5498. #define DEPENDENT_TYPE(Class, Base) \
  5499. case Type::Class: \
  5500. llvm_unreachable( \
  5501. "dependent types aren't supported in the constant evaluator!");
  5502. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  5503. case Type::Class: \
  5504. llvm_unreachable("either dependent or not canonical!");
  5505. #include "clang/AST/TypeNodes.def"
  5506. }
  5507. llvm_unreachable("Unhandled Type::TypeClass");
  5508. }
  5509. public:
  5510. // Pull out a full value of type DstType.
  5511. static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  5512. const CastExpr *BCE) {
  5513. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  5514. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  5515. }
  5516. };
  5517. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  5518. QualType Ty, EvalInfo *Info,
  5519. const ASTContext &Ctx,
  5520. bool CheckingDest) {
  5521. Ty = Ty.getCanonicalType();
  5522. auto diag = [&](int Reason) {
  5523. if (Info)
  5524. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  5525. << CheckingDest << (Reason == 4) << Reason;
  5526. return false;
  5527. };
  5528. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  5529. if (Info)
  5530. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  5531. << NoteTy << Construct << Ty;
  5532. return false;
  5533. };
  5534. if (Ty->isUnionType())
  5535. return diag(0);
  5536. if (Ty->isPointerType())
  5537. return diag(1);
  5538. if (Ty->isMemberPointerType())
  5539. return diag(2);
  5540. if (Ty.isVolatileQualified())
  5541. return diag(3);
  5542. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  5543. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  5544. for (CXXBaseSpecifier &BS : CXXRD->bases())
  5545. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  5546. CheckingDest))
  5547. return note(1, BS.getType(), BS.getBeginLoc());
  5548. }
  5549. for (FieldDecl *FD : Record->fields()) {
  5550. if (FD->getType()->isReferenceType())
  5551. return diag(4);
  5552. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  5553. CheckingDest))
  5554. return note(0, FD->getType(), FD->getBeginLoc());
  5555. }
  5556. }
  5557. if (Ty->isArrayType() &&
  5558. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  5559. Info, Ctx, CheckingDest))
  5560. return false;
  5561. return true;
  5562. }
  5563. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  5564. const ASTContext &Ctx,
  5565. const CastExpr *BCE) {
  5566. bool DestOK = checkBitCastConstexprEligibilityType(
  5567. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  5568. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  5569. BCE->getBeginLoc(),
  5570. BCE->getSubExpr()->getType(), Info, Ctx, false);
  5571. return SourceOK;
  5572. }
  5573. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  5574. APValue &SourceValue,
  5575. const CastExpr *BCE) {
  5576. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  5577. "no host or target supports non 8-bit chars");
  5578. assert(SourceValue.isLValue() &&
  5579. "LValueToRValueBitcast requires an lvalue operand!");
  5580. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  5581. return false;
  5582. LValue SourceLValue;
  5583. APValue SourceRValue;
  5584. SourceLValue.setFrom(Info.Ctx, SourceValue);
  5585. if (!handleLValueToRValueConversion(
  5586. Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
  5587. SourceRValue, /*WantObjectRepresentation=*/true))
  5588. return false;
  5589. // Read out SourceValue into a char buffer.
  5590. Optional<BitCastBuffer> Buffer =
  5591. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  5592. if (!Buffer)
  5593. return false;
  5594. // Write out the buffer into a new APValue.
  5595. Optional<APValue> MaybeDestValue =
  5596. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  5597. if (!MaybeDestValue)
  5598. return false;
  5599. DestValue = std::move(*MaybeDestValue);
  5600. return true;
  5601. }
  5602. template <class Derived>
  5603. class ExprEvaluatorBase
  5604. : public ConstStmtVisitor<Derived, bool> {
  5605. private:
  5606. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5607. bool DerivedSuccess(const APValue &V, const Expr *E) {
  5608. return getDerived().Success(V, E);
  5609. }
  5610. bool DerivedZeroInitialization(const Expr *E) {
  5611. return getDerived().ZeroInitialization(E);
  5612. }
  5613. // Check whether a conditional operator with a non-constant condition is a
  5614. // potential constant expression. If neither arm is a potential constant
  5615. // expression, then the conditional operator is not either.
  5616. template<typename ConditionalOperator>
  5617. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  5618. assert(Info.checkingPotentialConstantExpression());
  5619. // Speculatively evaluate both arms.
  5620. SmallVector<PartialDiagnosticAt, 8> Diag;
  5621. {
  5622. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5623. StmtVisitorTy::Visit(E->getFalseExpr());
  5624. if (Diag.empty())
  5625. return;
  5626. }
  5627. {
  5628. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5629. Diag.clear();
  5630. StmtVisitorTy::Visit(E->getTrueExpr());
  5631. if (Diag.empty())
  5632. return;
  5633. }
  5634. Error(E, diag::note_constexpr_conditional_never_const);
  5635. }
  5636. template<typename ConditionalOperator>
  5637. bool HandleConditionalOperator(const ConditionalOperator *E) {
  5638. bool BoolResult;
  5639. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  5640. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  5641. CheckPotentialConstantConditional(E);
  5642. return false;
  5643. }
  5644. if (Info.noteFailure()) {
  5645. StmtVisitorTy::Visit(E->getTrueExpr());
  5646. StmtVisitorTy::Visit(E->getFalseExpr());
  5647. }
  5648. return false;
  5649. }
  5650. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  5651. return StmtVisitorTy::Visit(EvalExpr);
  5652. }
  5653. protected:
  5654. EvalInfo &Info;
  5655. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  5656. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  5657. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  5658. return Info.CCEDiag(E, D);
  5659. }
  5660. bool ZeroInitialization(const Expr *E) { return Error(E); }
  5661. public:
  5662. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  5663. EvalInfo &getEvalInfo() { return Info; }
  5664. /// Report an evaluation error. This should only be called when an error is
  5665. /// first discovered. When propagating an error, just return false.
  5666. bool Error(const Expr *E, diag::kind D) {
  5667. Info.FFDiag(E, D);
  5668. return false;
  5669. }
  5670. bool Error(const Expr *E) {
  5671. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  5672. }
  5673. bool VisitStmt(const Stmt *) {
  5674. llvm_unreachable("Expression evaluator should not be called on stmts");
  5675. }
  5676. bool VisitExpr(const Expr *E) {
  5677. return Error(E);
  5678. }
  5679. bool VisitConstantExpr(const ConstantExpr *E)
  5680. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5681. bool VisitParenExpr(const ParenExpr *E)
  5682. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5683. bool VisitUnaryExtension(const UnaryOperator *E)
  5684. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5685. bool VisitUnaryPlus(const UnaryOperator *E)
  5686. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5687. bool VisitChooseExpr(const ChooseExpr *E)
  5688. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  5689. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  5690. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  5691. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  5692. { return StmtVisitorTy::Visit(E->getReplacement()); }
  5693. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  5694. TempVersionRAII RAII(*Info.CurrentCall);
  5695. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5696. return StmtVisitorTy::Visit(E->getExpr());
  5697. }
  5698. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  5699. TempVersionRAII RAII(*Info.CurrentCall);
  5700. // The initializer may not have been parsed yet, or might be erroneous.
  5701. if (!E->getExpr())
  5702. return Error(E);
  5703. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5704. return StmtVisitorTy::Visit(E->getExpr());
  5705. }
  5706. bool VisitExprWithCleanups(const ExprWithCleanups *E) {
  5707. FullExpressionRAII Scope(Info);
  5708. return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
  5709. }
  5710. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  5711. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  5712. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5713. }
  5714. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  5715. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  5716. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  5717. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5718. }
  5719. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  5720. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5721. }
  5722. bool VisitBinaryOperator(const BinaryOperator *E) {
  5723. switch (E->getOpcode()) {
  5724. default:
  5725. return Error(E);
  5726. case BO_Comma:
  5727. VisitIgnoredValue(E->getLHS());
  5728. return StmtVisitorTy::Visit(E->getRHS());
  5729. case BO_PtrMemD:
  5730. case BO_PtrMemI: {
  5731. LValue Obj;
  5732. if (!HandleMemberPointerAccess(Info, E, Obj))
  5733. return false;
  5734. APValue Result;
  5735. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  5736. return false;
  5737. return DerivedSuccess(Result, E);
  5738. }
  5739. }
  5740. }
  5741. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  5742. // Evaluate and cache the common expression. We treat it as a temporary,
  5743. // even though it's not quite the same thing.
  5744. LValue CommonLV;
  5745. if (!Evaluate(Info.CurrentCall->createTemporary(
  5746. E->getOpaqueValue(),
  5747. getStorageType(Info.Ctx, E->getOpaqueValue()), false,
  5748. CommonLV),
  5749. Info, E->getCommon()))
  5750. return false;
  5751. return HandleConditionalOperator(E);
  5752. }
  5753. bool VisitConditionalOperator(const ConditionalOperator *E) {
  5754. bool IsBcpCall = false;
  5755. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5756. // the result is a constant expression if it can be folded without
  5757. // side-effects. This is an important GNU extension. See GCC PR38377
  5758. // for discussion.
  5759. if (const CallExpr *CallCE =
  5760. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  5761. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  5762. IsBcpCall = true;
  5763. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  5764. // constant expression; we can't check whether it's potentially foldable.
  5765. // FIXME: We should instead treat __builtin_constant_p as non-constant if
  5766. // it would return 'false' in this mode.
  5767. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  5768. return false;
  5769. FoldConstant Fold(Info, IsBcpCall);
  5770. if (!HandleConditionalOperator(E)) {
  5771. Fold.keepDiagnostics();
  5772. return false;
  5773. }
  5774. return true;
  5775. }
  5776. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  5777. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  5778. return DerivedSuccess(*Value, E);
  5779. const Expr *Source = E->getSourceExpr();
  5780. if (!Source)
  5781. return Error(E);
  5782. if (Source == E) { // sanity checking.
  5783. assert(0 && "OpaqueValueExpr recursively refers to itself");
  5784. return Error(E);
  5785. }
  5786. return StmtVisitorTy::Visit(Source);
  5787. }
  5788. bool VisitCallExpr(const CallExpr *E) {
  5789. APValue Result;
  5790. if (!handleCallExpr(E, Result, nullptr))
  5791. return false;
  5792. return DerivedSuccess(Result, E);
  5793. }
  5794. bool handleCallExpr(const CallExpr *E, APValue &Result,
  5795. const LValue *ResultSlot) {
  5796. const Expr *Callee = E->getCallee()->IgnoreParens();
  5797. QualType CalleeType = Callee->getType();
  5798. const FunctionDecl *FD = nullptr;
  5799. LValue *This = nullptr, ThisVal;
  5800. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5801. bool HasQualifier = false;
  5802. // Extract function decl and 'this' pointer from the callee.
  5803. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  5804. const CXXMethodDecl *Member = nullptr;
  5805. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  5806. // Explicit bound member calls, such as x.f() or p->g();
  5807. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  5808. return false;
  5809. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  5810. if (!Member)
  5811. return Error(Callee);
  5812. This = &ThisVal;
  5813. HasQualifier = ME->hasQualifier();
  5814. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  5815. // Indirect bound member calls ('.*' or '->*').
  5816. Member = dyn_cast_or_null<CXXMethodDecl>(
  5817. HandleMemberPointerAccess(Info, BE, ThisVal, false));
  5818. if (!Member)
  5819. return Error(Callee);
  5820. This = &ThisVal;
  5821. } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
  5822. if (!Info.getLangOpts().CPlusPlus2a)
  5823. Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
  5824. // FIXME: If pseudo-destructor calls ever start ending the lifetime of
  5825. // their callee, we should start calling HandleDestruction here.
  5826. // For now, we just evaluate the object argument and discard it.
  5827. return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
  5828. } else
  5829. return Error(Callee);
  5830. FD = Member;
  5831. } else if (CalleeType->isFunctionPointerType()) {
  5832. LValue Call;
  5833. if (!EvaluatePointer(Callee, Call, Info))
  5834. return false;
  5835. if (!Call.getLValueOffset().isZero())
  5836. return Error(Callee);
  5837. FD = dyn_cast_or_null<FunctionDecl>(
  5838. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  5839. if (!FD)
  5840. return Error(Callee);
  5841. // Don't call function pointers which have been cast to some other type.
  5842. // Per DR (no number yet), the caller and callee can differ in noexcept.
  5843. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  5844. CalleeType->getPointeeType(), FD->getType())) {
  5845. return Error(E);
  5846. }
  5847. // Overloaded operator calls to member functions are represented as normal
  5848. // calls with '*this' as the first argument.
  5849. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  5850. if (MD && !MD->isStatic()) {
  5851. // FIXME: When selecting an implicit conversion for an overloaded
  5852. // operator delete, we sometimes try to evaluate calls to conversion
  5853. // operators without a 'this' parameter!
  5854. if (Args.empty())
  5855. return Error(E);
  5856. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  5857. return false;
  5858. This = &ThisVal;
  5859. Args = Args.slice(1);
  5860. } else if (MD && MD->isLambdaStaticInvoker()) {
  5861. // Map the static invoker for the lambda back to the call operator.
  5862. // Conveniently, we don't have to slice out the 'this' argument (as is
  5863. // being done for the non-static case), since a static member function
  5864. // doesn't have an implicit argument passed in.
  5865. const CXXRecordDecl *ClosureClass = MD->getParent();
  5866. assert(
  5867. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  5868. "Number of captures must be zero for conversion to function-ptr");
  5869. const CXXMethodDecl *LambdaCallOp =
  5870. ClosureClass->getLambdaCallOperator();
  5871. // Set 'FD', the function that will be called below, to the call
  5872. // operator. If the closure object represents a generic lambda, find
  5873. // the corresponding specialization of the call operator.
  5874. if (ClosureClass->isGenericLambda()) {
  5875. assert(MD->isFunctionTemplateSpecialization() &&
  5876. "A generic lambda's static-invoker function must be a "
  5877. "template specialization");
  5878. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  5879. FunctionTemplateDecl *CallOpTemplate =
  5880. LambdaCallOp->getDescribedFunctionTemplate();
  5881. void *InsertPos = nullptr;
  5882. FunctionDecl *CorrespondingCallOpSpecialization =
  5883. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  5884. assert(CorrespondingCallOpSpecialization &&
  5885. "We must always have a function call operator specialization "
  5886. "that corresponds to our static invoker specialization");
  5887. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  5888. } else
  5889. FD = LambdaCallOp;
  5890. }
  5891. } else
  5892. return Error(E);
  5893. SmallVector<QualType, 4> CovariantAdjustmentPath;
  5894. if (This) {
  5895. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  5896. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  5897. // Perform virtual dispatch, if necessary.
  5898. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  5899. CovariantAdjustmentPath);
  5900. if (!FD)
  5901. return false;
  5902. } else {
  5903. // Check that the 'this' pointer points to an object of the right type.
  5904. // FIXME: If this is an assignment operator call, we may need to change
  5905. // the active union member before we check this.
  5906. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
  5907. return false;
  5908. }
  5909. }
  5910. // Destructor calls are different enough that they have their own codepath.
  5911. if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
  5912. assert(This && "no 'this' pointer for destructor call");
  5913. return HandleDestruction(Info, E, *This,
  5914. Info.Ctx.getRecordType(DD->getParent()));
  5915. }
  5916. const FunctionDecl *Definition = nullptr;
  5917. Stmt *Body = FD->getBody(Definition);
  5918. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  5919. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  5920. Result, ResultSlot))
  5921. return false;
  5922. if (!CovariantAdjustmentPath.empty() &&
  5923. !HandleCovariantReturnAdjustment(Info, E, Result,
  5924. CovariantAdjustmentPath))
  5925. return false;
  5926. return true;
  5927. }
  5928. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5929. return StmtVisitorTy::Visit(E->getInitializer());
  5930. }
  5931. bool VisitInitListExpr(const InitListExpr *E) {
  5932. if (E->getNumInits() == 0)
  5933. return DerivedZeroInitialization(E);
  5934. if (E->getNumInits() == 1)
  5935. return StmtVisitorTy::Visit(E->getInit(0));
  5936. return Error(E);
  5937. }
  5938. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  5939. return DerivedZeroInitialization(E);
  5940. }
  5941. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  5942. return DerivedZeroInitialization(E);
  5943. }
  5944. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  5945. return DerivedZeroInitialization(E);
  5946. }
  5947. /// A member expression where the object is a prvalue is itself a prvalue.
  5948. bool VisitMemberExpr(const MemberExpr *E) {
  5949. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  5950. "missing temporary materialization conversion");
  5951. assert(!E->isArrow() && "missing call to bound member function?");
  5952. APValue Val;
  5953. if (!Evaluate(Val, Info, E->getBase()))
  5954. return false;
  5955. QualType BaseTy = E->getBase()->getType();
  5956. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  5957. if (!FD) return Error(E);
  5958. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  5959. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5960. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5961. // Note: there is no lvalue base here. But this case should only ever
  5962. // happen in C or in C++98, where we cannot be evaluating a constexpr
  5963. // constructor, which is the only case the base matters.
  5964. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  5965. SubobjectDesignator Designator(BaseTy);
  5966. Designator.addDeclUnchecked(FD);
  5967. APValue Result;
  5968. return extractSubobject(Info, E, Obj, Designator, Result) &&
  5969. DerivedSuccess(Result, E);
  5970. }
  5971. bool VisitCastExpr(const CastExpr *E) {
  5972. switch (E->getCastKind()) {
  5973. default:
  5974. break;
  5975. case CK_AtomicToNonAtomic: {
  5976. APValue AtomicVal;
  5977. // This does not need to be done in place even for class/array types:
  5978. // atomic-to-non-atomic conversion implies copying the object
  5979. // representation.
  5980. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  5981. return false;
  5982. return DerivedSuccess(AtomicVal, E);
  5983. }
  5984. case CK_NoOp:
  5985. case CK_UserDefinedConversion:
  5986. return StmtVisitorTy::Visit(E->getSubExpr());
  5987. case CK_LValueToRValue: {
  5988. LValue LVal;
  5989. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  5990. return false;
  5991. APValue RVal;
  5992. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5993. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5994. LVal, RVal))
  5995. return false;
  5996. return DerivedSuccess(RVal, E);
  5997. }
  5998. case CK_LValueToRValueBitCast: {
  5999. APValue DestValue, SourceValue;
  6000. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  6001. return false;
  6002. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  6003. return false;
  6004. return DerivedSuccess(DestValue, E);
  6005. }
  6006. }
  6007. return Error(E);
  6008. }
  6009. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  6010. return VisitUnaryPostIncDec(UO);
  6011. }
  6012. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  6013. return VisitUnaryPostIncDec(UO);
  6014. }
  6015. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  6016. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6017. return Error(UO);
  6018. LValue LVal;
  6019. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  6020. return false;
  6021. APValue RVal;
  6022. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  6023. UO->isIncrementOp(), &RVal))
  6024. return false;
  6025. return DerivedSuccess(RVal, UO);
  6026. }
  6027. bool VisitStmtExpr(const StmtExpr *E) {
  6028. // We will have checked the full-expressions inside the statement expression
  6029. // when they were completed, and don't need to check them again now.
  6030. if (Info.checkingForUndefinedBehavior())
  6031. return Error(E);
  6032. const CompoundStmt *CS = E->getSubStmt();
  6033. if (CS->body_empty())
  6034. return true;
  6035. BlockScopeRAII Scope(Info);
  6036. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  6037. BE = CS->body_end();
  6038. /**/; ++BI) {
  6039. if (BI + 1 == BE) {
  6040. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  6041. if (!FinalExpr) {
  6042. Info.FFDiag((*BI)->getBeginLoc(),
  6043. diag::note_constexpr_stmt_expr_unsupported);
  6044. return false;
  6045. }
  6046. return this->Visit(FinalExpr) && Scope.destroy();
  6047. }
  6048. APValue ReturnValue;
  6049. StmtResult Result = { ReturnValue, nullptr };
  6050. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  6051. if (ESR != ESR_Succeeded) {
  6052. // FIXME: If the statement-expression terminated due to 'return',
  6053. // 'break', or 'continue', it would be nice to propagate that to
  6054. // the outer statement evaluation rather than bailing out.
  6055. if (ESR != ESR_Failed)
  6056. Info.FFDiag((*BI)->getBeginLoc(),
  6057. diag::note_constexpr_stmt_expr_unsupported);
  6058. return false;
  6059. }
  6060. }
  6061. llvm_unreachable("Return from function from the loop above.");
  6062. }
  6063. /// Visit a value which is evaluated, but whose value is ignored.
  6064. void VisitIgnoredValue(const Expr *E) {
  6065. EvaluateIgnoredValue(Info, E);
  6066. }
  6067. /// Potentially visit a MemberExpr's base expression.
  6068. void VisitIgnoredBaseExpression(const Expr *E) {
  6069. // While MSVC doesn't evaluate the base expression, it does diagnose the
  6070. // presence of side-effecting behavior.
  6071. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  6072. return;
  6073. VisitIgnoredValue(E);
  6074. }
  6075. };
  6076. } // namespace
  6077. //===----------------------------------------------------------------------===//
  6078. // Common base class for lvalue and temporary evaluation.
  6079. //===----------------------------------------------------------------------===//
  6080. namespace {
  6081. template<class Derived>
  6082. class LValueExprEvaluatorBase
  6083. : public ExprEvaluatorBase<Derived> {
  6084. protected:
  6085. LValue &Result;
  6086. bool InvalidBaseOK;
  6087. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  6088. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  6089. bool Success(APValue::LValueBase B) {
  6090. Result.set(B);
  6091. return true;
  6092. }
  6093. bool evaluatePointer(const Expr *E, LValue &Result) {
  6094. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  6095. }
  6096. public:
  6097. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  6098. : ExprEvaluatorBaseTy(Info), Result(Result),
  6099. InvalidBaseOK(InvalidBaseOK) {}
  6100. bool Success(const APValue &V, const Expr *E) {
  6101. Result.setFrom(this->Info.Ctx, V);
  6102. return true;
  6103. }
  6104. bool VisitMemberExpr(const MemberExpr *E) {
  6105. // Handle non-static data members.
  6106. QualType BaseTy;
  6107. bool EvalOK;
  6108. if (E->isArrow()) {
  6109. EvalOK = evaluatePointer(E->getBase(), Result);
  6110. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  6111. } else if (E->getBase()->isRValue()) {
  6112. assert(E->getBase()->getType()->isRecordType());
  6113. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  6114. BaseTy = E->getBase()->getType();
  6115. } else {
  6116. EvalOK = this->Visit(E->getBase());
  6117. BaseTy = E->getBase()->getType();
  6118. }
  6119. if (!EvalOK) {
  6120. if (!InvalidBaseOK)
  6121. return false;
  6122. Result.setInvalid(E);
  6123. return true;
  6124. }
  6125. const ValueDecl *MD = E->getMemberDecl();
  6126. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  6127. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6128. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6129. (void)BaseTy;
  6130. if (!HandleLValueMember(this->Info, E, Result, FD))
  6131. return false;
  6132. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  6133. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  6134. return false;
  6135. } else
  6136. return this->Error(E);
  6137. if (MD->getType()->isReferenceType()) {
  6138. APValue RefValue;
  6139. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  6140. RefValue))
  6141. return false;
  6142. return Success(RefValue, E);
  6143. }
  6144. return true;
  6145. }
  6146. bool VisitBinaryOperator(const BinaryOperator *E) {
  6147. switch (E->getOpcode()) {
  6148. default:
  6149. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6150. case BO_PtrMemD:
  6151. case BO_PtrMemI:
  6152. return HandleMemberPointerAccess(this->Info, E, Result);
  6153. }
  6154. }
  6155. bool VisitCastExpr(const CastExpr *E) {
  6156. switch (E->getCastKind()) {
  6157. default:
  6158. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6159. case CK_DerivedToBase:
  6160. case CK_UncheckedDerivedToBase:
  6161. if (!this->Visit(E->getSubExpr()))
  6162. return false;
  6163. // Now figure out the necessary offset to add to the base LV to get from
  6164. // the derived class to the base class.
  6165. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  6166. Result);
  6167. }
  6168. }
  6169. };
  6170. }
  6171. //===----------------------------------------------------------------------===//
  6172. // LValue Evaluation
  6173. //
  6174. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  6175. // function designators (in C), decl references to void objects (in C), and
  6176. // temporaries (if building with -Wno-address-of-temporary).
  6177. //
  6178. // LValue evaluation produces values comprising a base expression of one of the
  6179. // following types:
  6180. // - Declarations
  6181. // * VarDecl
  6182. // * FunctionDecl
  6183. // - Literals
  6184. // * CompoundLiteralExpr in C (and in global scope in C++)
  6185. // * StringLiteral
  6186. // * PredefinedExpr
  6187. // * ObjCStringLiteralExpr
  6188. // * ObjCEncodeExpr
  6189. // * AddrLabelExpr
  6190. // * BlockExpr
  6191. // * CallExpr for a MakeStringConstant builtin
  6192. // - typeid(T) expressions, as TypeInfoLValues
  6193. // - Locals and temporaries
  6194. // * MaterializeTemporaryExpr
  6195. // * Any Expr, with a CallIndex indicating the function in which the temporary
  6196. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  6197. // from the AST (FIXME).
  6198. // * A MaterializeTemporaryExpr that has static storage duration, with no
  6199. // CallIndex, for a lifetime-extended temporary.
  6200. // plus an offset in bytes.
  6201. //===----------------------------------------------------------------------===//
  6202. namespace {
  6203. class LValueExprEvaluator
  6204. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  6205. public:
  6206. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  6207. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  6208. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  6209. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  6210. bool VisitDeclRefExpr(const DeclRefExpr *E);
  6211. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  6212. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  6213. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  6214. bool VisitMemberExpr(const MemberExpr *E);
  6215. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  6216. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  6217. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  6218. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  6219. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  6220. bool VisitUnaryDeref(const UnaryOperator *E);
  6221. bool VisitUnaryReal(const UnaryOperator *E);
  6222. bool VisitUnaryImag(const UnaryOperator *E);
  6223. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  6224. return VisitUnaryPreIncDec(UO);
  6225. }
  6226. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  6227. return VisitUnaryPreIncDec(UO);
  6228. }
  6229. bool VisitBinAssign(const BinaryOperator *BO);
  6230. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  6231. bool VisitCastExpr(const CastExpr *E) {
  6232. switch (E->getCastKind()) {
  6233. default:
  6234. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6235. case CK_LValueBitCast:
  6236. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6237. if (!Visit(E->getSubExpr()))
  6238. return false;
  6239. Result.Designator.setInvalid();
  6240. return true;
  6241. case CK_BaseToDerived:
  6242. if (!Visit(E->getSubExpr()))
  6243. return false;
  6244. return HandleBaseToDerivedCast(Info, E, Result);
  6245. case CK_Dynamic:
  6246. if (!Visit(E->getSubExpr()))
  6247. return false;
  6248. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6249. }
  6250. }
  6251. };
  6252. } // end anonymous namespace
  6253. /// Evaluate an expression as an lvalue. This can be legitimately called on
  6254. /// expressions which are not glvalues, in three cases:
  6255. /// * function designators in C, and
  6256. /// * "extern void" objects
  6257. /// * @selector() expressions in Objective-C
  6258. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  6259. bool InvalidBaseOK) {
  6260. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  6261. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  6262. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6263. }
  6264. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  6265. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  6266. return Success(FD);
  6267. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  6268. return VisitVarDecl(E, VD);
  6269. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  6270. return Visit(BD->getBinding());
  6271. return Error(E);
  6272. }
  6273. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  6274. // If we are within a lambda's call operator, check whether the 'VD' referred
  6275. // to within 'E' actually represents a lambda-capture that maps to a
  6276. // data-member/field within the closure object, and if so, evaluate to the
  6277. // field or what the field refers to.
  6278. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  6279. isa<DeclRefExpr>(E) &&
  6280. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  6281. // We don't always have a complete capture-map when checking or inferring if
  6282. // the function call operator meets the requirements of a constexpr function
  6283. // - but we don't need to evaluate the captures to determine constexprness
  6284. // (dcl.constexpr C++17).
  6285. if (Info.checkingPotentialConstantExpression())
  6286. return false;
  6287. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  6288. // Start with 'Result' referring to the complete closure object...
  6289. Result = *Info.CurrentCall->This;
  6290. // ... then update it to refer to the field of the closure object
  6291. // that represents the capture.
  6292. if (!HandleLValueMember(Info, E, Result, FD))
  6293. return false;
  6294. // And if the field is of reference type, update 'Result' to refer to what
  6295. // the field refers to.
  6296. if (FD->getType()->isReferenceType()) {
  6297. APValue RVal;
  6298. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  6299. RVal))
  6300. return false;
  6301. Result.setFrom(Info.Ctx, RVal);
  6302. }
  6303. return true;
  6304. }
  6305. }
  6306. CallStackFrame *Frame = nullptr;
  6307. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  6308. // Only if a local variable was declared in the function currently being
  6309. // evaluated, do we expect to be able to find its value in the current
  6310. // frame. (Otherwise it was likely declared in an enclosing context and
  6311. // could either have a valid evaluatable value (for e.g. a constexpr
  6312. // variable) or be ill-formed (and trigger an appropriate evaluation
  6313. // diagnostic)).
  6314. if (Info.CurrentCall->Callee &&
  6315. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  6316. Frame = Info.CurrentCall;
  6317. }
  6318. }
  6319. if (!VD->getType()->isReferenceType()) {
  6320. if (Frame) {
  6321. Result.set({VD, Frame->Index,
  6322. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  6323. return true;
  6324. }
  6325. return Success(VD);
  6326. }
  6327. APValue *V;
  6328. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  6329. return false;
  6330. if (!V->hasValue()) {
  6331. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  6332. // adjust the diagnostic to say that.
  6333. if (!Info.checkingPotentialConstantExpression())
  6334. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  6335. return false;
  6336. }
  6337. return Success(*V, E);
  6338. }
  6339. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  6340. const MaterializeTemporaryExpr *E) {
  6341. // Walk through the expression to find the materialized temporary itself.
  6342. SmallVector<const Expr *, 2> CommaLHSs;
  6343. SmallVector<SubobjectAdjustment, 2> Adjustments;
  6344. const Expr *Inner = E->GetTemporaryExpr()->
  6345. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  6346. // If we passed any comma operators, evaluate their LHSs.
  6347. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  6348. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  6349. return false;
  6350. // A materialized temporary with static storage duration can appear within the
  6351. // result of a constant expression evaluation, so we need to preserve its
  6352. // value for use outside this evaluation.
  6353. APValue *Value;
  6354. if (E->getStorageDuration() == SD_Static) {
  6355. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  6356. *Value = APValue();
  6357. Result.set(E);
  6358. } else {
  6359. Value = &Info.CurrentCall->createTemporary(
  6360. E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
  6361. }
  6362. QualType Type = Inner->getType();
  6363. // Materialize the temporary itself.
  6364. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  6365. (E->getStorageDuration() == SD_Static &&
  6366. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  6367. *Value = APValue();
  6368. return false;
  6369. }
  6370. // Adjust our lvalue to refer to the desired subobject.
  6371. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  6372. --I;
  6373. switch (Adjustments[I].Kind) {
  6374. case SubobjectAdjustment::DerivedToBaseAdjustment:
  6375. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  6376. Type, Result))
  6377. return false;
  6378. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  6379. break;
  6380. case SubobjectAdjustment::FieldAdjustment:
  6381. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  6382. return false;
  6383. Type = Adjustments[I].Field->getType();
  6384. break;
  6385. case SubobjectAdjustment::MemberPointerAdjustment:
  6386. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  6387. Adjustments[I].Ptr.RHS))
  6388. return false;
  6389. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  6390. break;
  6391. }
  6392. }
  6393. return true;
  6394. }
  6395. bool
  6396. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6397. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  6398. "lvalue compound literal in c++?");
  6399. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  6400. // only see this when folding in C, so there's no standard to follow here.
  6401. return Success(E);
  6402. }
  6403. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  6404. TypeInfoLValue TypeInfo;
  6405. if (!E->isPotentiallyEvaluated()) {
  6406. if (E->isTypeOperand())
  6407. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  6408. else
  6409. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  6410. } else {
  6411. if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
  6412. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  6413. << E->getExprOperand()->getType()
  6414. << E->getExprOperand()->getSourceRange();
  6415. }
  6416. if (!Visit(E->getExprOperand()))
  6417. return false;
  6418. Optional<DynamicType> DynType =
  6419. ComputeDynamicType(Info, E, Result, AK_TypeId);
  6420. if (!DynType)
  6421. return false;
  6422. TypeInfo =
  6423. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  6424. }
  6425. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  6426. }
  6427. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  6428. return Success(E);
  6429. }
  6430. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  6431. // Handle static data members.
  6432. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  6433. VisitIgnoredBaseExpression(E->getBase());
  6434. return VisitVarDecl(E, VD);
  6435. }
  6436. // Handle static member functions.
  6437. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  6438. if (MD->isStatic()) {
  6439. VisitIgnoredBaseExpression(E->getBase());
  6440. return Success(MD);
  6441. }
  6442. }
  6443. // Handle non-static data members.
  6444. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  6445. }
  6446. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  6447. // FIXME: Deal with vectors as array subscript bases.
  6448. if (E->getBase()->getType()->isVectorType())
  6449. return Error(E);
  6450. bool Success = true;
  6451. if (!evaluatePointer(E->getBase(), Result)) {
  6452. if (!Info.noteFailure())
  6453. return false;
  6454. Success = false;
  6455. }
  6456. APSInt Index;
  6457. if (!EvaluateInteger(E->getIdx(), Index, Info))
  6458. return false;
  6459. return Success &&
  6460. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  6461. }
  6462. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  6463. return evaluatePointer(E->getSubExpr(), Result);
  6464. }
  6465. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6466. if (!Visit(E->getSubExpr()))
  6467. return false;
  6468. // __real is a no-op on scalar lvalues.
  6469. if (E->getSubExpr()->getType()->isAnyComplexType())
  6470. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  6471. return true;
  6472. }
  6473. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6474. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  6475. "lvalue __imag__ on scalar?");
  6476. if (!Visit(E->getSubExpr()))
  6477. return false;
  6478. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  6479. return true;
  6480. }
  6481. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  6482. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6483. return Error(UO);
  6484. if (!this->Visit(UO->getSubExpr()))
  6485. return false;
  6486. return handleIncDec(
  6487. this->Info, UO, Result, UO->getSubExpr()->getType(),
  6488. UO->isIncrementOp(), nullptr);
  6489. }
  6490. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  6491. const CompoundAssignOperator *CAO) {
  6492. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6493. return Error(CAO);
  6494. APValue RHS;
  6495. // The overall lvalue result is the result of evaluating the LHS.
  6496. if (!this->Visit(CAO->getLHS())) {
  6497. if (Info.noteFailure())
  6498. Evaluate(RHS, this->Info, CAO->getRHS());
  6499. return false;
  6500. }
  6501. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  6502. return false;
  6503. return handleCompoundAssignment(
  6504. this->Info, CAO,
  6505. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  6506. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  6507. }
  6508. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  6509. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6510. return Error(E);
  6511. APValue NewVal;
  6512. if (!this->Visit(E->getLHS())) {
  6513. if (Info.noteFailure())
  6514. Evaluate(NewVal, this->Info, E->getRHS());
  6515. return false;
  6516. }
  6517. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  6518. return false;
  6519. if (Info.getLangOpts().CPlusPlus2a &&
  6520. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  6521. return false;
  6522. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  6523. NewVal);
  6524. }
  6525. //===----------------------------------------------------------------------===//
  6526. // Pointer Evaluation
  6527. //===----------------------------------------------------------------------===//
  6528. /// Attempts to compute the number of bytes available at the pointer
  6529. /// returned by a function with the alloc_size attribute. Returns true if we
  6530. /// were successful. Places an unsigned number into `Result`.
  6531. ///
  6532. /// This expects the given CallExpr to be a call to a function with an
  6533. /// alloc_size attribute.
  6534. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6535. const CallExpr *Call,
  6536. llvm::APInt &Result) {
  6537. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  6538. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  6539. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  6540. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  6541. if (Call->getNumArgs() <= SizeArgNo)
  6542. return false;
  6543. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  6544. Expr::EvalResult ExprResult;
  6545. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  6546. return false;
  6547. Into = ExprResult.Val.getInt();
  6548. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  6549. return false;
  6550. Into = Into.zextOrSelf(BitsInSizeT);
  6551. return true;
  6552. };
  6553. APSInt SizeOfElem;
  6554. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  6555. return false;
  6556. if (!AllocSize->getNumElemsParam().isValid()) {
  6557. Result = std::move(SizeOfElem);
  6558. return true;
  6559. }
  6560. APSInt NumberOfElems;
  6561. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  6562. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  6563. return false;
  6564. bool Overflow;
  6565. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  6566. if (Overflow)
  6567. return false;
  6568. Result = std::move(BytesAvailable);
  6569. return true;
  6570. }
  6571. /// Convenience function. LVal's base must be a call to an alloc_size
  6572. /// function.
  6573. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6574. const LValue &LVal,
  6575. llvm::APInt &Result) {
  6576. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6577. "Can't get the size of a non alloc_size function");
  6578. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  6579. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  6580. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  6581. }
  6582. /// Attempts to evaluate the given LValueBase as the result of a call to
  6583. /// a function with the alloc_size attribute. If it was possible to do so, this
  6584. /// function will return true, make Result's Base point to said function call,
  6585. /// and mark Result's Base as invalid.
  6586. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  6587. LValue &Result) {
  6588. if (Base.isNull())
  6589. return false;
  6590. // Because we do no form of static analysis, we only support const variables.
  6591. //
  6592. // Additionally, we can't support parameters, nor can we support static
  6593. // variables (in the latter case, use-before-assign isn't UB; in the former,
  6594. // we have no clue what they'll be assigned to).
  6595. const auto *VD =
  6596. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  6597. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  6598. return false;
  6599. const Expr *Init = VD->getAnyInitializer();
  6600. if (!Init)
  6601. return false;
  6602. const Expr *E = Init->IgnoreParens();
  6603. if (!tryUnwrapAllocSizeCall(E))
  6604. return false;
  6605. // Store E instead of E unwrapped so that the type of the LValue's base is
  6606. // what the user wanted.
  6607. Result.setInvalid(E);
  6608. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  6609. Result.addUnsizedArray(Info, E, Pointee);
  6610. return true;
  6611. }
  6612. namespace {
  6613. class PointerExprEvaluator
  6614. : public ExprEvaluatorBase<PointerExprEvaluator> {
  6615. LValue &Result;
  6616. bool InvalidBaseOK;
  6617. bool Success(const Expr *E) {
  6618. Result.set(E);
  6619. return true;
  6620. }
  6621. bool evaluateLValue(const Expr *E, LValue &Result) {
  6622. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  6623. }
  6624. bool evaluatePointer(const Expr *E, LValue &Result) {
  6625. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  6626. }
  6627. bool visitNonBuiltinCallExpr(const CallExpr *E);
  6628. public:
  6629. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  6630. : ExprEvaluatorBaseTy(info), Result(Result),
  6631. InvalidBaseOK(InvalidBaseOK) {}
  6632. bool Success(const APValue &V, const Expr *E) {
  6633. Result.setFrom(Info.Ctx, V);
  6634. return true;
  6635. }
  6636. bool ZeroInitialization(const Expr *E) {
  6637. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  6638. Result.setNull(E->getType(), TargetVal);
  6639. return true;
  6640. }
  6641. bool VisitBinaryOperator(const BinaryOperator *E);
  6642. bool VisitCastExpr(const CastExpr* E);
  6643. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6644. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  6645. { return Success(E); }
  6646. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  6647. if (E->isExpressibleAsConstantInitializer())
  6648. return Success(E);
  6649. if (Info.noteFailure())
  6650. EvaluateIgnoredValue(Info, E->getSubExpr());
  6651. return Error(E);
  6652. }
  6653. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  6654. { return Success(E); }
  6655. bool VisitCallExpr(const CallExpr *E);
  6656. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6657. bool VisitBlockExpr(const BlockExpr *E) {
  6658. if (!E->getBlockDecl()->hasCaptures())
  6659. return Success(E);
  6660. return Error(E);
  6661. }
  6662. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  6663. // Can't look at 'this' when checking a potential constant expression.
  6664. if (Info.checkingPotentialConstantExpression())
  6665. return false;
  6666. if (!Info.CurrentCall->This) {
  6667. if (Info.getLangOpts().CPlusPlus11)
  6668. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  6669. else
  6670. Info.FFDiag(E);
  6671. return false;
  6672. }
  6673. Result = *Info.CurrentCall->This;
  6674. // If we are inside a lambda's call operator, the 'this' expression refers
  6675. // to the enclosing '*this' object (either by value or reference) which is
  6676. // either copied into the closure object's field that represents the '*this'
  6677. // or refers to '*this'.
  6678. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  6679. // Update 'Result' to refer to the data member/field of the closure object
  6680. // that represents the '*this' capture.
  6681. if (!HandleLValueMember(Info, E, Result,
  6682. Info.CurrentCall->LambdaThisCaptureField))
  6683. return false;
  6684. // If we captured '*this' by reference, replace the field with its referent.
  6685. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  6686. ->isPointerType()) {
  6687. APValue RVal;
  6688. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  6689. RVal))
  6690. return false;
  6691. Result.setFrom(Info.Ctx, RVal);
  6692. }
  6693. }
  6694. return true;
  6695. }
  6696. bool VisitCXXNewExpr(const CXXNewExpr *E);
  6697. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  6698. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  6699. APValue LValResult = E->EvaluateInContext(
  6700. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  6701. Result.setFrom(Info.Ctx, LValResult);
  6702. return true;
  6703. }
  6704. // FIXME: Missing: @protocol, @selector
  6705. };
  6706. } // end anonymous namespace
  6707. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  6708. bool InvalidBaseOK) {
  6709. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6710. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6711. }
  6712. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6713. if (E->getOpcode() != BO_Add &&
  6714. E->getOpcode() != BO_Sub)
  6715. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6716. const Expr *PExp = E->getLHS();
  6717. const Expr *IExp = E->getRHS();
  6718. if (IExp->getType()->isPointerType())
  6719. std::swap(PExp, IExp);
  6720. bool EvalPtrOK = evaluatePointer(PExp, Result);
  6721. if (!EvalPtrOK && !Info.noteFailure())
  6722. return false;
  6723. llvm::APSInt Offset;
  6724. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  6725. return false;
  6726. if (E->getOpcode() == BO_Sub)
  6727. negateAsSigned(Offset);
  6728. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  6729. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  6730. }
  6731. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6732. return evaluateLValue(E->getSubExpr(), Result);
  6733. }
  6734. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6735. const Expr *SubExpr = E->getSubExpr();
  6736. switch (E->getCastKind()) {
  6737. default:
  6738. break;
  6739. case CK_BitCast:
  6740. case CK_CPointerToObjCPointerCast:
  6741. case CK_BlockPointerToObjCPointerCast:
  6742. case CK_AnyPointerToBlockPointerCast:
  6743. case CK_AddressSpaceConversion:
  6744. if (!Visit(SubExpr))
  6745. return false;
  6746. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  6747. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  6748. // also static_casts, but we disallow them as a resolution to DR1312.
  6749. if (!E->getType()->isVoidPointerType()) {
  6750. Result.Designator.setInvalid();
  6751. if (SubExpr->getType()->isVoidPointerType())
  6752. CCEDiag(E, diag::note_constexpr_invalid_cast)
  6753. << 3 << SubExpr->getType();
  6754. else
  6755. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6756. }
  6757. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  6758. ZeroInitialization(E);
  6759. return true;
  6760. case CK_DerivedToBase:
  6761. case CK_UncheckedDerivedToBase:
  6762. if (!evaluatePointer(E->getSubExpr(), Result))
  6763. return false;
  6764. if (!Result.Base && Result.Offset.isZero())
  6765. return true;
  6766. // Now figure out the necessary offset to add to the base LV to get from
  6767. // the derived class to the base class.
  6768. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  6769. castAs<PointerType>()->getPointeeType(),
  6770. Result);
  6771. case CK_BaseToDerived:
  6772. if (!Visit(E->getSubExpr()))
  6773. return false;
  6774. if (!Result.Base && Result.Offset.isZero())
  6775. return true;
  6776. return HandleBaseToDerivedCast(Info, E, Result);
  6777. case CK_Dynamic:
  6778. if (!Visit(E->getSubExpr()))
  6779. return false;
  6780. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6781. case CK_NullToPointer:
  6782. VisitIgnoredValue(E->getSubExpr());
  6783. return ZeroInitialization(E);
  6784. case CK_IntegralToPointer: {
  6785. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6786. APValue Value;
  6787. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  6788. break;
  6789. if (Value.isInt()) {
  6790. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  6791. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  6792. Result.Base = (Expr*)nullptr;
  6793. Result.InvalidBase = false;
  6794. Result.Offset = CharUnits::fromQuantity(N);
  6795. Result.Designator.setInvalid();
  6796. Result.IsNullPtr = false;
  6797. return true;
  6798. } else {
  6799. // Cast is of an lvalue, no need to change value.
  6800. Result.setFrom(Info.Ctx, Value);
  6801. return true;
  6802. }
  6803. }
  6804. case CK_ArrayToPointerDecay: {
  6805. if (SubExpr->isGLValue()) {
  6806. if (!evaluateLValue(SubExpr, Result))
  6807. return false;
  6808. } else {
  6809. APValue &Value = Info.CurrentCall->createTemporary(
  6810. SubExpr, SubExpr->getType(), false, Result);
  6811. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  6812. return false;
  6813. }
  6814. // The result is a pointer to the first element of the array.
  6815. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  6816. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  6817. Result.addArray(Info, E, CAT);
  6818. else
  6819. Result.addUnsizedArray(Info, E, AT->getElementType());
  6820. return true;
  6821. }
  6822. case CK_FunctionToPointerDecay:
  6823. return evaluateLValue(SubExpr, Result);
  6824. case CK_LValueToRValue: {
  6825. LValue LVal;
  6826. if (!evaluateLValue(E->getSubExpr(), LVal))
  6827. return false;
  6828. APValue RVal;
  6829. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6830. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6831. LVal, RVal))
  6832. return InvalidBaseOK &&
  6833. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  6834. return Success(RVal, E);
  6835. }
  6836. }
  6837. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6838. }
  6839. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  6840. UnaryExprOrTypeTrait ExprKind) {
  6841. // C++ [expr.alignof]p3:
  6842. // When alignof is applied to a reference type, the result is the
  6843. // alignment of the referenced type.
  6844. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  6845. T = Ref->getPointeeType();
  6846. if (T.getQualifiers().hasUnaligned())
  6847. return CharUnits::One();
  6848. const bool AlignOfReturnsPreferred =
  6849. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  6850. // __alignof is defined to return the preferred alignment.
  6851. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  6852. // as well.
  6853. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  6854. return Info.Ctx.toCharUnitsFromBits(
  6855. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  6856. // alignof and _Alignof are defined to return the ABI alignment.
  6857. else if (ExprKind == UETT_AlignOf)
  6858. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  6859. else
  6860. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  6861. }
  6862. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  6863. UnaryExprOrTypeTrait ExprKind) {
  6864. E = E->IgnoreParens();
  6865. // The kinds of expressions that we have special-case logic here for
  6866. // should be kept up to date with the special checks for those
  6867. // expressions in Sema.
  6868. // alignof decl is always accepted, even if it doesn't make sense: we default
  6869. // to 1 in those cases.
  6870. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6871. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  6872. /*RefAsPointee*/true);
  6873. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  6874. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  6875. /*RefAsPointee*/true);
  6876. return GetAlignOfType(Info, E->getType(), ExprKind);
  6877. }
  6878. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  6879. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  6880. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  6881. return true;
  6882. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  6883. return false;
  6884. Result.setInvalid(E);
  6885. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  6886. Result.addUnsizedArray(Info, E, PointeeTy);
  6887. return true;
  6888. }
  6889. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6890. if (IsStringLiteralCall(E))
  6891. return Success(E);
  6892. if (unsigned BuiltinOp = E->getBuiltinCallee())
  6893. return VisitBuiltinCallExpr(E, BuiltinOp);
  6894. return visitNonBuiltinCallExpr(E);
  6895. }
  6896. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  6897. unsigned BuiltinOp) {
  6898. switch (BuiltinOp) {
  6899. case Builtin::BI__builtin_addressof:
  6900. return evaluateLValue(E->getArg(0), Result);
  6901. case Builtin::BI__builtin_assume_aligned: {
  6902. // We need to be very careful here because: if the pointer does not have the
  6903. // asserted alignment, then the behavior is undefined, and undefined
  6904. // behavior is non-constant.
  6905. if (!evaluatePointer(E->getArg(0), Result))
  6906. return false;
  6907. LValue OffsetResult(Result);
  6908. APSInt Alignment;
  6909. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  6910. return false;
  6911. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  6912. if (E->getNumArgs() > 2) {
  6913. APSInt Offset;
  6914. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  6915. return false;
  6916. int64_t AdditionalOffset = -Offset.getZExtValue();
  6917. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  6918. }
  6919. // If there is a base object, then it must have the correct alignment.
  6920. if (OffsetResult.Base) {
  6921. CharUnits BaseAlignment;
  6922. if (const ValueDecl *VD =
  6923. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  6924. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  6925. } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
  6926. BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
  6927. } else {
  6928. BaseAlignment = GetAlignOfType(
  6929. Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
  6930. }
  6931. if (BaseAlignment < Align) {
  6932. Result.Designator.setInvalid();
  6933. // FIXME: Add support to Diagnostic for long / long long.
  6934. CCEDiag(E->getArg(0),
  6935. diag::note_constexpr_baa_insufficient_alignment) << 0
  6936. << (unsigned)BaseAlignment.getQuantity()
  6937. << (unsigned)Align.getQuantity();
  6938. return false;
  6939. }
  6940. }
  6941. // The offset must also have the correct alignment.
  6942. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  6943. Result.Designator.setInvalid();
  6944. (OffsetResult.Base
  6945. ? CCEDiag(E->getArg(0),
  6946. diag::note_constexpr_baa_insufficient_alignment) << 1
  6947. : CCEDiag(E->getArg(0),
  6948. diag::note_constexpr_baa_value_insufficient_alignment))
  6949. << (int)OffsetResult.Offset.getQuantity()
  6950. << (unsigned)Align.getQuantity();
  6951. return false;
  6952. }
  6953. return true;
  6954. }
  6955. case Builtin::BI__builtin_launder:
  6956. return evaluatePointer(E->getArg(0), Result);
  6957. case Builtin::BIstrchr:
  6958. case Builtin::BIwcschr:
  6959. case Builtin::BImemchr:
  6960. case Builtin::BIwmemchr:
  6961. if (Info.getLangOpts().CPlusPlus11)
  6962. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6963. << /*isConstexpr*/0 << /*isConstructor*/0
  6964. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6965. else
  6966. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6967. LLVM_FALLTHROUGH;
  6968. case Builtin::BI__builtin_strchr:
  6969. case Builtin::BI__builtin_wcschr:
  6970. case Builtin::BI__builtin_memchr:
  6971. case Builtin::BI__builtin_char_memchr:
  6972. case Builtin::BI__builtin_wmemchr: {
  6973. if (!Visit(E->getArg(0)))
  6974. return false;
  6975. APSInt Desired;
  6976. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  6977. return false;
  6978. uint64_t MaxLength = uint64_t(-1);
  6979. if (BuiltinOp != Builtin::BIstrchr &&
  6980. BuiltinOp != Builtin::BIwcschr &&
  6981. BuiltinOp != Builtin::BI__builtin_strchr &&
  6982. BuiltinOp != Builtin::BI__builtin_wcschr) {
  6983. APSInt N;
  6984. if (!EvaluateInteger(E->getArg(2), N, Info))
  6985. return false;
  6986. MaxLength = N.getExtValue();
  6987. }
  6988. // We cannot find the value if there are no candidates to match against.
  6989. if (MaxLength == 0u)
  6990. return ZeroInitialization(E);
  6991. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  6992. Result.Designator.Invalid)
  6993. return false;
  6994. QualType CharTy = Result.Designator.getType(Info.Ctx);
  6995. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  6996. BuiltinOp == Builtin::BI__builtin_memchr;
  6997. assert(IsRawByte ||
  6998. Info.Ctx.hasSameUnqualifiedType(
  6999. CharTy, E->getArg(0)->getType()->getPointeeType()));
  7000. // Pointers to const void may point to objects of incomplete type.
  7001. if (IsRawByte && CharTy->isIncompleteType()) {
  7002. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  7003. return false;
  7004. }
  7005. // Give up on byte-oriented matching against multibyte elements.
  7006. // FIXME: We can compare the bytes in the correct order.
  7007. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  7008. return false;
  7009. // Figure out what value we're actually looking for (after converting to
  7010. // the corresponding unsigned type if necessary).
  7011. uint64_t DesiredVal;
  7012. bool StopAtNull = false;
  7013. switch (BuiltinOp) {
  7014. case Builtin::BIstrchr:
  7015. case Builtin::BI__builtin_strchr:
  7016. // strchr compares directly to the passed integer, and therefore
  7017. // always fails if given an int that is not a char.
  7018. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  7019. E->getArg(1)->getType(),
  7020. Desired),
  7021. Desired))
  7022. return ZeroInitialization(E);
  7023. StopAtNull = true;
  7024. LLVM_FALLTHROUGH;
  7025. case Builtin::BImemchr:
  7026. case Builtin::BI__builtin_memchr:
  7027. case Builtin::BI__builtin_char_memchr:
  7028. // memchr compares by converting both sides to unsigned char. That's also
  7029. // correct for strchr if we get this far (to cope with plain char being
  7030. // unsigned in the strchr case).
  7031. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  7032. break;
  7033. case Builtin::BIwcschr:
  7034. case Builtin::BI__builtin_wcschr:
  7035. StopAtNull = true;
  7036. LLVM_FALLTHROUGH;
  7037. case Builtin::BIwmemchr:
  7038. case Builtin::BI__builtin_wmemchr:
  7039. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  7040. DesiredVal = Desired.getZExtValue();
  7041. break;
  7042. }
  7043. for (; MaxLength; --MaxLength) {
  7044. APValue Char;
  7045. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  7046. !Char.isInt())
  7047. return false;
  7048. if (Char.getInt().getZExtValue() == DesiredVal)
  7049. return true;
  7050. if (StopAtNull && !Char.getInt())
  7051. break;
  7052. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  7053. return false;
  7054. }
  7055. // Not found: return nullptr.
  7056. return ZeroInitialization(E);
  7057. }
  7058. case Builtin::BImemcpy:
  7059. case Builtin::BImemmove:
  7060. case Builtin::BIwmemcpy:
  7061. case Builtin::BIwmemmove:
  7062. if (Info.getLangOpts().CPlusPlus11)
  7063. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7064. << /*isConstexpr*/0 << /*isConstructor*/0
  7065. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7066. else
  7067. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7068. LLVM_FALLTHROUGH;
  7069. case Builtin::BI__builtin_memcpy:
  7070. case Builtin::BI__builtin_memmove:
  7071. case Builtin::BI__builtin_wmemcpy:
  7072. case Builtin::BI__builtin_wmemmove: {
  7073. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  7074. BuiltinOp == Builtin::BIwmemmove ||
  7075. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  7076. BuiltinOp == Builtin::BI__builtin_wmemmove;
  7077. bool Move = BuiltinOp == Builtin::BImemmove ||
  7078. BuiltinOp == Builtin::BIwmemmove ||
  7079. BuiltinOp == Builtin::BI__builtin_memmove ||
  7080. BuiltinOp == Builtin::BI__builtin_wmemmove;
  7081. // The result of mem* is the first argument.
  7082. if (!Visit(E->getArg(0)))
  7083. return false;
  7084. LValue Dest = Result;
  7085. LValue Src;
  7086. if (!EvaluatePointer(E->getArg(1), Src, Info))
  7087. return false;
  7088. APSInt N;
  7089. if (!EvaluateInteger(E->getArg(2), N, Info))
  7090. return false;
  7091. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  7092. // If the size is zero, we treat this as always being a valid no-op.
  7093. // (Even if one of the src and dest pointers is null.)
  7094. if (!N)
  7095. return true;
  7096. // Otherwise, if either of the operands is null, we can't proceed. Don't
  7097. // try to determine the type of the copied objects, because there aren't
  7098. // any.
  7099. if (!Src.Base || !Dest.Base) {
  7100. APValue Val;
  7101. (!Src.Base ? Src : Dest).moveInto(Val);
  7102. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  7103. << Move << WChar << !!Src.Base
  7104. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  7105. return false;
  7106. }
  7107. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  7108. return false;
  7109. // We require that Src and Dest are both pointers to arrays of
  7110. // trivially-copyable type. (For the wide version, the designator will be
  7111. // invalid if the designated object is not a wchar_t.)
  7112. QualType T = Dest.Designator.getType(Info.Ctx);
  7113. QualType SrcT = Src.Designator.getType(Info.Ctx);
  7114. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  7115. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  7116. return false;
  7117. }
  7118. if (T->isIncompleteType()) {
  7119. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  7120. return false;
  7121. }
  7122. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  7123. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  7124. return false;
  7125. }
  7126. // Figure out how many T's we're copying.
  7127. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  7128. if (!WChar) {
  7129. uint64_t Remainder;
  7130. llvm::APInt OrigN = N;
  7131. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  7132. if (Remainder) {
  7133. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7134. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  7135. << (unsigned)TSize;
  7136. return false;
  7137. }
  7138. }
  7139. // Check that the copying will remain within the arrays, just so that we
  7140. // can give a more meaningful diagnostic. This implicitly also checks that
  7141. // N fits into 64 bits.
  7142. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  7143. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  7144. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  7145. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7146. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  7147. << N.toString(10, /*Signed*/false);
  7148. return false;
  7149. }
  7150. uint64_t NElems = N.getZExtValue();
  7151. uint64_t NBytes = NElems * TSize;
  7152. // Check for overlap.
  7153. int Direction = 1;
  7154. if (HasSameBase(Src, Dest)) {
  7155. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  7156. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  7157. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  7158. // Dest is inside the source region.
  7159. if (!Move) {
  7160. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7161. return false;
  7162. }
  7163. // For memmove and friends, copy backwards.
  7164. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  7165. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  7166. return false;
  7167. Direction = -1;
  7168. } else if (!Move && SrcOffset >= DestOffset &&
  7169. SrcOffset - DestOffset < NBytes) {
  7170. // Src is inside the destination region for memcpy: invalid.
  7171. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7172. return false;
  7173. }
  7174. }
  7175. while (true) {
  7176. APValue Val;
  7177. // FIXME: Set WantObjectRepresentation to true if we're copying a
  7178. // char-like type?
  7179. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  7180. !handleAssignment(Info, E, Dest, T, Val))
  7181. return false;
  7182. // Do not iterate past the last element; if we're copying backwards, that
  7183. // might take us off the start of the array.
  7184. if (--NElems == 0)
  7185. return true;
  7186. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  7187. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  7188. return false;
  7189. }
  7190. }
  7191. default:
  7192. return visitNonBuiltinCallExpr(E);
  7193. }
  7194. }
  7195. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  7196. APValue &Result, const InitListExpr *ILE,
  7197. QualType AllocType);
  7198. bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
  7199. if (!Info.getLangOpts().CPlusPlus2a)
  7200. Info.CCEDiag(E, diag::note_constexpr_new);
  7201. // We cannot speculatively evaluate a delete expression.
  7202. if (Info.SpeculativeEvaluationDepth)
  7203. return false;
  7204. FunctionDecl *OperatorNew = E->getOperatorNew();
  7205. if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
  7206. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  7207. << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
  7208. return false;
  7209. }
  7210. bool IsNothrow = false;
  7211. if (E->getNumPlacementArgs()) {
  7212. // The only new-placement list we support is of the form (std::nothrow).
  7213. //
  7214. // FIXME: There is no restriction on this, but it's not clear that any
  7215. // other form makes any sense. We get here for cases such as:
  7216. //
  7217. // new (std::align_val_t{N}) X(int)
  7218. //
  7219. // (which should presumably be valid only if N is a multiple of
  7220. // alignof(int), and in any case can't be deallocated unless N is
  7221. // alignof(X) and X has new-extended alignment).
  7222. if (E->getNumPlacementArgs() != 1 ||
  7223. !E->getPlacementArg(0)->getType()->isNothrowT())
  7224. return Error(E, diag::note_constexpr_new_placement);
  7225. LValue Nothrow;
  7226. if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
  7227. return false;
  7228. IsNothrow = true;
  7229. }
  7230. const Expr *Init = E->getInitializer();
  7231. const InitListExpr *ResizedArrayILE = nullptr;
  7232. QualType AllocType = E->getAllocatedType();
  7233. if (Optional<const Expr*> ArraySize = E->getArraySize()) {
  7234. const Expr *Stripped = *ArraySize;
  7235. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
  7236. Stripped = ICE->getSubExpr())
  7237. if (ICE->getCastKind() != CK_NoOp &&
  7238. ICE->getCastKind() != CK_IntegralCast)
  7239. break;
  7240. llvm::APSInt ArrayBound;
  7241. if (!EvaluateInteger(Stripped, ArrayBound, Info))
  7242. return false;
  7243. // C++ [expr.new]p9:
  7244. // The expression is erroneous if:
  7245. // -- [...] its value before converting to size_t [or] applying the
  7246. // second standard conversion sequence is less than zero
  7247. if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
  7248. if (IsNothrow)
  7249. return ZeroInitialization(E);
  7250. Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
  7251. << ArrayBound << (*ArraySize)->getSourceRange();
  7252. return false;
  7253. }
  7254. // -- its value is such that the size of the allocated object would
  7255. // exceed the implementation-defined limit
  7256. if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
  7257. ArrayBound) >
  7258. ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  7259. if (IsNothrow)
  7260. return ZeroInitialization(E);
  7261. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
  7262. << ArrayBound << (*ArraySize)->getSourceRange();
  7263. return false;
  7264. }
  7265. // -- the new-initializer is a braced-init-list and the number of
  7266. // array elements for which initializers are provided [...]
  7267. // exceeds the number of elements to initialize
  7268. if (Init) {
  7269. auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
  7270. assert(CAT && "unexpected type for array initializer");
  7271. unsigned Bits =
  7272. std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
  7273. llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
  7274. llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
  7275. if (InitBound.ugt(AllocBound)) {
  7276. if (IsNothrow)
  7277. return ZeroInitialization(E);
  7278. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
  7279. << AllocBound.toString(10, /*Signed=*/false)
  7280. << InitBound.toString(10, /*Signed=*/false)
  7281. << (*ArraySize)->getSourceRange();
  7282. return false;
  7283. }
  7284. // If the sizes differ, we must have an initializer list, and we need
  7285. // special handling for this case when we initialize.
  7286. if (InitBound != AllocBound)
  7287. ResizedArrayILE = cast<InitListExpr>(Init);
  7288. }
  7289. AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound,
  7290. ArrayType::Normal, 0);
  7291. } else {
  7292. assert(!AllocType->isArrayType() &&
  7293. "array allocation with non-array new");
  7294. }
  7295. // Perform the allocation and obtain a pointer to the resulting object.
  7296. APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
  7297. if (!Val)
  7298. return false;
  7299. if (ResizedArrayILE) {
  7300. if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
  7301. AllocType))
  7302. return false;
  7303. } else if (Init) {
  7304. if (!EvaluateInPlace(*Val, Info, Result, Init))
  7305. return false;
  7306. } else {
  7307. *Val = getDefaultInitValue(AllocType);
  7308. }
  7309. // Array new returns a pointer to the first element, not a pointer to the
  7310. // array.
  7311. if (auto *AT = AllocType->getAsArrayTypeUnsafe())
  7312. Result.addArray(Info, E, cast<ConstantArrayType>(AT));
  7313. return true;
  7314. }
  7315. //===----------------------------------------------------------------------===//
  7316. // Member Pointer Evaluation
  7317. //===----------------------------------------------------------------------===//
  7318. namespace {
  7319. class MemberPointerExprEvaluator
  7320. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  7321. MemberPtr &Result;
  7322. bool Success(const ValueDecl *D) {
  7323. Result = MemberPtr(D);
  7324. return true;
  7325. }
  7326. public:
  7327. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  7328. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  7329. bool Success(const APValue &V, const Expr *E) {
  7330. Result.setFrom(V);
  7331. return true;
  7332. }
  7333. bool ZeroInitialization(const Expr *E) {
  7334. return Success((const ValueDecl*)nullptr);
  7335. }
  7336. bool VisitCastExpr(const CastExpr *E);
  7337. bool VisitUnaryAddrOf(const UnaryOperator *E);
  7338. };
  7339. } // end anonymous namespace
  7340. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  7341. EvalInfo &Info) {
  7342. assert(E->isRValue() && E->getType()->isMemberPointerType());
  7343. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  7344. }
  7345. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7346. switch (E->getCastKind()) {
  7347. default:
  7348. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7349. case CK_NullToMemberPointer:
  7350. VisitIgnoredValue(E->getSubExpr());
  7351. return ZeroInitialization(E);
  7352. case CK_BaseToDerivedMemberPointer: {
  7353. if (!Visit(E->getSubExpr()))
  7354. return false;
  7355. if (E->path_empty())
  7356. return true;
  7357. // Base-to-derived member pointer casts store the path in derived-to-base
  7358. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  7359. // the wrong end of the derived->base arc, so stagger the path by one class.
  7360. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  7361. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  7362. PathI != PathE; ++PathI) {
  7363. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7364. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  7365. if (!Result.castToDerived(Derived))
  7366. return Error(E);
  7367. }
  7368. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  7369. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  7370. return Error(E);
  7371. return true;
  7372. }
  7373. case CK_DerivedToBaseMemberPointer:
  7374. if (!Visit(E->getSubExpr()))
  7375. return false;
  7376. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7377. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7378. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7379. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7380. if (!Result.castToBase(Base))
  7381. return Error(E);
  7382. }
  7383. return true;
  7384. }
  7385. }
  7386. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  7387. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  7388. // member can be formed.
  7389. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  7390. }
  7391. //===----------------------------------------------------------------------===//
  7392. // Record Evaluation
  7393. //===----------------------------------------------------------------------===//
  7394. namespace {
  7395. class RecordExprEvaluator
  7396. : public ExprEvaluatorBase<RecordExprEvaluator> {
  7397. const LValue &This;
  7398. APValue &Result;
  7399. public:
  7400. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  7401. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  7402. bool Success(const APValue &V, const Expr *E) {
  7403. Result = V;
  7404. return true;
  7405. }
  7406. bool ZeroInitialization(const Expr *E) {
  7407. return ZeroInitialization(E, E->getType());
  7408. }
  7409. bool ZeroInitialization(const Expr *E, QualType T);
  7410. bool VisitCallExpr(const CallExpr *E) {
  7411. return handleCallExpr(E, Result, &This);
  7412. }
  7413. bool VisitCastExpr(const CastExpr *E);
  7414. bool VisitInitListExpr(const InitListExpr *E);
  7415. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7416. return VisitCXXConstructExpr(E, E->getType());
  7417. }
  7418. bool VisitLambdaExpr(const LambdaExpr *E);
  7419. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  7420. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  7421. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  7422. // Temporaries are registered when created, so we don't care about
  7423. // CXXBindTemporaryExpr.
  7424. bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
  7425. return Visit(E->getSubExpr());
  7426. }
  7427. bool VisitBinCmp(const BinaryOperator *E);
  7428. };
  7429. }
  7430. /// Perform zero-initialization on an object of non-union class type.
  7431. /// C++11 [dcl.init]p5:
  7432. /// To zero-initialize an object or reference of type T means:
  7433. /// [...]
  7434. /// -- if T is a (possibly cv-qualified) non-union class type,
  7435. /// each non-static data member and each base-class subobject is
  7436. /// zero-initialized
  7437. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  7438. const RecordDecl *RD,
  7439. const LValue &This, APValue &Result) {
  7440. assert(!RD->isUnion() && "Expected non-union class type");
  7441. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  7442. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  7443. std::distance(RD->field_begin(), RD->field_end()));
  7444. if (RD->isInvalidDecl()) return false;
  7445. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7446. if (CD) {
  7447. unsigned Index = 0;
  7448. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  7449. End = CD->bases_end(); I != End; ++I, ++Index) {
  7450. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  7451. LValue Subobject = This;
  7452. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  7453. return false;
  7454. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  7455. Result.getStructBase(Index)))
  7456. return false;
  7457. }
  7458. }
  7459. for (const auto *I : RD->fields()) {
  7460. // -- if T is a reference type, no initialization is performed.
  7461. if (I->getType()->isReferenceType())
  7462. continue;
  7463. LValue Subobject = This;
  7464. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  7465. return false;
  7466. ImplicitValueInitExpr VIE(I->getType());
  7467. if (!EvaluateInPlace(
  7468. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  7469. return false;
  7470. }
  7471. return true;
  7472. }
  7473. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  7474. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  7475. if (RD->isInvalidDecl()) return false;
  7476. if (RD->isUnion()) {
  7477. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  7478. // object's first non-static named data member is zero-initialized
  7479. RecordDecl::field_iterator I = RD->field_begin();
  7480. if (I == RD->field_end()) {
  7481. Result = APValue((const FieldDecl*)nullptr);
  7482. return true;
  7483. }
  7484. LValue Subobject = This;
  7485. if (!HandleLValueMember(Info, E, Subobject, *I))
  7486. return false;
  7487. Result = APValue(*I);
  7488. ImplicitValueInitExpr VIE(I->getType());
  7489. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  7490. }
  7491. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  7492. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  7493. return false;
  7494. }
  7495. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  7496. }
  7497. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7498. switch (E->getCastKind()) {
  7499. default:
  7500. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7501. case CK_ConstructorConversion:
  7502. return Visit(E->getSubExpr());
  7503. case CK_DerivedToBase:
  7504. case CK_UncheckedDerivedToBase: {
  7505. APValue DerivedObject;
  7506. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  7507. return false;
  7508. if (!DerivedObject.isStruct())
  7509. return Error(E->getSubExpr());
  7510. // Derived-to-base rvalue conversion: just slice off the derived part.
  7511. APValue *Value = &DerivedObject;
  7512. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  7513. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7514. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7515. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  7516. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7517. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  7518. RD = Base;
  7519. }
  7520. Result = *Value;
  7521. return true;
  7522. }
  7523. }
  7524. }
  7525. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7526. if (E->isTransparent())
  7527. return Visit(E->getInit(0));
  7528. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  7529. if (RD->isInvalidDecl()) return false;
  7530. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7531. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  7532. EvalInfo::EvaluatingConstructorRAII EvalObj(
  7533. Info,
  7534. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  7535. CXXRD && CXXRD->getNumBases());
  7536. if (RD->isUnion()) {
  7537. const FieldDecl *Field = E->getInitializedFieldInUnion();
  7538. Result = APValue(Field);
  7539. if (!Field)
  7540. return true;
  7541. // If the initializer list for a union does not contain any elements, the
  7542. // first element of the union is value-initialized.
  7543. // FIXME: The element should be initialized from an initializer list.
  7544. // Is this difference ever observable for initializer lists which
  7545. // we don't build?
  7546. ImplicitValueInitExpr VIE(Field->getType());
  7547. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  7548. LValue Subobject = This;
  7549. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  7550. return false;
  7551. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7552. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7553. isa<CXXDefaultInitExpr>(InitExpr));
  7554. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  7555. }
  7556. if (!Result.hasValue())
  7557. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  7558. std::distance(RD->field_begin(), RD->field_end()));
  7559. unsigned ElementNo = 0;
  7560. bool Success = true;
  7561. // Initialize base classes.
  7562. if (CXXRD && CXXRD->getNumBases()) {
  7563. for (const auto &Base : CXXRD->bases()) {
  7564. assert(ElementNo < E->getNumInits() && "missing init for base class");
  7565. const Expr *Init = E->getInit(ElementNo);
  7566. LValue Subobject = This;
  7567. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  7568. return false;
  7569. APValue &FieldVal = Result.getStructBase(ElementNo);
  7570. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  7571. if (!Info.noteFailure())
  7572. return false;
  7573. Success = false;
  7574. }
  7575. ++ElementNo;
  7576. }
  7577. EvalObj.finishedConstructingBases();
  7578. }
  7579. // Initialize members.
  7580. for (const auto *Field : RD->fields()) {
  7581. // Anonymous bit-fields are not considered members of the class for
  7582. // purposes of aggregate initialization.
  7583. if (Field->isUnnamedBitfield())
  7584. continue;
  7585. LValue Subobject = This;
  7586. bool HaveInit = ElementNo < E->getNumInits();
  7587. // FIXME: Diagnostics here should point to the end of the initializer
  7588. // list, not the start.
  7589. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  7590. Subobject, Field, &Layout))
  7591. return false;
  7592. // Perform an implicit value-initialization for members beyond the end of
  7593. // the initializer list.
  7594. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  7595. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  7596. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7597. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7598. isa<CXXDefaultInitExpr>(Init));
  7599. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7600. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  7601. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  7602. FieldVal, Field))) {
  7603. if (!Info.noteFailure())
  7604. return false;
  7605. Success = false;
  7606. }
  7607. }
  7608. return Success;
  7609. }
  7610. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7611. QualType T) {
  7612. // Note that E's type is not necessarily the type of our class here; we might
  7613. // be initializing an array element instead.
  7614. const CXXConstructorDecl *FD = E->getConstructor();
  7615. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  7616. bool ZeroInit = E->requiresZeroInitialization();
  7617. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  7618. // If we've already performed zero-initialization, we're already done.
  7619. if (Result.hasValue())
  7620. return true;
  7621. if (ZeroInit)
  7622. return ZeroInitialization(E, T);
  7623. Result = getDefaultInitValue(T);
  7624. return true;
  7625. }
  7626. const FunctionDecl *Definition = nullptr;
  7627. auto Body = FD->getBody(Definition);
  7628. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7629. return false;
  7630. // Avoid materializing a temporary for an elidable copy/move constructor.
  7631. if (E->isElidable() && !ZeroInit)
  7632. if (const MaterializeTemporaryExpr *ME
  7633. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  7634. return Visit(ME->GetTemporaryExpr());
  7635. if (ZeroInit && !ZeroInitialization(E, T))
  7636. return false;
  7637. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  7638. return HandleConstructorCall(E, This, Args,
  7639. cast<CXXConstructorDecl>(Definition), Info,
  7640. Result);
  7641. }
  7642. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  7643. const CXXInheritedCtorInitExpr *E) {
  7644. if (!Info.CurrentCall) {
  7645. assert(Info.checkingPotentialConstantExpression());
  7646. return false;
  7647. }
  7648. const CXXConstructorDecl *FD = E->getConstructor();
  7649. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  7650. return false;
  7651. const FunctionDecl *Definition = nullptr;
  7652. auto Body = FD->getBody(Definition);
  7653. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7654. return false;
  7655. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  7656. cast<CXXConstructorDecl>(Definition), Info,
  7657. Result);
  7658. }
  7659. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  7660. const CXXStdInitializerListExpr *E) {
  7661. const ConstantArrayType *ArrayType =
  7662. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  7663. LValue Array;
  7664. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  7665. return false;
  7666. // Get a pointer to the first element of the array.
  7667. Array.addArray(Info, E, ArrayType);
  7668. // FIXME: Perform the checks on the field types in SemaInit.
  7669. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  7670. RecordDecl::field_iterator Field = Record->field_begin();
  7671. if (Field == Record->field_end())
  7672. return Error(E);
  7673. // Start pointer.
  7674. if (!Field->getType()->isPointerType() ||
  7675. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7676. ArrayType->getElementType()))
  7677. return Error(E);
  7678. // FIXME: What if the initializer_list type has base classes, etc?
  7679. Result = APValue(APValue::UninitStruct(), 0, 2);
  7680. Array.moveInto(Result.getStructField(0));
  7681. if (++Field == Record->field_end())
  7682. return Error(E);
  7683. if (Field->getType()->isPointerType() &&
  7684. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7685. ArrayType->getElementType())) {
  7686. // End pointer.
  7687. if (!HandleLValueArrayAdjustment(Info, E, Array,
  7688. ArrayType->getElementType(),
  7689. ArrayType->getSize().getZExtValue()))
  7690. return false;
  7691. Array.moveInto(Result.getStructField(1));
  7692. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  7693. // Length.
  7694. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  7695. else
  7696. return Error(E);
  7697. if (++Field != Record->field_end())
  7698. return Error(E);
  7699. return true;
  7700. }
  7701. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  7702. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  7703. if (ClosureClass->isInvalidDecl())
  7704. return false;
  7705. const size_t NumFields =
  7706. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  7707. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  7708. E->capture_init_end()) &&
  7709. "The number of lambda capture initializers should equal the number of "
  7710. "fields within the closure type");
  7711. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  7712. // Iterate through all the lambda's closure object's fields and initialize
  7713. // them.
  7714. auto *CaptureInitIt = E->capture_init_begin();
  7715. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  7716. bool Success = true;
  7717. for (const auto *Field : ClosureClass->fields()) {
  7718. assert(CaptureInitIt != E->capture_init_end());
  7719. // Get the initializer for this field
  7720. Expr *const CurFieldInit = *CaptureInitIt++;
  7721. // If there is no initializer, either this is a VLA or an error has
  7722. // occurred.
  7723. if (!CurFieldInit)
  7724. return Error(E);
  7725. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7726. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  7727. if (!Info.keepEvaluatingAfterFailure())
  7728. return false;
  7729. Success = false;
  7730. }
  7731. ++CaptureIt;
  7732. }
  7733. return Success;
  7734. }
  7735. static bool EvaluateRecord(const Expr *E, const LValue &This,
  7736. APValue &Result, EvalInfo &Info) {
  7737. assert(E->isRValue() && E->getType()->isRecordType() &&
  7738. "can't evaluate expression as a record rvalue");
  7739. return RecordExprEvaluator(Info, This, Result).Visit(E);
  7740. }
  7741. //===----------------------------------------------------------------------===//
  7742. // Temporary Evaluation
  7743. //
  7744. // Temporaries are represented in the AST as rvalues, but generally behave like
  7745. // lvalues. The full-object of which the temporary is a subobject is implicitly
  7746. // materialized so that a reference can bind to it.
  7747. //===----------------------------------------------------------------------===//
  7748. namespace {
  7749. class TemporaryExprEvaluator
  7750. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  7751. public:
  7752. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  7753. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  7754. /// Visit an expression which constructs the value of this temporary.
  7755. bool VisitConstructExpr(const Expr *E) {
  7756. APValue &Value =
  7757. Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
  7758. return EvaluateInPlace(Value, Info, Result, E);
  7759. }
  7760. bool VisitCastExpr(const CastExpr *E) {
  7761. switch (E->getCastKind()) {
  7762. default:
  7763. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  7764. case CK_ConstructorConversion:
  7765. return VisitConstructExpr(E->getSubExpr());
  7766. }
  7767. }
  7768. bool VisitInitListExpr(const InitListExpr *E) {
  7769. return VisitConstructExpr(E);
  7770. }
  7771. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7772. return VisitConstructExpr(E);
  7773. }
  7774. bool VisitCallExpr(const CallExpr *E) {
  7775. return VisitConstructExpr(E);
  7776. }
  7777. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  7778. return VisitConstructExpr(E);
  7779. }
  7780. bool VisitLambdaExpr(const LambdaExpr *E) {
  7781. return VisitConstructExpr(E);
  7782. }
  7783. };
  7784. } // end anonymous namespace
  7785. /// Evaluate an expression of record type as a temporary.
  7786. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  7787. assert(E->isRValue() && E->getType()->isRecordType());
  7788. return TemporaryExprEvaluator(Info, Result).Visit(E);
  7789. }
  7790. //===----------------------------------------------------------------------===//
  7791. // Vector Evaluation
  7792. //===----------------------------------------------------------------------===//
  7793. namespace {
  7794. class VectorExprEvaluator
  7795. : public ExprEvaluatorBase<VectorExprEvaluator> {
  7796. APValue &Result;
  7797. public:
  7798. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  7799. : ExprEvaluatorBaseTy(info), Result(Result) {}
  7800. bool Success(ArrayRef<APValue> V, const Expr *E) {
  7801. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  7802. // FIXME: remove this APValue copy.
  7803. Result = APValue(V.data(), V.size());
  7804. return true;
  7805. }
  7806. bool Success(const APValue &V, const Expr *E) {
  7807. assert(V.isVector());
  7808. Result = V;
  7809. return true;
  7810. }
  7811. bool ZeroInitialization(const Expr *E);
  7812. bool VisitUnaryReal(const UnaryOperator *E)
  7813. { return Visit(E->getSubExpr()); }
  7814. bool VisitCastExpr(const CastExpr* E);
  7815. bool VisitInitListExpr(const InitListExpr *E);
  7816. bool VisitUnaryImag(const UnaryOperator *E);
  7817. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  7818. // binary comparisons, binary and/or/xor,
  7819. // shufflevector, ExtVectorElementExpr
  7820. };
  7821. } // end anonymous namespace
  7822. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  7823. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  7824. return VectorExprEvaluator(Info, Result).Visit(E);
  7825. }
  7826. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7827. const VectorType *VTy = E->getType()->castAs<VectorType>();
  7828. unsigned NElts = VTy->getNumElements();
  7829. const Expr *SE = E->getSubExpr();
  7830. QualType SETy = SE->getType();
  7831. switch (E->getCastKind()) {
  7832. case CK_VectorSplat: {
  7833. APValue Val = APValue();
  7834. if (SETy->isIntegerType()) {
  7835. APSInt IntResult;
  7836. if (!EvaluateInteger(SE, IntResult, Info))
  7837. return false;
  7838. Val = APValue(std::move(IntResult));
  7839. } else if (SETy->isRealFloatingType()) {
  7840. APFloat FloatResult(0.0);
  7841. if (!EvaluateFloat(SE, FloatResult, Info))
  7842. return false;
  7843. Val = APValue(std::move(FloatResult));
  7844. } else {
  7845. return Error(E);
  7846. }
  7847. // Splat and create vector APValue.
  7848. SmallVector<APValue, 4> Elts(NElts, Val);
  7849. return Success(Elts, E);
  7850. }
  7851. case CK_BitCast: {
  7852. // Evaluate the operand into an APInt we can extract from.
  7853. llvm::APInt SValInt;
  7854. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  7855. return false;
  7856. // Extract the elements
  7857. QualType EltTy = VTy->getElementType();
  7858. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  7859. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  7860. SmallVector<APValue, 4> Elts;
  7861. if (EltTy->isRealFloatingType()) {
  7862. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  7863. unsigned FloatEltSize = EltSize;
  7864. if (&Sem == &APFloat::x87DoubleExtended())
  7865. FloatEltSize = 80;
  7866. for (unsigned i = 0; i < NElts; i++) {
  7867. llvm::APInt Elt;
  7868. if (BigEndian)
  7869. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  7870. else
  7871. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  7872. Elts.push_back(APValue(APFloat(Sem, Elt)));
  7873. }
  7874. } else if (EltTy->isIntegerType()) {
  7875. for (unsigned i = 0; i < NElts; i++) {
  7876. llvm::APInt Elt;
  7877. if (BigEndian)
  7878. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  7879. else
  7880. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  7881. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  7882. }
  7883. } else {
  7884. return Error(E);
  7885. }
  7886. return Success(Elts, E);
  7887. }
  7888. default:
  7889. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7890. }
  7891. }
  7892. bool
  7893. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7894. const VectorType *VT = E->getType()->castAs<VectorType>();
  7895. unsigned NumInits = E->getNumInits();
  7896. unsigned NumElements = VT->getNumElements();
  7897. QualType EltTy = VT->getElementType();
  7898. SmallVector<APValue, 4> Elements;
  7899. // The number of initializers can be less than the number of
  7900. // vector elements. For OpenCL, this can be due to nested vector
  7901. // initialization. For GCC compatibility, missing trailing elements
  7902. // should be initialized with zeroes.
  7903. unsigned CountInits = 0, CountElts = 0;
  7904. while (CountElts < NumElements) {
  7905. // Handle nested vector initialization.
  7906. if (CountInits < NumInits
  7907. && E->getInit(CountInits)->getType()->isVectorType()) {
  7908. APValue v;
  7909. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  7910. return Error(E);
  7911. unsigned vlen = v.getVectorLength();
  7912. for (unsigned j = 0; j < vlen; j++)
  7913. Elements.push_back(v.getVectorElt(j));
  7914. CountElts += vlen;
  7915. } else if (EltTy->isIntegerType()) {
  7916. llvm::APSInt sInt(32);
  7917. if (CountInits < NumInits) {
  7918. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  7919. return false;
  7920. } else // trailing integer zero.
  7921. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  7922. Elements.push_back(APValue(sInt));
  7923. CountElts++;
  7924. } else {
  7925. llvm::APFloat f(0.0);
  7926. if (CountInits < NumInits) {
  7927. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  7928. return false;
  7929. } else // trailing float zero.
  7930. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  7931. Elements.push_back(APValue(f));
  7932. CountElts++;
  7933. }
  7934. CountInits++;
  7935. }
  7936. return Success(Elements, E);
  7937. }
  7938. bool
  7939. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  7940. const VectorType *VT = E->getType()->getAs<VectorType>();
  7941. QualType EltTy = VT->getElementType();
  7942. APValue ZeroElement;
  7943. if (EltTy->isIntegerType())
  7944. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  7945. else
  7946. ZeroElement =
  7947. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  7948. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  7949. return Success(Elements, E);
  7950. }
  7951. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7952. VisitIgnoredValue(E->getSubExpr());
  7953. return ZeroInitialization(E);
  7954. }
  7955. //===----------------------------------------------------------------------===//
  7956. // Array Evaluation
  7957. //===----------------------------------------------------------------------===//
  7958. namespace {
  7959. class ArrayExprEvaluator
  7960. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  7961. const LValue &This;
  7962. APValue &Result;
  7963. public:
  7964. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  7965. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  7966. bool Success(const APValue &V, const Expr *E) {
  7967. assert(V.isArray() && "expected array");
  7968. Result = V;
  7969. return true;
  7970. }
  7971. bool ZeroInitialization(const Expr *E) {
  7972. const ConstantArrayType *CAT =
  7973. Info.Ctx.getAsConstantArrayType(E->getType());
  7974. if (!CAT)
  7975. return Error(E);
  7976. Result = APValue(APValue::UninitArray(), 0,
  7977. CAT->getSize().getZExtValue());
  7978. if (!Result.hasArrayFiller()) return true;
  7979. // Zero-initialize all elements.
  7980. LValue Subobject = This;
  7981. Subobject.addArray(Info, E, CAT);
  7982. ImplicitValueInitExpr VIE(CAT->getElementType());
  7983. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  7984. }
  7985. bool VisitCallExpr(const CallExpr *E) {
  7986. return handleCallExpr(E, Result, &This);
  7987. }
  7988. bool VisitInitListExpr(const InitListExpr *E,
  7989. QualType AllocType = QualType());
  7990. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  7991. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  7992. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  7993. const LValue &Subobject,
  7994. APValue *Value, QualType Type);
  7995. bool VisitStringLiteral(const StringLiteral *E,
  7996. QualType AllocType = QualType()) {
  7997. expandStringLiteral(Info, E, Result, AllocType);
  7998. return true;
  7999. }
  8000. };
  8001. } // end anonymous namespace
  8002. static bool EvaluateArray(const Expr *E, const LValue &This,
  8003. APValue &Result, EvalInfo &Info) {
  8004. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  8005. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  8006. }
  8007. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  8008. APValue &Result, const InitListExpr *ILE,
  8009. QualType AllocType) {
  8010. assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
  8011. "not an array rvalue");
  8012. return ArrayExprEvaluator(Info, This, Result)
  8013. .VisitInitListExpr(ILE, AllocType);
  8014. }
  8015. // Return true iff the given array filler may depend on the element index.
  8016. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  8017. // For now, just whitelist non-class value-initialization and initialization
  8018. // lists comprised of them.
  8019. if (isa<ImplicitValueInitExpr>(FillerExpr))
  8020. return false;
  8021. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  8022. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  8023. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  8024. return true;
  8025. }
  8026. return false;
  8027. }
  8028. return true;
  8029. }
  8030. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
  8031. QualType AllocType) {
  8032. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  8033. AllocType.isNull() ? E->getType() : AllocType);
  8034. if (!CAT)
  8035. return Error(E);
  8036. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  8037. // an appropriately-typed string literal enclosed in braces.
  8038. if (E->isStringLiteralInit()) {
  8039. auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
  8040. // FIXME: Support ObjCEncodeExpr here once we support it in
  8041. // ArrayExprEvaluator generally.
  8042. if (!SL)
  8043. return Error(E);
  8044. return VisitStringLiteral(SL, AllocType);
  8045. }
  8046. bool Success = true;
  8047. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  8048. "zero-initialized array shouldn't have any initialized elts");
  8049. APValue Filler;
  8050. if (Result.isArray() && Result.hasArrayFiller())
  8051. Filler = Result.getArrayFiller();
  8052. unsigned NumEltsToInit = E->getNumInits();
  8053. unsigned NumElts = CAT->getSize().getZExtValue();
  8054. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  8055. // If the initializer might depend on the array index, run it for each
  8056. // array element.
  8057. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  8058. NumEltsToInit = NumElts;
  8059. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  8060. << NumEltsToInit << ".\n");
  8061. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  8062. // If the array was previously zero-initialized, preserve the
  8063. // zero-initialized values.
  8064. if (Filler.hasValue()) {
  8065. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  8066. Result.getArrayInitializedElt(I) = Filler;
  8067. if (Result.hasArrayFiller())
  8068. Result.getArrayFiller() = Filler;
  8069. }
  8070. LValue Subobject = This;
  8071. Subobject.addArray(Info, E, CAT);
  8072. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  8073. const Expr *Init =
  8074. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  8075. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  8076. Info, Subobject, Init) ||
  8077. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  8078. CAT->getElementType(), 1)) {
  8079. if (!Info.noteFailure())
  8080. return false;
  8081. Success = false;
  8082. }
  8083. }
  8084. if (!Result.hasArrayFiller())
  8085. return Success;
  8086. // If we get here, we have a trivial filler, which we can just evaluate
  8087. // once and splat over the rest of the array elements.
  8088. assert(FillerExpr && "no array filler for incomplete init list");
  8089. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  8090. FillerExpr) && Success;
  8091. }
  8092. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  8093. LValue CommonLV;
  8094. if (E->getCommonExpr() &&
  8095. !Evaluate(Info.CurrentCall->createTemporary(
  8096. E->getCommonExpr(),
  8097. getStorageType(Info.Ctx, E->getCommonExpr()), false,
  8098. CommonLV),
  8099. Info, E->getCommonExpr()->getSourceExpr()))
  8100. return false;
  8101. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  8102. uint64_t Elements = CAT->getSize().getZExtValue();
  8103. Result = APValue(APValue::UninitArray(), Elements, Elements);
  8104. LValue Subobject = This;
  8105. Subobject.addArray(Info, E, CAT);
  8106. bool Success = true;
  8107. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  8108. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  8109. Info, Subobject, E->getSubExpr()) ||
  8110. !HandleLValueArrayAdjustment(Info, E, Subobject,
  8111. CAT->getElementType(), 1)) {
  8112. if (!Info.noteFailure())
  8113. return false;
  8114. Success = false;
  8115. }
  8116. }
  8117. return Success;
  8118. }
  8119. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8120. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  8121. }
  8122. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  8123. const LValue &Subobject,
  8124. APValue *Value,
  8125. QualType Type) {
  8126. bool HadZeroInit = Value->hasValue();
  8127. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  8128. unsigned N = CAT->getSize().getZExtValue();
  8129. // Preserve the array filler if we had prior zero-initialization.
  8130. APValue Filler =
  8131. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  8132. : APValue();
  8133. *Value = APValue(APValue::UninitArray(), N, N);
  8134. if (HadZeroInit)
  8135. for (unsigned I = 0; I != N; ++I)
  8136. Value->getArrayInitializedElt(I) = Filler;
  8137. // Initialize the elements.
  8138. LValue ArrayElt = Subobject;
  8139. ArrayElt.addArray(Info, E, CAT);
  8140. for (unsigned I = 0; I != N; ++I)
  8141. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  8142. CAT->getElementType()) ||
  8143. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  8144. CAT->getElementType(), 1))
  8145. return false;
  8146. return true;
  8147. }
  8148. if (!Type->isRecordType())
  8149. return Error(E);
  8150. return RecordExprEvaluator(Info, Subobject, *Value)
  8151. .VisitCXXConstructExpr(E, Type);
  8152. }
  8153. //===----------------------------------------------------------------------===//
  8154. // Integer Evaluation
  8155. //
  8156. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  8157. // types and back in constant folding. Integer values are thus represented
  8158. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  8159. //===----------------------------------------------------------------------===//
  8160. namespace {
  8161. class IntExprEvaluator
  8162. : public ExprEvaluatorBase<IntExprEvaluator> {
  8163. APValue &Result;
  8164. public:
  8165. IntExprEvaluator(EvalInfo &info, APValue &result)
  8166. : ExprEvaluatorBaseTy(info), Result(result) {}
  8167. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  8168. assert(E->getType()->isIntegralOrEnumerationType() &&
  8169. "Invalid evaluation result.");
  8170. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  8171. "Invalid evaluation result.");
  8172. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8173. "Invalid evaluation result.");
  8174. Result = APValue(SI);
  8175. return true;
  8176. }
  8177. bool Success(const llvm::APSInt &SI, const Expr *E) {
  8178. return Success(SI, E, Result);
  8179. }
  8180. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  8181. assert(E->getType()->isIntegralOrEnumerationType() &&
  8182. "Invalid evaluation result.");
  8183. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8184. "Invalid evaluation result.");
  8185. Result = APValue(APSInt(I));
  8186. Result.getInt().setIsUnsigned(
  8187. E->getType()->isUnsignedIntegerOrEnumerationType());
  8188. return true;
  8189. }
  8190. bool Success(const llvm::APInt &I, const Expr *E) {
  8191. return Success(I, E, Result);
  8192. }
  8193. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8194. assert(E->getType()->isIntegralOrEnumerationType() &&
  8195. "Invalid evaluation result.");
  8196. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  8197. return true;
  8198. }
  8199. bool Success(uint64_t Value, const Expr *E) {
  8200. return Success(Value, E, Result);
  8201. }
  8202. bool Success(CharUnits Size, const Expr *E) {
  8203. return Success(Size.getQuantity(), E);
  8204. }
  8205. bool Success(const APValue &V, const Expr *E) {
  8206. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  8207. Result = V;
  8208. return true;
  8209. }
  8210. return Success(V.getInt(), E);
  8211. }
  8212. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  8213. //===--------------------------------------------------------------------===//
  8214. // Visitor Methods
  8215. //===--------------------------------------------------------------------===//
  8216. bool VisitConstantExpr(const ConstantExpr *E);
  8217. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  8218. return Success(E->getValue(), E);
  8219. }
  8220. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  8221. return Success(E->getValue(), E);
  8222. }
  8223. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  8224. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  8225. if (CheckReferencedDecl(E, E->getDecl()))
  8226. return true;
  8227. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  8228. }
  8229. bool VisitMemberExpr(const MemberExpr *E) {
  8230. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  8231. VisitIgnoredBaseExpression(E->getBase());
  8232. return true;
  8233. }
  8234. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  8235. }
  8236. bool VisitCallExpr(const CallExpr *E);
  8237. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  8238. bool VisitBinaryOperator(const BinaryOperator *E);
  8239. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  8240. bool VisitUnaryOperator(const UnaryOperator *E);
  8241. bool VisitCastExpr(const CastExpr* E);
  8242. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  8243. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  8244. return Success(E->getValue(), E);
  8245. }
  8246. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  8247. return Success(E->getValue(), E);
  8248. }
  8249. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  8250. if (Info.ArrayInitIndex == uint64_t(-1)) {
  8251. // We were asked to evaluate this subexpression independent of the
  8252. // enclosing ArrayInitLoopExpr. We can't do that.
  8253. Info.FFDiag(E);
  8254. return false;
  8255. }
  8256. return Success(Info.ArrayInitIndex, E);
  8257. }
  8258. // Note, GNU defines __null as an integer, not a pointer.
  8259. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  8260. return ZeroInitialization(E);
  8261. }
  8262. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  8263. return Success(E->getValue(), E);
  8264. }
  8265. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  8266. return Success(E->getValue(), E);
  8267. }
  8268. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  8269. return Success(E->getValue(), E);
  8270. }
  8271. bool VisitUnaryReal(const UnaryOperator *E);
  8272. bool VisitUnaryImag(const UnaryOperator *E);
  8273. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  8274. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  8275. bool VisitSourceLocExpr(const SourceLocExpr *E);
  8276. // FIXME: Missing: array subscript of vector, member of vector
  8277. };
  8278. class FixedPointExprEvaluator
  8279. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  8280. APValue &Result;
  8281. public:
  8282. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  8283. : ExprEvaluatorBaseTy(info), Result(result) {}
  8284. bool Success(const llvm::APInt &I, const Expr *E) {
  8285. return Success(
  8286. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8287. }
  8288. bool Success(uint64_t Value, const Expr *E) {
  8289. return Success(
  8290. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8291. }
  8292. bool Success(const APValue &V, const Expr *E) {
  8293. return Success(V.getFixedPoint(), E);
  8294. }
  8295. bool Success(const APFixedPoint &V, const Expr *E) {
  8296. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  8297. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8298. "Invalid evaluation result.");
  8299. Result = APValue(V);
  8300. return true;
  8301. }
  8302. //===--------------------------------------------------------------------===//
  8303. // Visitor Methods
  8304. //===--------------------------------------------------------------------===//
  8305. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  8306. return Success(E->getValue(), E);
  8307. }
  8308. bool VisitCastExpr(const CastExpr *E);
  8309. bool VisitUnaryOperator(const UnaryOperator *E);
  8310. bool VisitBinaryOperator(const BinaryOperator *E);
  8311. };
  8312. } // end anonymous namespace
  8313. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  8314. /// produce either the integer value or a pointer.
  8315. ///
  8316. /// GCC has a heinous extension which folds casts between pointer types and
  8317. /// pointer-sized integral types. We support this by allowing the evaluation of
  8318. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  8319. /// Some simple arithmetic on such values is supported (they are treated much
  8320. /// like char*).
  8321. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  8322. EvalInfo &Info) {
  8323. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  8324. return IntExprEvaluator(Info, Result).Visit(E);
  8325. }
  8326. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  8327. APValue Val;
  8328. if (!EvaluateIntegerOrLValue(E, Val, Info))
  8329. return false;
  8330. if (!Val.isInt()) {
  8331. // FIXME: It would be better to produce the diagnostic for casting
  8332. // a pointer to an integer.
  8333. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8334. return false;
  8335. }
  8336. Result = Val.getInt();
  8337. return true;
  8338. }
  8339. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  8340. APValue Evaluated = E->EvaluateInContext(
  8341. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  8342. return Success(Evaluated, E);
  8343. }
  8344. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  8345. EvalInfo &Info) {
  8346. if (E->getType()->isFixedPointType()) {
  8347. APValue Val;
  8348. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  8349. return false;
  8350. if (!Val.isFixedPoint())
  8351. return false;
  8352. Result = Val.getFixedPoint();
  8353. return true;
  8354. }
  8355. return false;
  8356. }
  8357. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  8358. EvalInfo &Info) {
  8359. if (E->getType()->isIntegerType()) {
  8360. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  8361. APSInt Val;
  8362. if (!EvaluateInteger(E, Val, Info))
  8363. return false;
  8364. Result = APFixedPoint(Val, FXSema);
  8365. return true;
  8366. } else if (E->getType()->isFixedPointType()) {
  8367. return EvaluateFixedPoint(E, Result, Info);
  8368. }
  8369. return false;
  8370. }
  8371. /// Check whether the given declaration can be directly converted to an integral
  8372. /// rvalue. If not, no diagnostic is produced; there are other things we can
  8373. /// try.
  8374. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  8375. // Enums are integer constant exprs.
  8376. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  8377. // Check for signedness/width mismatches between E type and ECD value.
  8378. bool SameSign = (ECD->getInitVal().isSigned()
  8379. == E->getType()->isSignedIntegerOrEnumerationType());
  8380. bool SameWidth = (ECD->getInitVal().getBitWidth()
  8381. == Info.Ctx.getIntWidth(E->getType()));
  8382. if (SameSign && SameWidth)
  8383. return Success(ECD->getInitVal(), E);
  8384. else {
  8385. // Get rid of mismatch (otherwise Success assertions will fail)
  8386. // by computing a new value matching the type of E.
  8387. llvm::APSInt Val = ECD->getInitVal();
  8388. if (!SameSign)
  8389. Val.setIsSigned(!ECD->getInitVal().isSigned());
  8390. if (!SameWidth)
  8391. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  8392. return Success(Val, E);
  8393. }
  8394. }
  8395. return false;
  8396. }
  8397. /// Values returned by __builtin_classify_type, chosen to match the values
  8398. /// produced by GCC's builtin.
  8399. enum class GCCTypeClass {
  8400. None = -1,
  8401. Void = 0,
  8402. Integer = 1,
  8403. // GCC reserves 2 for character types, but instead classifies them as
  8404. // integers.
  8405. Enum = 3,
  8406. Bool = 4,
  8407. Pointer = 5,
  8408. // GCC reserves 6 for references, but appears to never use it (because
  8409. // expressions never have reference type, presumably).
  8410. PointerToDataMember = 7,
  8411. RealFloat = 8,
  8412. Complex = 9,
  8413. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  8414. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8415. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  8416. // uses 12 for that purpose, same as for a class or struct. Maybe it
  8417. // internally implements a pointer to member as a struct? Who knows.
  8418. PointerToMemberFunction = 12, // Not a bug, see above.
  8419. ClassOrStruct = 12,
  8420. Union = 13,
  8421. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  8422. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8423. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  8424. // literals.
  8425. };
  8426. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8427. /// as GCC.
  8428. static GCCTypeClass
  8429. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  8430. assert(!T->isDependentType() && "unexpected dependent type");
  8431. QualType CanTy = T.getCanonicalType();
  8432. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  8433. switch (CanTy->getTypeClass()) {
  8434. #define TYPE(ID, BASE)
  8435. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8436. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  8437. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8438. #include "clang/AST/TypeNodes.def"
  8439. case Type::Auto:
  8440. case Type::DeducedTemplateSpecialization:
  8441. llvm_unreachable("unexpected non-canonical or dependent type");
  8442. case Type::Builtin:
  8443. switch (BT->getKind()) {
  8444. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  8445. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  8446. case BuiltinType::ID: return GCCTypeClass::Integer;
  8447. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  8448. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  8449. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  8450. case BuiltinType::ID: break;
  8451. #include "clang/AST/BuiltinTypes.def"
  8452. case BuiltinType::Void:
  8453. return GCCTypeClass::Void;
  8454. case BuiltinType::Bool:
  8455. return GCCTypeClass::Bool;
  8456. case BuiltinType::Char_U:
  8457. case BuiltinType::UChar:
  8458. case BuiltinType::WChar_U:
  8459. case BuiltinType::Char8:
  8460. case BuiltinType::Char16:
  8461. case BuiltinType::Char32:
  8462. case BuiltinType::UShort:
  8463. case BuiltinType::UInt:
  8464. case BuiltinType::ULong:
  8465. case BuiltinType::ULongLong:
  8466. case BuiltinType::UInt128:
  8467. return GCCTypeClass::Integer;
  8468. case BuiltinType::UShortAccum:
  8469. case BuiltinType::UAccum:
  8470. case BuiltinType::ULongAccum:
  8471. case BuiltinType::UShortFract:
  8472. case BuiltinType::UFract:
  8473. case BuiltinType::ULongFract:
  8474. case BuiltinType::SatUShortAccum:
  8475. case BuiltinType::SatUAccum:
  8476. case BuiltinType::SatULongAccum:
  8477. case BuiltinType::SatUShortFract:
  8478. case BuiltinType::SatUFract:
  8479. case BuiltinType::SatULongFract:
  8480. return GCCTypeClass::None;
  8481. case BuiltinType::NullPtr:
  8482. case BuiltinType::ObjCId:
  8483. case BuiltinType::ObjCClass:
  8484. case BuiltinType::ObjCSel:
  8485. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  8486. case BuiltinType::Id:
  8487. #include "clang/Basic/OpenCLImageTypes.def"
  8488. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  8489. case BuiltinType::Id:
  8490. #include "clang/Basic/OpenCLExtensionTypes.def"
  8491. case BuiltinType::OCLSampler:
  8492. case BuiltinType::OCLEvent:
  8493. case BuiltinType::OCLClkEvent:
  8494. case BuiltinType::OCLQueue:
  8495. case BuiltinType::OCLReserveID:
  8496. #define SVE_TYPE(Name, Id, SingletonId) \
  8497. case BuiltinType::Id:
  8498. #include "clang/Basic/AArch64SVEACLETypes.def"
  8499. return GCCTypeClass::None;
  8500. case BuiltinType::Dependent:
  8501. llvm_unreachable("unexpected dependent type");
  8502. };
  8503. llvm_unreachable("unexpected placeholder type");
  8504. case Type::Enum:
  8505. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  8506. case Type::Pointer:
  8507. case Type::ConstantArray:
  8508. case Type::VariableArray:
  8509. case Type::IncompleteArray:
  8510. case Type::FunctionNoProto:
  8511. case Type::FunctionProto:
  8512. return GCCTypeClass::Pointer;
  8513. case Type::MemberPointer:
  8514. return CanTy->isMemberDataPointerType()
  8515. ? GCCTypeClass::PointerToDataMember
  8516. : GCCTypeClass::PointerToMemberFunction;
  8517. case Type::Complex:
  8518. return GCCTypeClass::Complex;
  8519. case Type::Record:
  8520. return CanTy->isUnionType() ? GCCTypeClass::Union
  8521. : GCCTypeClass::ClassOrStruct;
  8522. case Type::Atomic:
  8523. // GCC classifies _Atomic T the same as T.
  8524. return EvaluateBuiltinClassifyType(
  8525. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  8526. case Type::BlockPointer:
  8527. case Type::Vector:
  8528. case Type::ExtVector:
  8529. case Type::ObjCObject:
  8530. case Type::ObjCInterface:
  8531. case Type::ObjCObjectPointer:
  8532. case Type::Pipe:
  8533. // GCC classifies vectors as None. We follow its lead and classify all
  8534. // other types that don't fit into the regular classification the same way.
  8535. return GCCTypeClass::None;
  8536. case Type::LValueReference:
  8537. case Type::RValueReference:
  8538. llvm_unreachable("invalid type for expression");
  8539. }
  8540. llvm_unreachable("unexpected type class");
  8541. }
  8542. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8543. /// as GCC.
  8544. static GCCTypeClass
  8545. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  8546. // If no argument was supplied, default to None. This isn't
  8547. // ideal, however it is what gcc does.
  8548. if (E->getNumArgs() == 0)
  8549. return GCCTypeClass::None;
  8550. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  8551. // being an ICE, but still folds it to a constant using the type of the first
  8552. // argument.
  8553. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  8554. }
  8555. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  8556. /// __builtin_constant_p when applied to the given pointer.
  8557. ///
  8558. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  8559. /// or it points to the first character of a string literal.
  8560. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  8561. APValue::LValueBase Base = LV.getLValueBase();
  8562. if (Base.isNull()) {
  8563. // A null base is acceptable.
  8564. return true;
  8565. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  8566. if (!isa<StringLiteral>(E))
  8567. return false;
  8568. return LV.getLValueOffset().isZero();
  8569. } else if (Base.is<TypeInfoLValue>()) {
  8570. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  8571. // evaluate to true.
  8572. return true;
  8573. } else {
  8574. // Any other base is not constant enough for GCC.
  8575. return false;
  8576. }
  8577. }
  8578. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  8579. /// GCC as we can manage.
  8580. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  8581. // This evaluation is not permitted to have side-effects, so evaluate it in
  8582. // a speculative evaluation context.
  8583. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8584. // Constant-folding is always enabled for the operand of __builtin_constant_p
  8585. // (even when the enclosing evaluation context otherwise requires a strict
  8586. // language-specific constant expression).
  8587. FoldConstant Fold(Info, true);
  8588. QualType ArgType = Arg->getType();
  8589. // __builtin_constant_p always has one operand. The rules which gcc follows
  8590. // are not precisely documented, but are as follows:
  8591. //
  8592. // - If the operand is of integral, floating, complex or enumeration type,
  8593. // and can be folded to a known value of that type, it returns 1.
  8594. // - If the operand can be folded to a pointer to the first character
  8595. // of a string literal (or such a pointer cast to an integral type)
  8596. // or to a null pointer or an integer cast to a pointer, it returns 1.
  8597. //
  8598. // Otherwise, it returns 0.
  8599. //
  8600. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  8601. // its support for this did not work prior to GCC 9 and is not yet well
  8602. // understood.
  8603. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  8604. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  8605. ArgType->isNullPtrType()) {
  8606. APValue V;
  8607. if (!::EvaluateAsRValue(Info, Arg, V)) {
  8608. Fold.keepDiagnostics();
  8609. return false;
  8610. }
  8611. // For a pointer (possibly cast to integer), there are special rules.
  8612. if (V.getKind() == APValue::LValue)
  8613. return EvaluateBuiltinConstantPForLValue(V);
  8614. // Otherwise, any constant value is good enough.
  8615. return V.hasValue();
  8616. }
  8617. // Anything else isn't considered to be sufficiently constant.
  8618. return false;
  8619. }
  8620. /// Retrieves the "underlying object type" of the given expression,
  8621. /// as used by __builtin_object_size.
  8622. static QualType getObjectType(APValue::LValueBase B) {
  8623. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  8624. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  8625. return VD->getType();
  8626. } else if (const Expr *E = B.get<const Expr*>()) {
  8627. if (isa<CompoundLiteralExpr>(E))
  8628. return E->getType();
  8629. } else if (B.is<TypeInfoLValue>()) {
  8630. return B.getTypeInfoType();
  8631. } else if (B.is<DynamicAllocLValue>()) {
  8632. return B.getDynamicAllocType();
  8633. }
  8634. return QualType();
  8635. }
  8636. /// A more selective version of E->IgnoreParenCasts for
  8637. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  8638. /// to change the type of E.
  8639. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  8640. ///
  8641. /// Always returns an RValue with a pointer representation.
  8642. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  8643. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  8644. auto *NoParens = E->IgnoreParens();
  8645. auto *Cast = dyn_cast<CastExpr>(NoParens);
  8646. if (Cast == nullptr)
  8647. return NoParens;
  8648. // We only conservatively allow a few kinds of casts, because this code is
  8649. // inherently a simple solution that seeks to support the common case.
  8650. auto CastKind = Cast->getCastKind();
  8651. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  8652. CastKind != CK_AddressSpaceConversion)
  8653. return NoParens;
  8654. auto *SubExpr = Cast->getSubExpr();
  8655. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  8656. return NoParens;
  8657. return ignorePointerCastsAndParens(SubExpr);
  8658. }
  8659. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  8660. /// record layout. e.g.
  8661. /// struct { struct { int a, b; } fst, snd; } obj;
  8662. /// obj.fst // no
  8663. /// obj.snd // yes
  8664. /// obj.fst.a // no
  8665. /// obj.fst.b // no
  8666. /// obj.snd.a // no
  8667. /// obj.snd.b // yes
  8668. ///
  8669. /// Please note: this function is specialized for how __builtin_object_size
  8670. /// views "objects".
  8671. ///
  8672. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  8673. /// correct result, it will always return true.
  8674. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  8675. assert(!LVal.Designator.Invalid);
  8676. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  8677. const RecordDecl *Parent = FD->getParent();
  8678. Invalid = Parent->isInvalidDecl();
  8679. if (Invalid || Parent->isUnion())
  8680. return true;
  8681. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  8682. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  8683. };
  8684. auto &Base = LVal.getLValueBase();
  8685. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  8686. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  8687. bool Invalid;
  8688. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8689. return Invalid;
  8690. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  8691. for (auto *FD : IFD->chain()) {
  8692. bool Invalid;
  8693. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  8694. return Invalid;
  8695. }
  8696. }
  8697. }
  8698. unsigned I = 0;
  8699. QualType BaseType = getType(Base);
  8700. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  8701. // If we don't know the array bound, conservatively assume we're looking at
  8702. // the final array element.
  8703. ++I;
  8704. if (BaseType->isIncompleteArrayType())
  8705. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  8706. else
  8707. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  8708. }
  8709. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  8710. const auto &Entry = LVal.Designator.Entries[I];
  8711. if (BaseType->isArrayType()) {
  8712. // Because __builtin_object_size treats arrays as objects, we can ignore
  8713. // the index iff this is the last array in the Designator.
  8714. if (I + 1 == E)
  8715. return true;
  8716. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  8717. uint64_t Index = Entry.getAsArrayIndex();
  8718. if (Index + 1 != CAT->getSize())
  8719. return false;
  8720. BaseType = CAT->getElementType();
  8721. } else if (BaseType->isAnyComplexType()) {
  8722. const auto *CT = BaseType->castAs<ComplexType>();
  8723. uint64_t Index = Entry.getAsArrayIndex();
  8724. if (Index != 1)
  8725. return false;
  8726. BaseType = CT->getElementType();
  8727. } else if (auto *FD = getAsField(Entry)) {
  8728. bool Invalid;
  8729. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8730. return Invalid;
  8731. BaseType = FD->getType();
  8732. } else {
  8733. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  8734. return false;
  8735. }
  8736. }
  8737. return true;
  8738. }
  8739. /// Tests to see if the LValue has a user-specified designator (that isn't
  8740. /// necessarily valid). Note that this always returns 'true' if the LValue has
  8741. /// an unsized array as its first designator entry, because there's currently no
  8742. /// way to tell if the user typed *foo or foo[0].
  8743. static bool refersToCompleteObject(const LValue &LVal) {
  8744. if (LVal.Designator.Invalid)
  8745. return false;
  8746. if (!LVal.Designator.Entries.empty())
  8747. return LVal.Designator.isMostDerivedAnUnsizedArray();
  8748. if (!LVal.InvalidBase)
  8749. return true;
  8750. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  8751. // the LValueBase.
  8752. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  8753. return !E || !isa<MemberExpr>(E);
  8754. }
  8755. /// Attempts to detect a user writing into a piece of memory that's impossible
  8756. /// to figure out the size of by just using types.
  8757. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  8758. const SubobjectDesignator &Designator = LVal.Designator;
  8759. // Notes:
  8760. // - Users can only write off of the end when we have an invalid base. Invalid
  8761. // bases imply we don't know where the memory came from.
  8762. // - We used to be a bit more aggressive here; we'd only be conservative if
  8763. // the array at the end was flexible, or if it had 0 or 1 elements. This
  8764. // broke some common standard library extensions (PR30346), but was
  8765. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  8766. // with some sort of whitelist. OTOH, it seems that GCC is always
  8767. // conservative with the last element in structs (if it's an array), so our
  8768. // current behavior is more compatible than a whitelisting approach would
  8769. // be.
  8770. return LVal.InvalidBase &&
  8771. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  8772. Designator.MostDerivedIsArrayElement &&
  8773. isDesignatorAtObjectEnd(Ctx, LVal);
  8774. }
  8775. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  8776. /// Fails if the conversion would cause loss of precision.
  8777. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  8778. CharUnits &Result) {
  8779. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  8780. if (Int.ugt(CharUnitsMax))
  8781. return false;
  8782. Result = CharUnits::fromQuantity(Int.getZExtValue());
  8783. return true;
  8784. }
  8785. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  8786. /// determine how many bytes exist from the beginning of the object to either
  8787. /// the end of the current subobject, or the end of the object itself, depending
  8788. /// on what the LValue looks like + the value of Type.
  8789. ///
  8790. /// If this returns false, the value of Result is undefined.
  8791. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  8792. unsigned Type, const LValue &LVal,
  8793. CharUnits &EndOffset) {
  8794. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  8795. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  8796. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  8797. return false;
  8798. return HandleSizeof(Info, ExprLoc, Ty, Result);
  8799. };
  8800. // We want to evaluate the size of the entire object. This is a valid fallback
  8801. // for when Type=1 and the designator is invalid, because we're asked for an
  8802. // upper-bound.
  8803. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  8804. // Type=3 wants a lower bound, so we can't fall back to this.
  8805. if (Type == 3 && !DetermineForCompleteObject)
  8806. return false;
  8807. llvm::APInt APEndOffset;
  8808. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8809. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8810. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8811. if (LVal.InvalidBase)
  8812. return false;
  8813. QualType BaseTy = getObjectType(LVal.getLValueBase());
  8814. return CheckedHandleSizeof(BaseTy, EndOffset);
  8815. }
  8816. // We want to evaluate the size of a subobject.
  8817. const SubobjectDesignator &Designator = LVal.Designator;
  8818. // The following is a moderately common idiom in C:
  8819. //
  8820. // struct Foo { int a; char c[1]; };
  8821. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  8822. // strcpy(&F->c[0], Bar);
  8823. //
  8824. // In order to not break too much legacy code, we need to support it.
  8825. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  8826. // If we can resolve this to an alloc_size call, we can hand that back,
  8827. // because we know for certain how many bytes there are to write to.
  8828. llvm::APInt APEndOffset;
  8829. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  8830. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  8831. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  8832. // If we cannot determine the size of the initial allocation, then we can't
  8833. // given an accurate upper-bound. However, we are still able to give
  8834. // conservative lower-bounds for Type=3.
  8835. if (Type == 1)
  8836. return false;
  8837. }
  8838. CharUnits BytesPerElem;
  8839. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  8840. return false;
  8841. // According to the GCC documentation, we want the size of the subobject
  8842. // denoted by the pointer. But that's not quite right -- what we actually
  8843. // want is the size of the immediately-enclosing array, if there is one.
  8844. int64_t ElemsRemaining;
  8845. if (Designator.MostDerivedIsArrayElement &&
  8846. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  8847. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  8848. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  8849. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  8850. } else {
  8851. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  8852. }
  8853. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  8854. return true;
  8855. }
  8856. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  8857. /// returns true and stores the result in @p Size.
  8858. ///
  8859. /// If @p WasError is non-null, this will report whether the failure to evaluate
  8860. /// is to be treated as an Error in IntExprEvaluator.
  8861. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  8862. EvalInfo &Info, uint64_t &Size) {
  8863. // Determine the denoted object.
  8864. LValue LVal;
  8865. {
  8866. // The operand of __builtin_object_size is never evaluated for side-effects.
  8867. // If there are any, but we can determine the pointed-to object anyway, then
  8868. // ignore the side-effects.
  8869. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8870. IgnoreSideEffectsRAII Fold(Info);
  8871. if (E->isGLValue()) {
  8872. // It's possible for us to be given GLValues if we're called via
  8873. // Expr::tryEvaluateObjectSize.
  8874. APValue RVal;
  8875. if (!EvaluateAsRValue(Info, E, RVal))
  8876. return false;
  8877. LVal.setFrom(Info.Ctx, RVal);
  8878. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  8879. /*InvalidBaseOK=*/true))
  8880. return false;
  8881. }
  8882. // If we point to before the start of the object, there are no accessible
  8883. // bytes.
  8884. if (LVal.getLValueOffset().isNegative()) {
  8885. Size = 0;
  8886. return true;
  8887. }
  8888. CharUnits EndOffset;
  8889. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  8890. return false;
  8891. // If we've fallen outside of the end offset, just pretend there's nothing to
  8892. // write to/read from.
  8893. if (EndOffset <= LVal.getLValueOffset())
  8894. Size = 0;
  8895. else
  8896. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  8897. return true;
  8898. }
  8899. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  8900. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  8901. if (E->getResultAPValueKind() != APValue::None)
  8902. return Success(E->getAPValueResult(), E);
  8903. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  8904. }
  8905. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8906. if (unsigned BuiltinOp = E->getBuiltinCallee())
  8907. return VisitBuiltinCallExpr(E, BuiltinOp);
  8908. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8909. }
  8910. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  8911. unsigned BuiltinOp) {
  8912. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  8913. default:
  8914. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8915. case Builtin::BI__builtin_dynamic_object_size:
  8916. case Builtin::BI__builtin_object_size: {
  8917. // The type was checked when we built the expression.
  8918. unsigned Type =
  8919. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  8920. assert(Type <= 3 && "unexpected type");
  8921. uint64_t Size;
  8922. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  8923. return Success(Size, E);
  8924. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  8925. return Success((Type & 2) ? 0 : -1, E);
  8926. // Expression had no side effects, but we couldn't statically determine the
  8927. // size of the referenced object.
  8928. switch (Info.EvalMode) {
  8929. case EvalInfo::EM_ConstantExpression:
  8930. case EvalInfo::EM_ConstantFold:
  8931. case EvalInfo::EM_IgnoreSideEffects:
  8932. // Leave it to IR generation.
  8933. return Error(E);
  8934. case EvalInfo::EM_ConstantExpressionUnevaluated:
  8935. // Reduce it to a constant now.
  8936. return Success((Type & 2) ? 0 : -1, E);
  8937. }
  8938. llvm_unreachable("unexpected EvalMode");
  8939. }
  8940. case Builtin::BI__builtin_os_log_format_buffer_size: {
  8941. analyze_os_log::OSLogBufferLayout Layout;
  8942. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  8943. return Success(Layout.size().getQuantity(), E);
  8944. }
  8945. case Builtin::BI__builtin_bswap16:
  8946. case Builtin::BI__builtin_bswap32:
  8947. case Builtin::BI__builtin_bswap64: {
  8948. APSInt Val;
  8949. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8950. return false;
  8951. return Success(Val.byteSwap(), E);
  8952. }
  8953. case Builtin::BI__builtin_classify_type:
  8954. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  8955. case Builtin::BI__builtin_clrsb:
  8956. case Builtin::BI__builtin_clrsbl:
  8957. case Builtin::BI__builtin_clrsbll: {
  8958. APSInt Val;
  8959. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8960. return false;
  8961. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  8962. }
  8963. case Builtin::BI__builtin_clz:
  8964. case Builtin::BI__builtin_clzl:
  8965. case Builtin::BI__builtin_clzll:
  8966. case Builtin::BI__builtin_clzs: {
  8967. APSInt Val;
  8968. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8969. return false;
  8970. if (!Val)
  8971. return Error(E);
  8972. return Success(Val.countLeadingZeros(), E);
  8973. }
  8974. case Builtin::BI__builtin_constant_p: {
  8975. const Expr *Arg = E->getArg(0);
  8976. if (EvaluateBuiltinConstantP(Info, Arg))
  8977. return Success(true, E);
  8978. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  8979. // Outside a constant context, eagerly evaluate to false in the presence
  8980. // of side-effects in order to avoid -Wunsequenced false-positives in
  8981. // a branch on __builtin_constant_p(expr).
  8982. return Success(false, E);
  8983. }
  8984. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8985. return false;
  8986. }
  8987. case Builtin::BI__builtin_is_constant_evaluated:
  8988. return Success(Info.InConstantContext, E);
  8989. case Builtin::BI__builtin_ctz:
  8990. case Builtin::BI__builtin_ctzl:
  8991. case Builtin::BI__builtin_ctzll:
  8992. case Builtin::BI__builtin_ctzs: {
  8993. APSInt Val;
  8994. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8995. return false;
  8996. if (!Val)
  8997. return Error(E);
  8998. return Success(Val.countTrailingZeros(), E);
  8999. }
  9000. case Builtin::BI__builtin_eh_return_data_regno: {
  9001. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  9002. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  9003. return Success(Operand, E);
  9004. }
  9005. case Builtin::BI__builtin_expect:
  9006. return Visit(E->getArg(0));
  9007. case Builtin::BI__builtin_ffs:
  9008. case Builtin::BI__builtin_ffsl:
  9009. case Builtin::BI__builtin_ffsll: {
  9010. APSInt Val;
  9011. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9012. return false;
  9013. unsigned N = Val.countTrailingZeros();
  9014. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  9015. }
  9016. case Builtin::BI__builtin_fpclassify: {
  9017. APFloat Val(0.0);
  9018. if (!EvaluateFloat(E->getArg(5), Val, Info))
  9019. return false;
  9020. unsigned Arg;
  9021. switch (Val.getCategory()) {
  9022. case APFloat::fcNaN: Arg = 0; break;
  9023. case APFloat::fcInfinity: Arg = 1; break;
  9024. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  9025. case APFloat::fcZero: Arg = 4; break;
  9026. }
  9027. return Visit(E->getArg(Arg));
  9028. }
  9029. case Builtin::BI__builtin_isinf_sign: {
  9030. APFloat Val(0.0);
  9031. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9032. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  9033. }
  9034. case Builtin::BI__builtin_isinf: {
  9035. APFloat Val(0.0);
  9036. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9037. Success(Val.isInfinity() ? 1 : 0, E);
  9038. }
  9039. case Builtin::BI__builtin_isfinite: {
  9040. APFloat Val(0.0);
  9041. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9042. Success(Val.isFinite() ? 1 : 0, E);
  9043. }
  9044. case Builtin::BI__builtin_isnan: {
  9045. APFloat Val(0.0);
  9046. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9047. Success(Val.isNaN() ? 1 : 0, E);
  9048. }
  9049. case Builtin::BI__builtin_isnormal: {
  9050. APFloat Val(0.0);
  9051. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9052. Success(Val.isNormal() ? 1 : 0, E);
  9053. }
  9054. case Builtin::BI__builtin_parity:
  9055. case Builtin::BI__builtin_parityl:
  9056. case Builtin::BI__builtin_parityll: {
  9057. APSInt Val;
  9058. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9059. return false;
  9060. return Success(Val.countPopulation() % 2, E);
  9061. }
  9062. case Builtin::BI__builtin_popcount:
  9063. case Builtin::BI__builtin_popcountl:
  9064. case Builtin::BI__builtin_popcountll: {
  9065. APSInt Val;
  9066. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9067. return false;
  9068. return Success(Val.countPopulation(), E);
  9069. }
  9070. case Builtin::BIstrlen:
  9071. case Builtin::BIwcslen:
  9072. // A call to strlen is not a constant expression.
  9073. if (Info.getLangOpts().CPlusPlus11)
  9074. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9075. << /*isConstexpr*/0 << /*isConstructor*/0
  9076. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9077. else
  9078. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9079. LLVM_FALLTHROUGH;
  9080. case Builtin::BI__builtin_strlen:
  9081. case Builtin::BI__builtin_wcslen: {
  9082. // As an extension, we support __builtin_strlen() as a constant expression,
  9083. // and support folding strlen() to a constant.
  9084. LValue String;
  9085. if (!EvaluatePointer(E->getArg(0), String, Info))
  9086. return false;
  9087. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  9088. // Fast path: if it's a string literal, search the string value.
  9089. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  9090. String.getLValueBase().dyn_cast<const Expr *>())) {
  9091. // The string literal may have embedded null characters. Find the first
  9092. // one and truncate there.
  9093. StringRef Str = S->getBytes();
  9094. int64_t Off = String.Offset.getQuantity();
  9095. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  9096. S->getCharByteWidth() == 1 &&
  9097. // FIXME: Add fast-path for wchar_t too.
  9098. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  9099. Str = Str.substr(Off);
  9100. StringRef::size_type Pos = Str.find(0);
  9101. if (Pos != StringRef::npos)
  9102. Str = Str.substr(0, Pos);
  9103. return Success(Str.size(), E);
  9104. }
  9105. // Fall through to slow path to issue appropriate diagnostic.
  9106. }
  9107. // Slow path: scan the bytes of the string looking for the terminating 0.
  9108. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  9109. APValue Char;
  9110. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  9111. !Char.isInt())
  9112. return false;
  9113. if (!Char.getInt())
  9114. return Success(Strlen, E);
  9115. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  9116. return false;
  9117. }
  9118. }
  9119. case Builtin::BIstrcmp:
  9120. case Builtin::BIwcscmp:
  9121. case Builtin::BIstrncmp:
  9122. case Builtin::BIwcsncmp:
  9123. case Builtin::BImemcmp:
  9124. case Builtin::BIbcmp:
  9125. case Builtin::BIwmemcmp:
  9126. // A call to strlen is not a constant expression.
  9127. if (Info.getLangOpts().CPlusPlus11)
  9128. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9129. << /*isConstexpr*/0 << /*isConstructor*/0
  9130. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9131. else
  9132. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9133. LLVM_FALLTHROUGH;
  9134. case Builtin::BI__builtin_strcmp:
  9135. case Builtin::BI__builtin_wcscmp:
  9136. case Builtin::BI__builtin_strncmp:
  9137. case Builtin::BI__builtin_wcsncmp:
  9138. case Builtin::BI__builtin_memcmp:
  9139. case Builtin::BI__builtin_bcmp:
  9140. case Builtin::BI__builtin_wmemcmp: {
  9141. LValue String1, String2;
  9142. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  9143. !EvaluatePointer(E->getArg(1), String2, Info))
  9144. return false;
  9145. uint64_t MaxLength = uint64_t(-1);
  9146. if (BuiltinOp != Builtin::BIstrcmp &&
  9147. BuiltinOp != Builtin::BIwcscmp &&
  9148. BuiltinOp != Builtin::BI__builtin_strcmp &&
  9149. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  9150. APSInt N;
  9151. if (!EvaluateInteger(E->getArg(2), N, Info))
  9152. return false;
  9153. MaxLength = N.getExtValue();
  9154. }
  9155. // Empty substrings compare equal by definition.
  9156. if (MaxLength == 0u)
  9157. return Success(0, E);
  9158. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9159. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9160. String1.Designator.Invalid || String2.Designator.Invalid)
  9161. return false;
  9162. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  9163. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  9164. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  9165. BuiltinOp == Builtin::BIbcmp ||
  9166. BuiltinOp == Builtin::BI__builtin_memcmp ||
  9167. BuiltinOp == Builtin::BI__builtin_bcmp;
  9168. assert(IsRawByte ||
  9169. (Info.Ctx.hasSameUnqualifiedType(
  9170. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  9171. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  9172. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  9173. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  9174. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  9175. Char1.isInt() && Char2.isInt();
  9176. };
  9177. const auto &AdvanceElems = [&] {
  9178. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  9179. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  9180. };
  9181. if (IsRawByte) {
  9182. uint64_t BytesRemaining = MaxLength;
  9183. // Pointers to const void may point to objects of incomplete type.
  9184. if (CharTy1->isIncompleteType()) {
  9185. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  9186. return false;
  9187. }
  9188. if (CharTy2->isIncompleteType()) {
  9189. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  9190. return false;
  9191. }
  9192. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  9193. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  9194. // Give up on comparing between elements with disparate widths.
  9195. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  9196. return false;
  9197. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  9198. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  9199. "following loop considers at least one element");
  9200. while (true) {
  9201. APValue Char1, Char2;
  9202. if (!ReadCurElems(Char1, Char2))
  9203. return false;
  9204. // We have compatible in-memory widths, but a possible type and
  9205. // (for `bool`) internal representation mismatch.
  9206. // Assuming two's complement representation, including 0 for `false` and
  9207. // 1 for `true`, we can check an appropriate number of elements for
  9208. // equality even if they are not byte-sized.
  9209. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  9210. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  9211. if (Char1InMem.ne(Char2InMem)) {
  9212. // If the elements are byte-sized, then we can produce a three-way
  9213. // comparison result in a straightforward manner.
  9214. if (BytesPerElement == 1u) {
  9215. // memcmp always compares unsigned chars.
  9216. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  9217. }
  9218. // The result is byte-order sensitive, and we have multibyte elements.
  9219. // FIXME: We can compare the remaining bytes in the correct order.
  9220. return false;
  9221. }
  9222. if (!AdvanceElems())
  9223. return false;
  9224. if (BytesRemaining <= BytesPerElement)
  9225. break;
  9226. BytesRemaining -= BytesPerElement;
  9227. }
  9228. // Enough elements are equal to account for the memcmp limit.
  9229. return Success(0, E);
  9230. }
  9231. bool StopAtNull =
  9232. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  9233. BuiltinOp != Builtin::BIwmemcmp &&
  9234. BuiltinOp != Builtin::BI__builtin_memcmp &&
  9235. BuiltinOp != Builtin::BI__builtin_bcmp &&
  9236. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  9237. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  9238. BuiltinOp == Builtin::BIwcsncmp ||
  9239. BuiltinOp == Builtin::BIwmemcmp ||
  9240. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  9241. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  9242. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  9243. for (; MaxLength; --MaxLength) {
  9244. APValue Char1, Char2;
  9245. if (!ReadCurElems(Char1, Char2))
  9246. return false;
  9247. if (Char1.getInt() != Char2.getInt()) {
  9248. if (IsWide) // wmemcmp compares with wchar_t signedness.
  9249. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  9250. // memcmp always compares unsigned chars.
  9251. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  9252. }
  9253. if (StopAtNull && !Char1.getInt())
  9254. return Success(0, E);
  9255. assert(!(StopAtNull && !Char2.getInt()));
  9256. if (!AdvanceElems())
  9257. return false;
  9258. }
  9259. // We hit the strncmp / memcmp limit.
  9260. return Success(0, E);
  9261. }
  9262. case Builtin::BI__atomic_always_lock_free:
  9263. case Builtin::BI__atomic_is_lock_free:
  9264. case Builtin::BI__c11_atomic_is_lock_free: {
  9265. APSInt SizeVal;
  9266. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  9267. return false;
  9268. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  9269. // of two less than the maximum inline atomic width, we know it is
  9270. // lock-free. If the size isn't a power of two, or greater than the
  9271. // maximum alignment where we promote atomics, we know it is not lock-free
  9272. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  9273. // the answer can only be determined at runtime; for example, 16-byte
  9274. // atomics have lock-free implementations on some, but not all,
  9275. // x86-64 processors.
  9276. // Check power-of-two.
  9277. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  9278. if (Size.isPowerOfTwo()) {
  9279. // Check against inlining width.
  9280. unsigned InlineWidthBits =
  9281. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  9282. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  9283. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  9284. Size == CharUnits::One() ||
  9285. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  9286. Expr::NPC_NeverValueDependent))
  9287. // OK, we will inline appropriately-aligned operations of this size,
  9288. // and _Atomic(T) is appropriately-aligned.
  9289. return Success(1, E);
  9290. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  9291. castAs<PointerType>()->getPointeeType();
  9292. if (!PointeeType->isIncompleteType() &&
  9293. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  9294. // OK, we will inline operations on this object.
  9295. return Success(1, E);
  9296. }
  9297. }
  9298. }
  9299. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  9300. Success(0, E) : Error(E);
  9301. }
  9302. case Builtin::BIomp_is_initial_device:
  9303. // We can decide statically which value the runtime would return if called.
  9304. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  9305. case Builtin::BI__builtin_add_overflow:
  9306. case Builtin::BI__builtin_sub_overflow:
  9307. case Builtin::BI__builtin_mul_overflow:
  9308. case Builtin::BI__builtin_sadd_overflow:
  9309. case Builtin::BI__builtin_uadd_overflow:
  9310. case Builtin::BI__builtin_uaddl_overflow:
  9311. case Builtin::BI__builtin_uaddll_overflow:
  9312. case Builtin::BI__builtin_usub_overflow:
  9313. case Builtin::BI__builtin_usubl_overflow:
  9314. case Builtin::BI__builtin_usubll_overflow:
  9315. case Builtin::BI__builtin_umul_overflow:
  9316. case Builtin::BI__builtin_umull_overflow:
  9317. case Builtin::BI__builtin_umulll_overflow:
  9318. case Builtin::BI__builtin_saddl_overflow:
  9319. case Builtin::BI__builtin_saddll_overflow:
  9320. case Builtin::BI__builtin_ssub_overflow:
  9321. case Builtin::BI__builtin_ssubl_overflow:
  9322. case Builtin::BI__builtin_ssubll_overflow:
  9323. case Builtin::BI__builtin_smul_overflow:
  9324. case Builtin::BI__builtin_smull_overflow:
  9325. case Builtin::BI__builtin_smulll_overflow: {
  9326. LValue ResultLValue;
  9327. APSInt LHS, RHS;
  9328. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  9329. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  9330. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  9331. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  9332. return false;
  9333. APSInt Result;
  9334. bool DidOverflow = false;
  9335. // If the types don't have to match, enlarge all 3 to the largest of them.
  9336. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9337. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9338. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9339. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  9340. ResultType->isSignedIntegerOrEnumerationType();
  9341. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  9342. ResultType->isSignedIntegerOrEnumerationType();
  9343. uint64_t LHSSize = LHS.getBitWidth();
  9344. uint64_t RHSSize = RHS.getBitWidth();
  9345. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  9346. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  9347. // Add an additional bit if the signedness isn't uniformly agreed to. We
  9348. // could do this ONLY if there is a signed and an unsigned that both have
  9349. // MaxBits, but the code to check that is pretty nasty. The issue will be
  9350. // caught in the shrink-to-result later anyway.
  9351. if (IsSigned && !AllSigned)
  9352. ++MaxBits;
  9353. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  9354. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  9355. Result = APSInt(MaxBits, !IsSigned);
  9356. }
  9357. // Find largest int.
  9358. switch (BuiltinOp) {
  9359. default:
  9360. llvm_unreachable("Invalid value for BuiltinOp");
  9361. case Builtin::BI__builtin_add_overflow:
  9362. case Builtin::BI__builtin_sadd_overflow:
  9363. case Builtin::BI__builtin_saddl_overflow:
  9364. case Builtin::BI__builtin_saddll_overflow:
  9365. case Builtin::BI__builtin_uadd_overflow:
  9366. case Builtin::BI__builtin_uaddl_overflow:
  9367. case Builtin::BI__builtin_uaddll_overflow:
  9368. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  9369. : LHS.uadd_ov(RHS, DidOverflow);
  9370. break;
  9371. case Builtin::BI__builtin_sub_overflow:
  9372. case Builtin::BI__builtin_ssub_overflow:
  9373. case Builtin::BI__builtin_ssubl_overflow:
  9374. case Builtin::BI__builtin_ssubll_overflow:
  9375. case Builtin::BI__builtin_usub_overflow:
  9376. case Builtin::BI__builtin_usubl_overflow:
  9377. case Builtin::BI__builtin_usubll_overflow:
  9378. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  9379. : LHS.usub_ov(RHS, DidOverflow);
  9380. break;
  9381. case Builtin::BI__builtin_mul_overflow:
  9382. case Builtin::BI__builtin_smul_overflow:
  9383. case Builtin::BI__builtin_smull_overflow:
  9384. case Builtin::BI__builtin_smulll_overflow:
  9385. case Builtin::BI__builtin_umul_overflow:
  9386. case Builtin::BI__builtin_umull_overflow:
  9387. case Builtin::BI__builtin_umulll_overflow:
  9388. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  9389. : LHS.umul_ov(RHS, DidOverflow);
  9390. break;
  9391. }
  9392. // In the case where multiple sizes are allowed, truncate and see if
  9393. // the values are the same.
  9394. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9395. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9396. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9397. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  9398. // since it will give us the behavior of a TruncOrSelf in the case where
  9399. // its parameter <= its size. We previously set Result to be at least the
  9400. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  9401. // will work exactly like TruncOrSelf.
  9402. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  9403. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  9404. if (!APSInt::isSameValue(Temp, Result))
  9405. DidOverflow = true;
  9406. Result = Temp;
  9407. }
  9408. APValue APV{Result};
  9409. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  9410. return false;
  9411. return Success(DidOverflow, E);
  9412. }
  9413. }
  9414. }
  9415. /// Determine whether this is a pointer past the end of the complete
  9416. /// object referred to by the lvalue.
  9417. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  9418. const LValue &LV) {
  9419. // A null pointer can be viewed as being "past the end" but we don't
  9420. // choose to look at it that way here.
  9421. if (!LV.getLValueBase())
  9422. return false;
  9423. // If the designator is valid and refers to a subobject, we're not pointing
  9424. // past the end.
  9425. if (!LV.getLValueDesignator().Invalid &&
  9426. !LV.getLValueDesignator().isOnePastTheEnd())
  9427. return false;
  9428. // A pointer to an incomplete type might be past-the-end if the type's size is
  9429. // zero. We cannot tell because the type is incomplete.
  9430. QualType Ty = getType(LV.getLValueBase());
  9431. if (Ty->isIncompleteType())
  9432. return true;
  9433. // We're a past-the-end pointer if we point to the byte after the object,
  9434. // no matter what our type or path is.
  9435. auto Size = Ctx.getTypeSizeInChars(Ty);
  9436. return LV.getLValueOffset() == Size;
  9437. }
  9438. namespace {
  9439. /// Data recursive integer evaluator of certain binary operators.
  9440. ///
  9441. /// We use a data recursive algorithm for binary operators so that we are able
  9442. /// to handle extreme cases of chained binary operators without causing stack
  9443. /// overflow.
  9444. class DataRecursiveIntBinOpEvaluator {
  9445. struct EvalResult {
  9446. APValue Val;
  9447. bool Failed;
  9448. EvalResult() : Failed(false) { }
  9449. void swap(EvalResult &RHS) {
  9450. Val.swap(RHS.Val);
  9451. Failed = RHS.Failed;
  9452. RHS.Failed = false;
  9453. }
  9454. };
  9455. struct Job {
  9456. const Expr *E;
  9457. EvalResult LHSResult; // meaningful only for binary operator expression.
  9458. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  9459. Job() = default;
  9460. Job(Job &&) = default;
  9461. void startSpeculativeEval(EvalInfo &Info) {
  9462. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  9463. }
  9464. private:
  9465. SpeculativeEvaluationRAII SpecEvalRAII;
  9466. };
  9467. SmallVector<Job, 16> Queue;
  9468. IntExprEvaluator &IntEval;
  9469. EvalInfo &Info;
  9470. APValue &FinalResult;
  9471. public:
  9472. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  9473. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  9474. /// True if \param E is a binary operator that we are going to handle
  9475. /// data recursively.
  9476. /// We handle binary operators that are comma, logical, or that have operands
  9477. /// with integral or enumeration type.
  9478. static bool shouldEnqueue(const BinaryOperator *E) {
  9479. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  9480. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  9481. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9482. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9483. }
  9484. bool Traverse(const BinaryOperator *E) {
  9485. enqueue(E);
  9486. EvalResult PrevResult;
  9487. while (!Queue.empty())
  9488. process(PrevResult);
  9489. if (PrevResult.Failed) return false;
  9490. FinalResult.swap(PrevResult.Val);
  9491. return true;
  9492. }
  9493. private:
  9494. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  9495. return IntEval.Success(Value, E, Result);
  9496. }
  9497. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  9498. return IntEval.Success(Value, E, Result);
  9499. }
  9500. bool Error(const Expr *E) {
  9501. return IntEval.Error(E);
  9502. }
  9503. bool Error(const Expr *E, diag::kind D) {
  9504. return IntEval.Error(E, D);
  9505. }
  9506. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  9507. return Info.CCEDiag(E, D);
  9508. }
  9509. // Returns true if visiting the RHS is necessary, false otherwise.
  9510. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9511. bool &SuppressRHSDiags);
  9512. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9513. const BinaryOperator *E, APValue &Result);
  9514. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  9515. Result.Failed = !Evaluate(Result.Val, Info, E);
  9516. if (Result.Failed)
  9517. Result.Val = APValue();
  9518. }
  9519. void process(EvalResult &Result);
  9520. void enqueue(const Expr *E) {
  9521. E = E->IgnoreParens();
  9522. Queue.resize(Queue.size()+1);
  9523. Queue.back().E = E;
  9524. Queue.back().Kind = Job::AnyExprKind;
  9525. }
  9526. };
  9527. }
  9528. bool DataRecursiveIntBinOpEvaluator::
  9529. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9530. bool &SuppressRHSDiags) {
  9531. if (E->getOpcode() == BO_Comma) {
  9532. // Ignore LHS but note if we could not evaluate it.
  9533. if (LHSResult.Failed)
  9534. return Info.noteSideEffect();
  9535. return true;
  9536. }
  9537. if (E->isLogicalOp()) {
  9538. bool LHSAsBool;
  9539. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  9540. // We were able to evaluate the LHS, see if we can get away with not
  9541. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  9542. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  9543. Success(LHSAsBool, E, LHSResult.Val);
  9544. return false; // Ignore RHS
  9545. }
  9546. } else {
  9547. LHSResult.Failed = true;
  9548. // Since we weren't able to evaluate the left hand side, it
  9549. // might have had side effects.
  9550. if (!Info.noteSideEffect())
  9551. return false;
  9552. // We can't evaluate the LHS; however, sometimes the result
  9553. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9554. // Don't ignore RHS and suppress diagnostics from this arm.
  9555. SuppressRHSDiags = true;
  9556. }
  9557. return true;
  9558. }
  9559. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9560. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9561. if (LHSResult.Failed && !Info.noteFailure())
  9562. return false; // Ignore RHS;
  9563. return true;
  9564. }
  9565. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  9566. bool IsSub) {
  9567. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  9568. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  9569. // offsets.
  9570. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  9571. CharUnits &Offset = LVal.getLValueOffset();
  9572. uint64_t Offset64 = Offset.getQuantity();
  9573. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  9574. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  9575. : Offset64 + Index64);
  9576. }
  9577. bool DataRecursiveIntBinOpEvaluator::
  9578. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9579. const BinaryOperator *E, APValue &Result) {
  9580. if (E->getOpcode() == BO_Comma) {
  9581. if (RHSResult.Failed)
  9582. return false;
  9583. Result = RHSResult.Val;
  9584. return true;
  9585. }
  9586. if (E->isLogicalOp()) {
  9587. bool lhsResult, rhsResult;
  9588. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  9589. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  9590. if (LHSIsOK) {
  9591. if (RHSIsOK) {
  9592. if (E->getOpcode() == BO_LOr)
  9593. return Success(lhsResult || rhsResult, E, Result);
  9594. else
  9595. return Success(lhsResult && rhsResult, E, Result);
  9596. }
  9597. } else {
  9598. if (RHSIsOK) {
  9599. // We can't evaluate the LHS; however, sometimes the result
  9600. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9601. if (rhsResult == (E->getOpcode() == BO_LOr))
  9602. return Success(rhsResult, E, Result);
  9603. }
  9604. }
  9605. return false;
  9606. }
  9607. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9608. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9609. if (LHSResult.Failed || RHSResult.Failed)
  9610. return false;
  9611. const APValue &LHSVal = LHSResult.Val;
  9612. const APValue &RHSVal = RHSResult.Val;
  9613. // Handle cases like (unsigned long)&a + 4.
  9614. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  9615. Result = LHSVal;
  9616. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  9617. return true;
  9618. }
  9619. // Handle cases like 4 + (unsigned long)&a
  9620. if (E->getOpcode() == BO_Add &&
  9621. RHSVal.isLValue() && LHSVal.isInt()) {
  9622. Result = RHSVal;
  9623. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  9624. return true;
  9625. }
  9626. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  9627. // Handle (intptr_t)&&A - (intptr_t)&&B.
  9628. if (!LHSVal.getLValueOffset().isZero() ||
  9629. !RHSVal.getLValueOffset().isZero())
  9630. return false;
  9631. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  9632. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  9633. if (!LHSExpr || !RHSExpr)
  9634. return false;
  9635. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9636. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9637. if (!LHSAddrExpr || !RHSAddrExpr)
  9638. return false;
  9639. // Make sure both labels come from the same function.
  9640. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9641. RHSAddrExpr->getLabel()->getDeclContext())
  9642. return false;
  9643. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  9644. return true;
  9645. }
  9646. // All the remaining cases expect both operands to be an integer
  9647. if (!LHSVal.isInt() || !RHSVal.isInt())
  9648. return Error(E);
  9649. // Set up the width and signedness manually, in case it can't be deduced
  9650. // from the operation we're performing.
  9651. // FIXME: Don't do this in the cases where we can deduce it.
  9652. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  9653. E->getType()->isUnsignedIntegerOrEnumerationType());
  9654. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  9655. RHSVal.getInt(), Value))
  9656. return false;
  9657. return Success(Value, E, Result);
  9658. }
  9659. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  9660. Job &job = Queue.back();
  9661. switch (job.Kind) {
  9662. case Job::AnyExprKind: {
  9663. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  9664. if (shouldEnqueue(Bop)) {
  9665. job.Kind = Job::BinOpKind;
  9666. enqueue(Bop->getLHS());
  9667. return;
  9668. }
  9669. }
  9670. EvaluateExpr(job.E, Result);
  9671. Queue.pop_back();
  9672. return;
  9673. }
  9674. case Job::BinOpKind: {
  9675. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9676. bool SuppressRHSDiags = false;
  9677. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  9678. Queue.pop_back();
  9679. return;
  9680. }
  9681. if (SuppressRHSDiags)
  9682. job.startSpeculativeEval(Info);
  9683. job.LHSResult.swap(Result);
  9684. job.Kind = Job::BinOpVisitedLHSKind;
  9685. enqueue(Bop->getRHS());
  9686. return;
  9687. }
  9688. case Job::BinOpVisitedLHSKind: {
  9689. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9690. EvalResult RHS;
  9691. RHS.swap(Result);
  9692. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  9693. Queue.pop_back();
  9694. return;
  9695. }
  9696. }
  9697. llvm_unreachable("Invalid Job::Kind!");
  9698. }
  9699. namespace {
  9700. /// Used when we determine that we should fail, but can keep evaluating prior to
  9701. /// noting that we had a failure.
  9702. class DelayedNoteFailureRAII {
  9703. EvalInfo &Info;
  9704. bool NoteFailure;
  9705. public:
  9706. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  9707. : Info(Info), NoteFailure(NoteFailure) {}
  9708. ~DelayedNoteFailureRAII() {
  9709. if (NoteFailure) {
  9710. bool ContinueAfterFailure = Info.noteFailure();
  9711. (void)ContinueAfterFailure;
  9712. assert(ContinueAfterFailure &&
  9713. "Shouldn't have kept evaluating on failure.");
  9714. }
  9715. }
  9716. };
  9717. }
  9718. template <class SuccessCB, class AfterCB>
  9719. static bool
  9720. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  9721. SuccessCB &&Success, AfterCB &&DoAfter) {
  9722. assert(E->isComparisonOp() && "expected comparison operator");
  9723. assert((E->getOpcode() == BO_Cmp ||
  9724. E->getType()->isIntegralOrEnumerationType()) &&
  9725. "unsupported binary expression evaluation");
  9726. auto Error = [&](const Expr *E) {
  9727. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9728. return false;
  9729. };
  9730. using CCR = ComparisonCategoryResult;
  9731. bool IsRelational = E->isRelationalOp();
  9732. bool IsEquality = E->isEqualityOp();
  9733. if (E->getOpcode() == BO_Cmp) {
  9734. const ComparisonCategoryInfo &CmpInfo =
  9735. Info.Ctx.CompCategories.getInfoForType(E->getType());
  9736. IsRelational = CmpInfo.isOrdered();
  9737. IsEquality = CmpInfo.isEquality();
  9738. }
  9739. QualType LHSTy = E->getLHS()->getType();
  9740. QualType RHSTy = E->getRHS()->getType();
  9741. if (LHSTy->isIntegralOrEnumerationType() &&
  9742. RHSTy->isIntegralOrEnumerationType()) {
  9743. APSInt LHS, RHS;
  9744. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  9745. if (!LHSOK && !Info.noteFailure())
  9746. return false;
  9747. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  9748. return false;
  9749. if (LHS < RHS)
  9750. return Success(CCR::Less, E);
  9751. if (LHS > RHS)
  9752. return Success(CCR::Greater, E);
  9753. return Success(CCR::Equal, E);
  9754. }
  9755. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  9756. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  9757. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  9758. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  9759. if (!LHSOK && !Info.noteFailure())
  9760. return false;
  9761. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  9762. return false;
  9763. if (LHSFX < RHSFX)
  9764. return Success(CCR::Less, E);
  9765. if (LHSFX > RHSFX)
  9766. return Success(CCR::Greater, E);
  9767. return Success(CCR::Equal, E);
  9768. }
  9769. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  9770. ComplexValue LHS, RHS;
  9771. bool LHSOK;
  9772. if (E->isAssignmentOp()) {
  9773. LValue LV;
  9774. EvaluateLValue(E->getLHS(), LV, Info);
  9775. LHSOK = false;
  9776. } else if (LHSTy->isRealFloatingType()) {
  9777. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  9778. if (LHSOK) {
  9779. LHS.makeComplexFloat();
  9780. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  9781. }
  9782. } else {
  9783. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  9784. }
  9785. if (!LHSOK && !Info.noteFailure())
  9786. return false;
  9787. if (E->getRHS()->getType()->isRealFloatingType()) {
  9788. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  9789. return false;
  9790. RHS.makeComplexFloat();
  9791. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  9792. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  9793. return false;
  9794. if (LHS.isComplexFloat()) {
  9795. APFloat::cmpResult CR_r =
  9796. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  9797. APFloat::cmpResult CR_i =
  9798. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  9799. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  9800. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9801. } else {
  9802. assert(IsEquality && "invalid complex comparison");
  9803. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  9804. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  9805. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  9806. }
  9807. }
  9808. if (LHSTy->isRealFloatingType() &&
  9809. RHSTy->isRealFloatingType()) {
  9810. APFloat RHS(0.0), LHS(0.0);
  9811. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  9812. if (!LHSOK && !Info.noteFailure())
  9813. return false;
  9814. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  9815. return false;
  9816. assert(E->isComparisonOp() && "Invalid binary operator!");
  9817. auto GetCmpRes = [&]() {
  9818. switch (LHS.compare(RHS)) {
  9819. case APFloat::cmpEqual:
  9820. return CCR::Equal;
  9821. case APFloat::cmpLessThan:
  9822. return CCR::Less;
  9823. case APFloat::cmpGreaterThan:
  9824. return CCR::Greater;
  9825. case APFloat::cmpUnordered:
  9826. return CCR::Unordered;
  9827. }
  9828. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  9829. };
  9830. return Success(GetCmpRes(), E);
  9831. }
  9832. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  9833. LValue LHSValue, RHSValue;
  9834. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9835. if (!LHSOK && !Info.noteFailure())
  9836. return false;
  9837. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9838. return false;
  9839. // Reject differing bases from the normal codepath; we special-case
  9840. // comparisons to null.
  9841. if (!HasSameBase(LHSValue, RHSValue)) {
  9842. // Inequalities and subtractions between unrelated pointers have
  9843. // unspecified or undefined behavior.
  9844. if (!IsEquality)
  9845. return Error(E);
  9846. // A constant address may compare equal to the address of a symbol.
  9847. // The one exception is that address of an object cannot compare equal
  9848. // to a null pointer constant.
  9849. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  9850. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  9851. return Error(E);
  9852. // It's implementation-defined whether distinct literals will have
  9853. // distinct addresses. In clang, the result of such a comparison is
  9854. // unspecified, so it is not a constant expression. However, we do know
  9855. // that the address of a literal will be non-null.
  9856. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  9857. LHSValue.Base && RHSValue.Base)
  9858. return Error(E);
  9859. // We can't tell whether weak symbols will end up pointing to the same
  9860. // object.
  9861. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  9862. return Error(E);
  9863. // We can't compare the address of the start of one object with the
  9864. // past-the-end address of another object, per C++ DR1652.
  9865. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  9866. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  9867. (RHSValue.Base && RHSValue.Offset.isZero() &&
  9868. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  9869. return Error(E);
  9870. // We can't tell whether an object is at the same address as another
  9871. // zero sized object.
  9872. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  9873. (LHSValue.Base && isZeroSized(RHSValue)))
  9874. return Error(E);
  9875. return Success(CCR::Nonequal, E);
  9876. }
  9877. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9878. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9879. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9880. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9881. // C++11 [expr.rel]p3:
  9882. // Pointers to void (after pointer conversions) can be compared, with a
  9883. // result defined as follows: If both pointers represent the same
  9884. // address or are both the null pointer value, the result is true if the
  9885. // operator is <= or >= and false otherwise; otherwise the result is
  9886. // unspecified.
  9887. // We interpret this as applying to pointers to *cv* void.
  9888. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  9889. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  9890. // C++11 [expr.rel]p2:
  9891. // - If two pointers point to non-static data members of the same object,
  9892. // or to subobjects or array elements fo such members, recursively, the
  9893. // pointer to the later declared member compares greater provided the
  9894. // two members have the same access control and provided their class is
  9895. // not a union.
  9896. // [...]
  9897. // - Otherwise pointer comparisons are unspecified.
  9898. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  9899. bool WasArrayIndex;
  9900. unsigned Mismatch = FindDesignatorMismatch(
  9901. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  9902. // At the point where the designators diverge, the comparison has a
  9903. // specified value if:
  9904. // - we are comparing array indices
  9905. // - we are comparing fields of a union, or fields with the same access
  9906. // Otherwise, the result is unspecified and thus the comparison is not a
  9907. // constant expression.
  9908. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  9909. Mismatch < RHSDesignator.Entries.size()) {
  9910. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  9911. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  9912. if (!LF && !RF)
  9913. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  9914. else if (!LF)
  9915. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9916. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  9917. << RF->getParent() << RF;
  9918. else if (!RF)
  9919. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  9920. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  9921. << LF->getParent() << LF;
  9922. else if (!LF->getParent()->isUnion() &&
  9923. LF->getAccess() != RF->getAccess())
  9924. Info.CCEDiag(E,
  9925. diag::note_constexpr_pointer_comparison_differing_access)
  9926. << LF << LF->getAccess() << RF << RF->getAccess()
  9927. << LF->getParent();
  9928. }
  9929. }
  9930. // The comparison here must be unsigned, and performed with the same
  9931. // width as the pointer.
  9932. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  9933. uint64_t CompareLHS = LHSOffset.getQuantity();
  9934. uint64_t CompareRHS = RHSOffset.getQuantity();
  9935. assert(PtrSize <= 64 && "Unexpected pointer width");
  9936. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  9937. CompareLHS &= Mask;
  9938. CompareRHS &= Mask;
  9939. // If there is a base and this is a relational operator, we can only
  9940. // compare pointers within the object in question; otherwise, the result
  9941. // depends on where the object is located in memory.
  9942. if (!LHSValue.Base.isNull() && IsRelational) {
  9943. QualType BaseTy = getType(LHSValue.Base);
  9944. if (BaseTy->isIncompleteType())
  9945. return Error(E);
  9946. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  9947. uint64_t OffsetLimit = Size.getQuantity();
  9948. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  9949. return Error(E);
  9950. }
  9951. if (CompareLHS < CompareRHS)
  9952. return Success(CCR::Less, E);
  9953. if (CompareLHS > CompareRHS)
  9954. return Success(CCR::Greater, E);
  9955. return Success(CCR::Equal, E);
  9956. }
  9957. if (LHSTy->isMemberPointerType()) {
  9958. assert(IsEquality && "unexpected member pointer operation");
  9959. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  9960. MemberPtr LHSValue, RHSValue;
  9961. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  9962. if (!LHSOK && !Info.noteFailure())
  9963. return false;
  9964. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9965. return false;
  9966. // C++11 [expr.eq]p2:
  9967. // If both operands are null, they compare equal. Otherwise if only one is
  9968. // null, they compare unequal.
  9969. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  9970. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  9971. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  9972. }
  9973. // Otherwise if either is a pointer to a virtual member function, the
  9974. // result is unspecified.
  9975. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  9976. if (MD->isVirtual())
  9977. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  9978. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  9979. if (MD->isVirtual())
  9980. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  9981. // Otherwise they compare equal if and only if they would refer to the
  9982. // same member of the same most derived object or the same subobject if
  9983. // they were dereferenced with a hypothetical object of the associated
  9984. // class type.
  9985. bool Equal = LHSValue == RHSValue;
  9986. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  9987. }
  9988. if (LHSTy->isNullPtrType()) {
  9989. assert(E->isComparisonOp() && "unexpected nullptr operation");
  9990. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  9991. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  9992. // are compared, the result is true of the operator is <=, >= or ==, and
  9993. // false otherwise.
  9994. return Success(CCR::Equal, E);
  9995. }
  9996. return DoAfter();
  9997. }
  9998. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  9999. if (!CheckLiteralType(Info, E))
  10000. return false;
  10001. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  10002. const BinaryOperator *E) {
  10003. // Evaluation succeeded. Lookup the information for the comparison category
  10004. // type and fetch the VarDecl for the result.
  10005. const ComparisonCategoryInfo &CmpInfo =
  10006. Info.Ctx.CompCategories.getInfoForType(E->getType());
  10007. const VarDecl *VD =
  10008. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  10009. // Check and evaluate the result as a constant expression.
  10010. LValue LV;
  10011. LV.set(VD);
  10012. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  10013. return false;
  10014. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  10015. };
  10016. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  10017. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  10018. });
  10019. }
  10020. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10021. // We don't call noteFailure immediately because the assignment happens after
  10022. // we evaluate LHS and RHS.
  10023. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  10024. return Error(E);
  10025. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  10026. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  10027. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  10028. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  10029. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  10030. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  10031. if (E->isComparisonOp()) {
  10032. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  10033. // comparisons and then translating the result.
  10034. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  10035. const BinaryOperator *E) {
  10036. using CCR = ComparisonCategoryResult;
  10037. bool IsEqual = ResKind == CCR::Equal,
  10038. IsLess = ResKind == CCR::Less,
  10039. IsGreater = ResKind == CCR::Greater;
  10040. auto Op = E->getOpcode();
  10041. switch (Op) {
  10042. default:
  10043. llvm_unreachable("unsupported binary operator");
  10044. case BO_EQ:
  10045. case BO_NE:
  10046. return Success(IsEqual == (Op == BO_EQ), E);
  10047. case BO_LT: return Success(IsLess, E);
  10048. case BO_GT: return Success(IsGreater, E);
  10049. case BO_LE: return Success(IsEqual || IsLess, E);
  10050. case BO_GE: return Success(IsEqual || IsGreater, E);
  10051. }
  10052. };
  10053. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  10054. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10055. });
  10056. }
  10057. QualType LHSTy = E->getLHS()->getType();
  10058. QualType RHSTy = E->getRHS()->getType();
  10059. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  10060. E->getOpcode() == BO_Sub) {
  10061. LValue LHSValue, RHSValue;
  10062. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  10063. if (!LHSOK && !Info.noteFailure())
  10064. return false;
  10065. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10066. return false;
  10067. // Reject differing bases from the normal codepath; we special-case
  10068. // comparisons to null.
  10069. if (!HasSameBase(LHSValue, RHSValue)) {
  10070. // Handle &&A - &&B.
  10071. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  10072. return Error(E);
  10073. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  10074. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  10075. if (!LHSExpr || !RHSExpr)
  10076. return Error(E);
  10077. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  10078. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  10079. if (!LHSAddrExpr || !RHSAddrExpr)
  10080. return Error(E);
  10081. // Make sure both labels come from the same function.
  10082. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  10083. RHSAddrExpr->getLabel()->getDeclContext())
  10084. return Error(E);
  10085. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  10086. }
  10087. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  10088. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  10089. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  10090. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  10091. // C++11 [expr.add]p6:
  10092. // Unless both pointers point to elements of the same array object, or
  10093. // one past the last element of the array object, the behavior is
  10094. // undefined.
  10095. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  10096. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  10097. RHSDesignator))
  10098. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  10099. QualType Type = E->getLHS()->getType();
  10100. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  10101. CharUnits ElementSize;
  10102. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  10103. return false;
  10104. // As an extension, a type may have zero size (empty struct or union in
  10105. // C, array of zero length). Pointer subtraction in such cases has
  10106. // undefined behavior, so is not constant.
  10107. if (ElementSize.isZero()) {
  10108. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  10109. << ElementType;
  10110. return false;
  10111. }
  10112. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  10113. // and produce incorrect results when it overflows. Such behavior
  10114. // appears to be non-conforming, but is common, so perhaps we should
  10115. // assume the standard intended for such cases to be undefined behavior
  10116. // and check for them.
  10117. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  10118. // overflow in the final conversion to ptrdiff_t.
  10119. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  10120. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  10121. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  10122. false);
  10123. APSInt TrueResult = (LHS - RHS) / ElemSize;
  10124. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  10125. if (Result.extend(65) != TrueResult &&
  10126. !HandleOverflow(Info, E, TrueResult, E->getType()))
  10127. return false;
  10128. return Success(Result, E);
  10129. }
  10130. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10131. }
  10132. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  10133. /// a result as the expression's type.
  10134. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  10135. const UnaryExprOrTypeTraitExpr *E) {
  10136. switch(E->getKind()) {
  10137. case UETT_PreferredAlignOf:
  10138. case UETT_AlignOf: {
  10139. if (E->isArgumentType())
  10140. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  10141. E);
  10142. else
  10143. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  10144. E);
  10145. }
  10146. case UETT_VecStep: {
  10147. QualType Ty = E->getTypeOfArgument();
  10148. if (Ty->isVectorType()) {
  10149. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  10150. // The vec_step built-in functions that take a 3-component
  10151. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  10152. if (n == 3)
  10153. n = 4;
  10154. return Success(n, E);
  10155. } else
  10156. return Success(1, E);
  10157. }
  10158. case UETT_SizeOf: {
  10159. QualType SrcTy = E->getTypeOfArgument();
  10160. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  10161. // the result is the size of the referenced type."
  10162. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  10163. SrcTy = Ref->getPointeeType();
  10164. CharUnits Sizeof;
  10165. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  10166. return false;
  10167. return Success(Sizeof, E);
  10168. }
  10169. case UETT_OpenMPRequiredSimdAlign:
  10170. assert(E->isArgumentType());
  10171. return Success(
  10172. Info.Ctx.toCharUnitsFromBits(
  10173. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  10174. .getQuantity(),
  10175. E);
  10176. }
  10177. llvm_unreachable("unknown expr/type trait");
  10178. }
  10179. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  10180. CharUnits Result;
  10181. unsigned n = OOE->getNumComponents();
  10182. if (n == 0)
  10183. return Error(OOE);
  10184. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  10185. for (unsigned i = 0; i != n; ++i) {
  10186. OffsetOfNode ON = OOE->getComponent(i);
  10187. switch (ON.getKind()) {
  10188. case OffsetOfNode::Array: {
  10189. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  10190. APSInt IdxResult;
  10191. if (!EvaluateInteger(Idx, IdxResult, Info))
  10192. return false;
  10193. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  10194. if (!AT)
  10195. return Error(OOE);
  10196. CurrentType = AT->getElementType();
  10197. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  10198. Result += IdxResult.getSExtValue() * ElementSize;
  10199. break;
  10200. }
  10201. case OffsetOfNode::Field: {
  10202. FieldDecl *MemberDecl = ON.getField();
  10203. const RecordType *RT = CurrentType->getAs<RecordType>();
  10204. if (!RT)
  10205. return Error(OOE);
  10206. RecordDecl *RD = RT->getDecl();
  10207. if (RD->isInvalidDecl()) return false;
  10208. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10209. unsigned i = MemberDecl->getFieldIndex();
  10210. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  10211. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  10212. CurrentType = MemberDecl->getType().getNonReferenceType();
  10213. break;
  10214. }
  10215. case OffsetOfNode::Identifier:
  10216. llvm_unreachable("dependent __builtin_offsetof");
  10217. case OffsetOfNode::Base: {
  10218. CXXBaseSpecifier *BaseSpec = ON.getBase();
  10219. if (BaseSpec->isVirtual())
  10220. return Error(OOE);
  10221. // Find the layout of the class whose base we are looking into.
  10222. const RecordType *RT = CurrentType->getAs<RecordType>();
  10223. if (!RT)
  10224. return Error(OOE);
  10225. RecordDecl *RD = RT->getDecl();
  10226. if (RD->isInvalidDecl()) return false;
  10227. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10228. // Find the base class itself.
  10229. CurrentType = BaseSpec->getType();
  10230. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  10231. if (!BaseRT)
  10232. return Error(OOE);
  10233. // Add the offset to the base.
  10234. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  10235. break;
  10236. }
  10237. }
  10238. }
  10239. return Success(Result, OOE);
  10240. }
  10241. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10242. switch (E->getOpcode()) {
  10243. default:
  10244. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  10245. // See C99 6.6p3.
  10246. return Error(E);
  10247. case UO_Extension:
  10248. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  10249. // If so, we could clear the diagnostic ID.
  10250. return Visit(E->getSubExpr());
  10251. case UO_Plus:
  10252. // The result is just the value.
  10253. return Visit(E->getSubExpr());
  10254. case UO_Minus: {
  10255. if (!Visit(E->getSubExpr()))
  10256. return false;
  10257. if (!Result.isInt()) return Error(E);
  10258. const APSInt &Value = Result.getInt();
  10259. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  10260. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  10261. E->getType()))
  10262. return false;
  10263. return Success(-Value, E);
  10264. }
  10265. case UO_Not: {
  10266. if (!Visit(E->getSubExpr()))
  10267. return false;
  10268. if (!Result.isInt()) return Error(E);
  10269. return Success(~Result.getInt(), E);
  10270. }
  10271. case UO_LNot: {
  10272. bool bres;
  10273. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10274. return false;
  10275. return Success(!bres, E);
  10276. }
  10277. }
  10278. }
  10279. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  10280. /// result type is integer.
  10281. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10282. const Expr *SubExpr = E->getSubExpr();
  10283. QualType DestType = E->getType();
  10284. QualType SrcType = SubExpr->getType();
  10285. switch (E->getCastKind()) {
  10286. case CK_BaseToDerived:
  10287. case CK_DerivedToBase:
  10288. case CK_UncheckedDerivedToBase:
  10289. case CK_Dynamic:
  10290. case CK_ToUnion:
  10291. case CK_ArrayToPointerDecay:
  10292. case CK_FunctionToPointerDecay:
  10293. case CK_NullToPointer:
  10294. case CK_NullToMemberPointer:
  10295. case CK_BaseToDerivedMemberPointer:
  10296. case CK_DerivedToBaseMemberPointer:
  10297. case CK_ReinterpretMemberPointer:
  10298. case CK_ConstructorConversion:
  10299. case CK_IntegralToPointer:
  10300. case CK_ToVoid:
  10301. case CK_VectorSplat:
  10302. case CK_IntegralToFloating:
  10303. case CK_FloatingCast:
  10304. case CK_CPointerToObjCPointerCast:
  10305. case CK_BlockPointerToObjCPointerCast:
  10306. case CK_AnyPointerToBlockPointerCast:
  10307. case CK_ObjCObjectLValueCast:
  10308. case CK_FloatingRealToComplex:
  10309. case CK_FloatingComplexToReal:
  10310. case CK_FloatingComplexCast:
  10311. case CK_FloatingComplexToIntegralComplex:
  10312. case CK_IntegralRealToComplex:
  10313. case CK_IntegralComplexCast:
  10314. case CK_IntegralComplexToFloatingComplex:
  10315. case CK_BuiltinFnToFnPtr:
  10316. case CK_ZeroToOCLOpaqueType:
  10317. case CK_NonAtomicToAtomic:
  10318. case CK_AddressSpaceConversion:
  10319. case CK_IntToOCLSampler:
  10320. case CK_FixedPointCast:
  10321. case CK_IntegralToFixedPoint:
  10322. llvm_unreachable("invalid cast kind for integral value");
  10323. case CK_BitCast:
  10324. case CK_Dependent:
  10325. case CK_LValueBitCast:
  10326. case CK_ARCProduceObject:
  10327. case CK_ARCConsumeObject:
  10328. case CK_ARCReclaimReturnedObject:
  10329. case CK_ARCExtendBlockObject:
  10330. case CK_CopyAndAutoreleaseBlockObject:
  10331. return Error(E);
  10332. case CK_UserDefinedConversion:
  10333. case CK_LValueToRValue:
  10334. case CK_AtomicToNonAtomic:
  10335. case CK_NoOp:
  10336. case CK_LValueToRValueBitCast:
  10337. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10338. case CK_MemberPointerToBoolean:
  10339. case CK_PointerToBoolean:
  10340. case CK_IntegralToBoolean:
  10341. case CK_FloatingToBoolean:
  10342. case CK_BooleanToSignedIntegral:
  10343. case CK_FloatingComplexToBoolean:
  10344. case CK_IntegralComplexToBoolean: {
  10345. bool BoolResult;
  10346. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  10347. return false;
  10348. uint64_t IntResult = BoolResult;
  10349. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  10350. IntResult = (uint64_t)-1;
  10351. return Success(IntResult, E);
  10352. }
  10353. case CK_FixedPointToIntegral: {
  10354. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  10355. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10356. return false;
  10357. bool Overflowed;
  10358. llvm::APSInt Result = Src.convertToInt(
  10359. Info.Ctx.getIntWidth(DestType),
  10360. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  10361. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10362. return false;
  10363. return Success(Result, E);
  10364. }
  10365. case CK_FixedPointToBoolean: {
  10366. // Unsigned padding does not affect this.
  10367. APValue Val;
  10368. if (!Evaluate(Val, Info, SubExpr))
  10369. return false;
  10370. return Success(Val.getFixedPoint().getBoolValue(), E);
  10371. }
  10372. case CK_IntegralCast: {
  10373. if (!Visit(SubExpr))
  10374. return false;
  10375. if (!Result.isInt()) {
  10376. // Allow casts of address-of-label differences if they are no-ops
  10377. // or narrowing. (The narrowing case isn't actually guaranteed to
  10378. // be constant-evaluatable except in some narrow cases which are hard
  10379. // to detect here. We let it through on the assumption the user knows
  10380. // what they are doing.)
  10381. if (Result.isAddrLabelDiff())
  10382. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  10383. // Only allow casts of lvalues if they are lossless.
  10384. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  10385. }
  10386. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  10387. Result.getInt()), E);
  10388. }
  10389. case CK_PointerToIntegral: {
  10390. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  10391. LValue LV;
  10392. if (!EvaluatePointer(SubExpr, LV, Info))
  10393. return false;
  10394. if (LV.getLValueBase()) {
  10395. // Only allow based lvalue casts if they are lossless.
  10396. // FIXME: Allow a larger integer size than the pointer size, and allow
  10397. // narrowing back down to pointer width in subsequent integral casts.
  10398. // FIXME: Check integer type's active bits, not its type size.
  10399. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  10400. return Error(E);
  10401. LV.Designator.setInvalid();
  10402. LV.moveInto(Result);
  10403. return true;
  10404. }
  10405. APSInt AsInt;
  10406. APValue V;
  10407. LV.moveInto(V);
  10408. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  10409. llvm_unreachable("Can't cast this!");
  10410. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  10411. }
  10412. case CK_IntegralComplexToReal: {
  10413. ComplexValue C;
  10414. if (!EvaluateComplex(SubExpr, C, Info))
  10415. return false;
  10416. return Success(C.getComplexIntReal(), E);
  10417. }
  10418. case CK_FloatingToIntegral: {
  10419. APFloat F(0.0);
  10420. if (!EvaluateFloat(SubExpr, F, Info))
  10421. return false;
  10422. APSInt Value;
  10423. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  10424. return false;
  10425. return Success(Value, E);
  10426. }
  10427. }
  10428. llvm_unreachable("unknown cast resulting in integral value");
  10429. }
  10430. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10431. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10432. ComplexValue LV;
  10433. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10434. return false;
  10435. if (!LV.isComplexInt())
  10436. return Error(E);
  10437. return Success(LV.getComplexIntReal(), E);
  10438. }
  10439. return Visit(E->getSubExpr());
  10440. }
  10441. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10442. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  10443. ComplexValue LV;
  10444. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10445. return false;
  10446. if (!LV.isComplexInt())
  10447. return Error(E);
  10448. return Success(LV.getComplexIntImag(), E);
  10449. }
  10450. VisitIgnoredValue(E->getSubExpr());
  10451. return Success(0, E);
  10452. }
  10453. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  10454. return Success(E->getPackLength(), E);
  10455. }
  10456. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  10457. return Success(E->getValue(), E);
  10458. }
  10459. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10460. switch (E->getOpcode()) {
  10461. default:
  10462. // Invalid unary operators
  10463. return Error(E);
  10464. case UO_Plus:
  10465. // The result is just the value.
  10466. return Visit(E->getSubExpr());
  10467. case UO_Minus: {
  10468. if (!Visit(E->getSubExpr())) return false;
  10469. if (!Result.isFixedPoint())
  10470. return Error(E);
  10471. bool Overflowed;
  10472. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  10473. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  10474. return false;
  10475. return Success(Negated, E);
  10476. }
  10477. case UO_LNot: {
  10478. bool bres;
  10479. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10480. return false;
  10481. return Success(!bres, E);
  10482. }
  10483. }
  10484. }
  10485. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10486. const Expr *SubExpr = E->getSubExpr();
  10487. QualType DestType = E->getType();
  10488. assert(DestType->isFixedPointType() &&
  10489. "Expected destination type to be a fixed point type");
  10490. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  10491. switch (E->getCastKind()) {
  10492. case CK_FixedPointCast: {
  10493. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  10494. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10495. return false;
  10496. bool Overflowed;
  10497. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  10498. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10499. return false;
  10500. return Success(Result, E);
  10501. }
  10502. case CK_IntegralToFixedPoint: {
  10503. APSInt Src;
  10504. if (!EvaluateInteger(SubExpr, Src, Info))
  10505. return false;
  10506. bool Overflowed;
  10507. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10508. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  10509. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  10510. return false;
  10511. return Success(IntResult, E);
  10512. }
  10513. case CK_NoOp:
  10514. case CK_LValueToRValue:
  10515. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10516. default:
  10517. return Error(E);
  10518. }
  10519. }
  10520. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10521. const Expr *LHS = E->getLHS();
  10522. const Expr *RHS = E->getRHS();
  10523. FixedPointSemantics ResultFXSema =
  10524. Info.Ctx.getFixedPointSemantics(E->getType());
  10525. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  10526. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  10527. return false;
  10528. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  10529. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  10530. return false;
  10531. switch (E->getOpcode()) {
  10532. case BO_Add: {
  10533. bool AddOverflow, ConversionOverflow;
  10534. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  10535. .convert(ResultFXSema, &ConversionOverflow);
  10536. if ((AddOverflow || ConversionOverflow) &&
  10537. !HandleOverflow(Info, E, Result, E->getType()))
  10538. return false;
  10539. return Success(Result, E);
  10540. }
  10541. default:
  10542. return false;
  10543. }
  10544. llvm_unreachable("Should've exited before this");
  10545. }
  10546. //===----------------------------------------------------------------------===//
  10547. // Float Evaluation
  10548. //===----------------------------------------------------------------------===//
  10549. namespace {
  10550. class FloatExprEvaluator
  10551. : public ExprEvaluatorBase<FloatExprEvaluator> {
  10552. APFloat &Result;
  10553. public:
  10554. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  10555. : ExprEvaluatorBaseTy(info), Result(result) {}
  10556. bool Success(const APValue &V, const Expr *e) {
  10557. Result = V.getFloat();
  10558. return true;
  10559. }
  10560. bool ZeroInitialization(const Expr *E) {
  10561. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  10562. return true;
  10563. }
  10564. bool VisitCallExpr(const CallExpr *E);
  10565. bool VisitUnaryOperator(const UnaryOperator *E);
  10566. bool VisitBinaryOperator(const BinaryOperator *E);
  10567. bool VisitFloatingLiteral(const FloatingLiteral *E);
  10568. bool VisitCastExpr(const CastExpr *E);
  10569. bool VisitUnaryReal(const UnaryOperator *E);
  10570. bool VisitUnaryImag(const UnaryOperator *E);
  10571. // FIXME: Missing: array subscript of vector, member of vector
  10572. };
  10573. } // end anonymous namespace
  10574. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  10575. assert(E->isRValue() && E->getType()->isRealFloatingType());
  10576. return FloatExprEvaluator(Info, Result).Visit(E);
  10577. }
  10578. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  10579. QualType ResultTy,
  10580. const Expr *Arg,
  10581. bool SNaN,
  10582. llvm::APFloat &Result) {
  10583. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  10584. if (!S) return false;
  10585. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  10586. llvm::APInt fill;
  10587. // Treat empty strings as if they were zero.
  10588. if (S->getString().empty())
  10589. fill = llvm::APInt(32, 0);
  10590. else if (S->getString().getAsInteger(0, fill))
  10591. return false;
  10592. if (Context.getTargetInfo().isNan2008()) {
  10593. if (SNaN)
  10594. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10595. else
  10596. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10597. } else {
  10598. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  10599. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  10600. // a different encoding to what became a standard in 2008, and for pre-
  10601. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  10602. // sNaN. This is now known as "legacy NaN" encoding.
  10603. if (SNaN)
  10604. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10605. else
  10606. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10607. }
  10608. return true;
  10609. }
  10610. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  10611. switch (E->getBuiltinCallee()) {
  10612. default:
  10613. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10614. case Builtin::BI__builtin_huge_val:
  10615. case Builtin::BI__builtin_huge_valf:
  10616. case Builtin::BI__builtin_huge_vall:
  10617. case Builtin::BI__builtin_huge_valf128:
  10618. case Builtin::BI__builtin_inf:
  10619. case Builtin::BI__builtin_inff:
  10620. case Builtin::BI__builtin_infl:
  10621. case Builtin::BI__builtin_inff128: {
  10622. const llvm::fltSemantics &Sem =
  10623. Info.Ctx.getFloatTypeSemantics(E->getType());
  10624. Result = llvm::APFloat::getInf(Sem);
  10625. return true;
  10626. }
  10627. case Builtin::BI__builtin_nans:
  10628. case Builtin::BI__builtin_nansf:
  10629. case Builtin::BI__builtin_nansl:
  10630. case Builtin::BI__builtin_nansf128:
  10631. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10632. true, Result))
  10633. return Error(E);
  10634. return true;
  10635. case Builtin::BI__builtin_nan:
  10636. case Builtin::BI__builtin_nanf:
  10637. case Builtin::BI__builtin_nanl:
  10638. case Builtin::BI__builtin_nanf128:
  10639. // If this is __builtin_nan() turn this into a nan, otherwise we
  10640. // can't constant fold it.
  10641. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10642. false, Result))
  10643. return Error(E);
  10644. return true;
  10645. case Builtin::BI__builtin_fabs:
  10646. case Builtin::BI__builtin_fabsf:
  10647. case Builtin::BI__builtin_fabsl:
  10648. case Builtin::BI__builtin_fabsf128:
  10649. if (!EvaluateFloat(E->getArg(0), Result, Info))
  10650. return false;
  10651. if (Result.isNegative())
  10652. Result.changeSign();
  10653. return true;
  10654. // FIXME: Builtin::BI__builtin_powi
  10655. // FIXME: Builtin::BI__builtin_powif
  10656. // FIXME: Builtin::BI__builtin_powil
  10657. case Builtin::BI__builtin_copysign:
  10658. case Builtin::BI__builtin_copysignf:
  10659. case Builtin::BI__builtin_copysignl:
  10660. case Builtin::BI__builtin_copysignf128: {
  10661. APFloat RHS(0.);
  10662. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  10663. !EvaluateFloat(E->getArg(1), RHS, Info))
  10664. return false;
  10665. Result.copySign(RHS);
  10666. return true;
  10667. }
  10668. }
  10669. }
  10670. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10671. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10672. ComplexValue CV;
  10673. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10674. return false;
  10675. Result = CV.FloatReal;
  10676. return true;
  10677. }
  10678. return Visit(E->getSubExpr());
  10679. }
  10680. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10681. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10682. ComplexValue CV;
  10683. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10684. return false;
  10685. Result = CV.FloatImag;
  10686. return true;
  10687. }
  10688. VisitIgnoredValue(E->getSubExpr());
  10689. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  10690. Result = llvm::APFloat::getZero(Sem);
  10691. return true;
  10692. }
  10693. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10694. switch (E->getOpcode()) {
  10695. default: return Error(E);
  10696. case UO_Plus:
  10697. return EvaluateFloat(E->getSubExpr(), Result, Info);
  10698. case UO_Minus:
  10699. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  10700. return false;
  10701. Result.changeSign();
  10702. return true;
  10703. }
  10704. }
  10705. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10706. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10707. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10708. APFloat RHS(0.0);
  10709. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  10710. if (!LHSOK && !Info.noteFailure())
  10711. return false;
  10712. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  10713. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  10714. }
  10715. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  10716. Result = E->getValue();
  10717. return true;
  10718. }
  10719. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10720. const Expr* SubExpr = E->getSubExpr();
  10721. switch (E->getCastKind()) {
  10722. default:
  10723. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10724. case CK_IntegralToFloating: {
  10725. APSInt IntResult;
  10726. return EvaluateInteger(SubExpr, IntResult, Info) &&
  10727. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  10728. E->getType(), Result);
  10729. }
  10730. case CK_FloatingCast: {
  10731. if (!Visit(SubExpr))
  10732. return false;
  10733. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  10734. Result);
  10735. }
  10736. case CK_FloatingComplexToReal: {
  10737. ComplexValue V;
  10738. if (!EvaluateComplex(SubExpr, V, Info))
  10739. return false;
  10740. Result = V.getComplexFloatReal();
  10741. return true;
  10742. }
  10743. }
  10744. }
  10745. //===----------------------------------------------------------------------===//
  10746. // Complex Evaluation (for float and integer)
  10747. //===----------------------------------------------------------------------===//
  10748. namespace {
  10749. class ComplexExprEvaluator
  10750. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  10751. ComplexValue &Result;
  10752. public:
  10753. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  10754. : ExprEvaluatorBaseTy(info), Result(Result) {}
  10755. bool Success(const APValue &V, const Expr *e) {
  10756. Result.setFrom(V);
  10757. return true;
  10758. }
  10759. bool ZeroInitialization(const Expr *E);
  10760. //===--------------------------------------------------------------------===//
  10761. // Visitor Methods
  10762. //===--------------------------------------------------------------------===//
  10763. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  10764. bool VisitCastExpr(const CastExpr *E);
  10765. bool VisitBinaryOperator(const BinaryOperator *E);
  10766. bool VisitUnaryOperator(const UnaryOperator *E);
  10767. bool VisitInitListExpr(const InitListExpr *E);
  10768. };
  10769. } // end anonymous namespace
  10770. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  10771. EvalInfo &Info) {
  10772. assert(E->isRValue() && E->getType()->isAnyComplexType());
  10773. return ComplexExprEvaluator(Info, Result).Visit(E);
  10774. }
  10775. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  10776. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  10777. if (ElemTy->isRealFloatingType()) {
  10778. Result.makeComplexFloat();
  10779. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  10780. Result.FloatReal = Zero;
  10781. Result.FloatImag = Zero;
  10782. } else {
  10783. Result.makeComplexInt();
  10784. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  10785. Result.IntReal = Zero;
  10786. Result.IntImag = Zero;
  10787. }
  10788. return true;
  10789. }
  10790. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  10791. const Expr* SubExpr = E->getSubExpr();
  10792. if (SubExpr->getType()->isRealFloatingType()) {
  10793. Result.makeComplexFloat();
  10794. APFloat &Imag = Result.FloatImag;
  10795. if (!EvaluateFloat(SubExpr, Imag, Info))
  10796. return false;
  10797. Result.FloatReal = APFloat(Imag.getSemantics());
  10798. return true;
  10799. } else {
  10800. assert(SubExpr->getType()->isIntegerType() &&
  10801. "Unexpected imaginary literal.");
  10802. Result.makeComplexInt();
  10803. APSInt &Imag = Result.IntImag;
  10804. if (!EvaluateInteger(SubExpr, Imag, Info))
  10805. return false;
  10806. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  10807. return true;
  10808. }
  10809. }
  10810. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10811. switch (E->getCastKind()) {
  10812. case CK_BitCast:
  10813. case CK_BaseToDerived:
  10814. case CK_DerivedToBase:
  10815. case CK_UncheckedDerivedToBase:
  10816. case CK_Dynamic:
  10817. case CK_ToUnion:
  10818. case CK_ArrayToPointerDecay:
  10819. case CK_FunctionToPointerDecay:
  10820. case CK_NullToPointer:
  10821. case CK_NullToMemberPointer:
  10822. case CK_BaseToDerivedMemberPointer:
  10823. case CK_DerivedToBaseMemberPointer:
  10824. case CK_MemberPointerToBoolean:
  10825. case CK_ReinterpretMemberPointer:
  10826. case CK_ConstructorConversion:
  10827. case CK_IntegralToPointer:
  10828. case CK_PointerToIntegral:
  10829. case CK_PointerToBoolean:
  10830. case CK_ToVoid:
  10831. case CK_VectorSplat:
  10832. case CK_IntegralCast:
  10833. case CK_BooleanToSignedIntegral:
  10834. case CK_IntegralToBoolean:
  10835. case CK_IntegralToFloating:
  10836. case CK_FloatingToIntegral:
  10837. case CK_FloatingToBoolean:
  10838. case CK_FloatingCast:
  10839. case CK_CPointerToObjCPointerCast:
  10840. case CK_BlockPointerToObjCPointerCast:
  10841. case CK_AnyPointerToBlockPointerCast:
  10842. case CK_ObjCObjectLValueCast:
  10843. case CK_FloatingComplexToReal:
  10844. case CK_FloatingComplexToBoolean:
  10845. case CK_IntegralComplexToReal:
  10846. case CK_IntegralComplexToBoolean:
  10847. case CK_ARCProduceObject:
  10848. case CK_ARCConsumeObject:
  10849. case CK_ARCReclaimReturnedObject:
  10850. case CK_ARCExtendBlockObject:
  10851. case CK_CopyAndAutoreleaseBlockObject:
  10852. case CK_BuiltinFnToFnPtr:
  10853. case CK_ZeroToOCLOpaqueType:
  10854. case CK_NonAtomicToAtomic:
  10855. case CK_AddressSpaceConversion:
  10856. case CK_IntToOCLSampler:
  10857. case CK_FixedPointCast:
  10858. case CK_FixedPointToBoolean:
  10859. case CK_FixedPointToIntegral:
  10860. case CK_IntegralToFixedPoint:
  10861. llvm_unreachable("invalid cast kind for complex value");
  10862. case CK_LValueToRValue:
  10863. case CK_AtomicToNonAtomic:
  10864. case CK_NoOp:
  10865. case CK_LValueToRValueBitCast:
  10866. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10867. case CK_Dependent:
  10868. case CK_LValueBitCast:
  10869. case CK_UserDefinedConversion:
  10870. return Error(E);
  10871. case CK_FloatingRealToComplex: {
  10872. APFloat &Real = Result.FloatReal;
  10873. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  10874. return false;
  10875. Result.makeComplexFloat();
  10876. Result.FloatImag = APFloat(Real.getSemantics());
  10877. return true;
  10878. }
  10879. case CK_FloatingComplexCast: {
  10880. if (!Visit(E->getSubExpr()))
  10881. return false;
  10882. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10883. QualType From
  10884. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10885. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  10886. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  10887. }
  10888. case CK_FloatingComplexToIntegralComplex: {
  10889. if (!Visit(E->getSubExpr()))
  10890. return false;
  10891. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10892. QualType From
  10893. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10894. Result.makeComplexInt();
  10895. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  10896. To, Result.IntReal) &&
  10897. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  10898. To, Result.IntImag);
  10899. }
  10900. case CK_IntegralRealToComplex: {
  10901. APSInt &Real = Result.IntReal;
  10902. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  10903. return false;
  10904. Result.makeComplexInt();
  10905. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  10906. return true;
  10907. }
  10908. case CK_IntegralComplexCast: {
  10909. if (!Visit(E->getSubExpr()))
  10910. return false;
  10911. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  10912. QualType From
  10913. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  10914. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  10915. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  10916. return true;
  10917. }
  10918. case CK_IntegralComplexToFloatingComplex: {
  10919. if (!Visit(E->getSubExpr()))
  10920. return false;
  10921. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  10922. QualType From
  10923. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  10924. Result.makeComplexFloat();
  10925. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  10926. To, Result.FloatReal) &&
  10927. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  10928. To, Result.FloatImag);
  10929. }
  10930. }
  10931. llvm_unreachable("unknown cast resulting in complex value");
  10932. }
  10933. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10934. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  10935. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10936. // Track whether the LHS or RHS is real at the type system level. When this is
  10937. // the case we can simplify our evaluation strategy.
  10938. bool LHSReal = false, RHSReal = false;
  10939. bool LHSOK;
  10940. if (E->getLHS()->getType()->isRealFloatingType()) {
  10941. LHSReal = true;
  10942. APFloat &Real = Result.FloatReal;
  10943. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  10944. if (LHSOK) {
  10945. Result.makeComplexFloat();
  10946. Result.FloatImag = APFloat(Real.getSemantics());
  10947. }
  10948. } else {
  10949. LHSOK = Visit(E->getLHS());
  10950. }
  10951. if (!LHSOK && !Info.noteFailure())
  10952. return false;
  10953. ComplexValue RHS;
  10954. if (E->getRHS()->getType()->isRealFloatingType()) {
  10955. RHSReal = true;
  10956. APFloat &Real = RHS.FloatReal;
  10957. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  10958. return false;
  10959. RHS.makeComplexFloat();
  10960. RHS.FloatImag = APFloat(Real.getSemantics());
  10961. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  10962. return false;
  10963. assert(!(LHSReal && RHSReal) &&
  10964. "Cannot have both operands of a complex operation be real.");
  10965. switch (E->getOpcode()) {
  10966. default: return Error(E);
  10967. case BO_Add:
  10968. if (Result.isComplexFloat()) {
  10969. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  10970. APFloat::rmNearestTiesToEven);
  10971. if (LHSReal)
  10972. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  10973. else if (!RHSReal)
  10974. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  10975. APFloat::rmNearestTiesToEven);
  10976. } else {
  10977. Result.getComplexIntReal() += RHS.getComplexIntReal();
  10978. Result.getComplexIntImag() += RHS.getComplexIntImag();
  10979. }
  10980. break;
  10981. case BO_Sub:
  10982. if (Result.isComplexFloat()) {
  10983. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  10984. APFloat::rmNearestTiesToEven);
  10985. if (LHSReal) {
  10986. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  10987. Result.getComplexFloatImag().changeSign();
  10988. } else if (!RHSReal) {
  10989. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  10990. APFloat::rmNearestTiesToEven);
  10991. }
  10992. } else {
  10993. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  10994. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  10995. }
  10996. break;
  10997. case BO_Mul:
  10998. if (Result.isComplexFloat()) {
  10999. // This is an implementation of complex multiplication according to the
  11000. // constraints laid out in C11 Annex G. The implementation uses the
  11001. // following naming scheme:
  11002. // (a + ib) * (c + id)
  11003. ComplexValue LHS = Result;
  11004. APFloat &A = LHS.getComplexFloatReal();
  11005. APFloat &B = LHS.getComplexFloatImag();
  11006. APFloat &C = RHS.getComplexFloatReal();
  11007. APFloat &D = RHS.getComplexFloatImag();
  11008. APFloat &ResR = Result.getComplexFloatReal();
  11009. APFloat &ResI = Result.getComplexFloatImag();
  11010. if (LHSReal) {
  11011. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  11012. ResR = A * C;
  11013. ResI = A * D;
  11014. } else if (RHSReal) {
  11015. ResR = C * A;
  11016. ResI = C * B;
  11017. } else {
  11018. // In the fully general case, we need to handle NaNs and infinities
  11019. // robustly.
  11020. APFloat AC = A * C;
  11021. APFloat BD = B * D;
  11022. APFloat AD = A * D;
  11023. APFloat BC = B * C;
  11024. ResR = AC - BD;
  11025. ResI = AD + BC;
  11026. if (ResR.isNaN() && ResI.isNaN()) {
  11027. bool Recalc = false;
  11028. if (A.isInfinity() || B.isInfinity()) {
  11029. A = APFloat::copySign(
  11030. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11031. B = APFloat::copySign(
  11032. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11033. if (C.isNaN())
  11034. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  11035. if (D.isNaN())
  11036. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  11037. Recalc = true;
  11038. }
  11039. if (C.isInfinity() || D.isInfinity()) {
  11040. C = APFloat::copySign(
  11041. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11042. D = APFloat::copySign(
  11043. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11044. if (A.isNaN())
  11045. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  11046. if (B.isNaN())
  11047. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  11048. Recalc = true;
  11049. }
  11050. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  11051. AD.isInfinity() || BC.isInfinity())) {
  11052. if (A.isNaN())
  11053. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  11054. if (B.isNaN())
  11055. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  11056. if (C.isNaN())
  11057. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  11058. if (D.isNaN())
  11059. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  11060. Recalc = true;
  11061. }
  11062. if (Recalc) {
  11063. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  11064. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  11065. }
  11066. }
  11067. }
  11068. } else {
  11069. ComplexValue LHS = Result;
  11070. Result.getComplexIntReal() =
  11071. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  11072. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  11073. Result.getComplexIntImag() =
  11074. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  11075. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  11076. }
  11077. break;
  11078. case BO_Div:
  11079. if (Result.isComplexFloat()) {
  11080. // This is an implementation of complex division according to the
  11081. // constraints laid out in C11 Annex G. The implementation uses the
  11082. // following naming scheme:
  11083. // (a + ib) / (c + id)
  11084. ComplexValue LHS = Result;
  11085. APFloat &A = LHS.getComplexFloatReal();
  11086. APFloat &B = LHS.getComplexFloatImag();
  11087. APFloat &C = RHS.getComplexFloatReal();
  11088. APFloat &D = RHS.getComplexFloatImag();
  11089. APFloat &ResR = Result.getComplexFloatReal();
  11090. APFloat &ResI = Result.getComplexFloatImag();
  11091. if (RHSReal) {
  11092. ResR = A / C;
  11093. ResI = B / C;
  11094. } else {
  11095. if (LHSReal) {
  11096. // No real optimizations we can do here, stub out with zero.
  11097. B = APFloat::getZero(A.getSemantics());
  11098. }
  11099. int DenomLogB = 0;
  11100. APFloat MaxCD = maxnum(abs(C), abs(D));
  11101. if (MaxCD.isFinite()) {
  11102. DenomLogB = ilogb(MaxCD);
  11103. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  11104. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  11105. }
  11106. APFloat Denom = C * C + D * D;
  11107. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  11108. APFloat::rmNearestTiesToEven);
  11109. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  11110. APFloat::rmNearestTiesToEven);
  11111. if (ResR.isNaN() && ResI.isNaN()) {
  11112. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  11113. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  11114. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  11115. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  11116. D.isFinite()) {
  11117. A = APFloat::copySign(
  11118. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11119. B = APFloat::copySign(
  11120. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11121. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  11122. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  11123. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  11124. C = APFloat::copySign(
  11125. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11126. D = APFloat::copySign(
  11127. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11128. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  11129. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  11130. }
  11131. }
  11132. }
  11133. } else {
  11134. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  11135. return Error(E, diag::note_expr_divide_by_zero);
  11136. ComplexValue LHS = Result;
  11137. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11138. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  11139. Result.getComplexIntReal() =
  11140. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11141. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  11142. Result.getComplexIntImag() =
  11143. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  11144. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  11145. }
  11146. break;
  11147. }
  11148. return true;
  11149. }
  11150. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11151. // Get the operand value into 'Result'.
  11152. if (!Visit(E->getSubExpr()))
  11153. return false;
  11154. switch (E->getOpcode()) {
  11155. default:
  11156. return Error(E);
  11157. case UO_Extension:
  11158. return true;
  11159. case UO_Plus:
  11160. // The result is always just the subexpr.
  11161. return true;
  11162. case UO_Minus:
  11163. if (Result.isComplexFloat()) {
  11164. Result.getComplexFloatReal().changeSign();
  11165. Result.getComplexFloatImag().changeSign();
  11166. }
  11167. else {
  11168. Result.getComplexIntReal() = -Result.getComplexIntReal();
  11169. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11170. }
  11171. return true;
  11172. case UO_Not:
  11173. if (Result.isComplexFloat())
  11174. Result.getComplexFloatImag().changeSign();
  11175. else
  11176. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11177. return true;
  11178. }
  11179. }
  11180. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  11181. if (E->getNumInits() == 2) {
  11182. if (E->getType()->isComplexType()) {
  11183. Result.makeComplexFloat();
  11184. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  11185. return false;
  11186. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  11187. return false;
  11188. } else {
  11189. Result.makeComplexInt();
  11190. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  11191. return false;
  11192. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  11193. return false;
  11194. }
  11195. return true;
  11196. }
  11197. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  11198. }
  11199. //===----------------------------------------------------------------------===//
  11200. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  11201. // implicit conversion.
  11202. //===----------------------------------------------------------------------===//
  11203. namespace {
  11204. class AtomicExprEvaluator :
  11205. public ExprEvaluatorBase<AtomicExprEvaluator> {
  11206. const LValue *This;
  11207. APValue &Result;
  11208. public:
  11209. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  11210. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  11211. bool Success(const APValue &V, const Expr *E) {
  11212. Result = V;
  11213. return true;
  11214. }
  11215. bool ZeroInitialization(const Expr *E) {
  11216. ImplicitValueInitExpr VIE(
  11217. E->getType()->castAs<AtomicType>()->getValueType());
  11218. // For atomic-qualified class (and array) types in C++, initialize the
  11219. // _Atomic-wrapped subobject directly, in-place.
  11220. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  11221. : Evaluate(Result, Info, &VIE);
  11222. }
  11223. bool VisitCastExpr(const CastExpr *E) {
  11224. switch (E->getCastKind()) {
  11225. default:
  11226. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11227. case CK_NonAtomicToAtomic:
  11228. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  11229. : Evaluate(Result, Info, E->getSubExpr());
  11230. }
  11231. }
  11232. };
  11233. } // end anonymous namespace
  11234. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  11235. EvalInfo &Info) {
  11236. assert(E->isRValue() && E->getType()->isAtomicType());
  11237. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  11238. }
  11239. //===----------------------------------------------------------------------===//
  11240. // Void expression evaluation, primarily for a cast to void on the LHS of a
  11241. // comma operator
  11242. //===----------------------------------------------------------------------===//
  11243. namespace {
  11244. class VoidExprEvaluator
  11245. : public ExprEvaluatorBase<VoidExprEvaluator> {
  11246. public:
  11247. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  11248. bool Success(const APValue &V, const Expr *e) { return true; }
  11249. bool ZeroInitialization(const Expr *E) { return true; }
  11250. bool VisitCastExpr(const CastExpr *E) {
  11251. switch (E->getCastKind()) {
  11252. default:
  11253. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11254. case CK_ToVoid:
  11255. VisitIgnoredValue(E->getSubExpr());
  11256. return true;
  11257. }
  11258. }
  11259. bool VisitCallExpr(const CallExpr *E) {
  11260. switch (E->getBuiltinCallee()) {
  11261. default:
  11262. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  11263. case Builtin::BI__assume:
  11264. case Builtin::BI__builtin_assume:
  11265. // The argument is not evaluated!
  11266. return true;
  11267. }
  11268. }
  11269. bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
  11270. };
  11271. } // end anonymous namespace
  11272. static bool hasVirtualDestructor(QualType T) {
  11273. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  11274. if (CXXDestructorDecl *DD = RD->getDestructor())
  11275. return DD->isVirtual();
  11276. return false;
  11277. }
  11278. bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  11279. // We cannot speculatively evaluate a delete expression.
  11280. if (Info.SpeculativeEvaluationDepth)
  11281. return false;
  11282. FunctionDecl *OperatorDelete = E->getOperatorDelete();
  11283. if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
  11284. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  11285. << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
  11286. return false;
  11287. }
  11288. const Expr *Arg = E->getArgument();
  11289. LValue Pointer;
  11290. if (!EvaluatePointer(Arg, Pointer, Info))
  11291. return false;
  11292. if (Pointer.Designator.Invalid)
  11293. return false;
  11294. // Deleting a null pointer has no effect.
  11295. if (Pointer.isNullPointer()) {
  11296. // This is the only case where we need to produce an extension warning:
  11297. // the only other way we can succeed is if we find a dynamic allocation,
  11298. // and we will have warned when we allocated it in that case.
  11299. if (!Info.getLangOpts().CPlusPlus2a)
  11300. Info.CCEDiag(E, diag::note_constexpr_new);
  11301. return true;
  11302. }
  11303. auto PointerAsString = [&] {
  11304. APValue Printable;
  11305. Pointer.moveInto(Printable);
  11306. return Printable.getAsString(Info.Ctx, Arg->getType());
  11307. };
  11308. DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
  11309. if (!DA) {
  11310. Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
  11311. << PointerAsString();
  11312. if (Pointer.Base)
  11313. NoteLValueLocation(Info, Pointer.Base);
  11314. return false;
  11315. }
  11316. QualType AllocType = Pointer.Base.getDynamicAllocType();
  11317. Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
  11318. if (!Alloc) {
  11319. Info.FFDiag(E, diag::note_constexpr_double_delete);
  11320. return false;
  11321. }
  11322. if (E->isArrayForm() != AllocType->isConstantArrayType()) {
  11323. Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
  11324. << E->isArrayForm() << AllocType;
  11325. NoteLValueLocation(Info, Pointer.Base);
  11326. return false;
  11327. }
  11328. bool Subobject = false;
  11329. if (E->isArrayForm()) {
  11330. Subobject = Pointer.Designator.Entries.size() != 1 ||
  11331. Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
  11332. } else {
  11333. Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
  11334. Pointer.Designator.isOnePastTheEnd();
  11335. }
  11336. if (Subobject) {
  11337. Info.FFDiag(E, diag::note_constexpr_delete_subobject)
  11338. << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
  11339. return false;
  11340. }
  11341. // For the non-array case, the designator must be empty if the static type
  11342. // does not have a virtual destructor.
  11343. if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
  11344. !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
  11345. Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
  11346. << Arg->getType()->getPointeeType() << AllocType;
  11347. return false;
  11348. }
  11349. if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
  11350. (*Alloc)->Value, AllocType))
  11351. return false;
  11352. if (!Info.HeapAllocs.erase(DA)) {
  11353. // The element was already erased. This means the destructor call also
  11354. // deleted the object.
  11355. // FIXME: This probably results in undefined behavior before we get this
  11356. // far, and should be diagnosed elsewhere first.
  11357. Info.FFDiag(E, diag::note_constexpr_double_delete);
  11358. return false;
  11359. }
  11360. return true;
  11361. }
  11362. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  11363. assert(E->isRValue() && E->getType()->isVoidType());
  11364. return VoidExprEvaluator(Info).Visit(E);
  11365. }
  11366. //===----------------------------------------------------------------------===//
  11367. // Top level Expr::EvaluateAsRValue method.
  11368. //===----------------------------------------------------------------------===//
  11369. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  11370. // In C, function designators are not lvalues, but we evaluate them as if they
  11371. // are.
  11372. QualType T = E->getType();
  11373. if (E->isGLValue() || T->isFunctionType()) {
  11374. LValue LV;
  11375. if (!EvaluateLValue(E, LV, Info))
  11376. return false;
  11377. LV.moveInto(Result);
  11378. } else if (T->isVectorType()) {
  11379. if (!EvaluateVector(E, Result, Info))
  11380. return false;
  11381. } else if (T->isIntegralOrEnumerationType()) {
  11382. if (!IntExprEvaluator(Info, Result).Visit(E))
  11383. return false;
  11384. } else if (T->hasPointerRepresentation()) {
  11385. LValue LV;
  11386. if (!EvaluatePointer(E, LV, Info))
  11387. return false;
  11388. LV.moveInto(Result);
  11389. } else if (T->isRealFloatingType()) {
  11390. llvm::APFloat F(0.0);
  11391. if (!EvaluateFloat(E, F, Info))
  11392. return false;
  11393. Result = APValue(F);
  11394. } else if (T->isAnyComplexType()) {
  11395. ComplexValue C;
  11396. if (!EvaluateComplex(E, C, Info))
  11397. return false;
  11398. C.moveInto(Result);
  11399. } else if (T->isFixedPointType()) {
  11400. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  11401. } else if (T->isMemberPointerType()) {
  11402. MemberPtr P;
  11403. if (!EvaluateMemberPointer(E, P, Info))
  11404. return false;
  11405. P.moveInto(Result);
  11406. return true;
  11407. } else if (T->isArrayType()) {
  11408. LValue LV;
  11409. APValue &Value =
  11410. Info.CurrentCall->createTemporary(E, T, false, LV);
  11411. if (!EvaluateArray(E, LV, Value, Info))
  11412. return false;
  11413. Result = Value;
  11414. } else if (T->isRecordType()) {
  11415. LValue LV;
  11416. APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
  11417. if (!EvaluateRecord(E, LV, Value, Info))
  11418. return false;
  11419. Result = Value;
  11420. } else if (T->isVoidType()) {
  11421. if (!Info.getLangOpts().CPlusPlus11)
  11422. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  11423. << E->getType();
  11424. if (!EvaluateVoid(E, Info))
  11425. return false;
  11426. } else if (T->isAtomicType()) {
  11427. QualType Unqual = T.getAtomicUnqualifiedType();
  11428. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  11429. LValue LV;
  11430. APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
  11431. if (!EvaluateAtomic(E, &LV, Value, Info))
  11432. return false;
  11433. } else {
  11434. if (!EvaluateAtomic(E, nullptr, Result, Info))
  11435. return false;
  11436. }
  11437. } else if (Info.getLangOpts().CPlusPlus11) {
  11438. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  11439. return false;
  11440. } else {
  11441. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  11442. return false;
  11443. }
  11444. return true;
  11445. }
  11446. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  11447. /// cases, the in-place evaluation is essential, since later initializers for
  11448. /// an object can indirectly refer to subobjects which were initialized earlier.
  11449. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  11450. const Expr *E, bool AllowNonLiteralTypes) {
  11451. assert(!E->isValueDependent());
  11452. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  11453. return false;
  11454. if (E->isRValue()) {
  11455. // Evaluate arrays and record types in-place, so that later initializers can
  11456. // refer to earlier-initialized members of the object.
  11457. QualType T = E->getType();
  11458. if (T->isArrayType())
  11459. return EvaluateArray(E, This, Result, Info);
  11460. else if (T->isRecordType())
  11461. return EvaluateRecord(E, This, Result, Info);
  11462. else if (T->isAtomicType()) {
  11463. QualType Unqual = T.getAtomicUnqualifiedType();
  11464. if (Unqual->isArrayType() || Unqual->isRecordType())
  11465. return EvaluateAtomic(E, &This, Result, Info);
  11466. }
  11467. }
  11468. // For any other type, in-place evaluation is unimportant.
  11469. return Evaluate(Result, Info, E);
  11470. }
  11471. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  11472. /// lvalue-to-rvalue cast if it is an lvalue.
  11473. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  11474. if (Info.EnableNewConstInterp) {
  11475. auto &InterpCtx = Info.Ctx.getInterpContext();
  11476. switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
  11477. case interp::InterpResult::Success:
  11478. return true;
  11479. case interp::InterpResult::Fail:
  11480. return false;
  11481. case interp::InterpResult::Bail:
  11482. break;
  11483. }
  11484. }
  11485. if (E->getType().isNull())
  11486. return false;
  11487. if (!CheckLiteralType(Info, E))
  11488. return false;
  11489. if (!::Evaluate(Result, Info, E))
  11490. return false;
  11491. if (E->isGLValue()) {
  11492. LValue LV;
  11493. LV.setFrom(Info.Ctx, Result);
  11494. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  11495. return false;
  11496. }
  11497. // Check this core constant expression is a constant expression.
  11498. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
  11499. CheckMemoryLeaks(Info);
  11500. }
  11501. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  11502. const ASTContext &Ctx, bool &IsConst) {
  11503. // Fast-path evaluations of integer literals, since we sometimes see files
  11504. // containing vast quantities of these.
  11505. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  11506. Result.Val = APValue(APSInt(L->getValue(),
  11507. L->getType()->isUnsignedIntegerType()));
  11508. IsConst = true;
  11509. return true;
  11510. }
  11511. // This case should be rare, but we need to check it before we check on
  11512. // the type below.
  11513. if (Exp->getType().isNull()) {
  11514. IsConst = false;
  11515. return true;
  11516. }
  11517. // FIXME: Evaluating values of large array and record types can cause
  11518. // performance problems. Only do so in C++11 for now.
  11519. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  11520. Exp->getType()->isRecordType()) &&
  11521. !Ctx.getLangOpts().CPlusPlus11) {
  11522. IsConst = false;
  11523. return true;
  11524. }
  11525. return false;
  11526. }
  11527. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  11528. Expr::SideEffectsKind SEK) {
  11529. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  11530. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  11531. }
  11532. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  11533. const ASTContext &Ctx, EvalInfo &Info) {
  11534. bool IsConst;
  11535. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  11536. return IsConst;
  11537. return EvaluateAsRValue(Info, E, Result.Val);
  11538. }
  11539. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  11540. const ASTContext &Ctx,
  11541. Expr::SideEffectsKind AllowSideEffects,
  11542. EvalInfo &Info) {
  11543. if (!E->getType()->isIntegralOrEnumerationType())
  11544. return false;
  11545. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  11546. !ExprResult.Val.isInt() ||
  11547. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11548. return false;
  11549. return true;
  11550. }
  11551. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  11552. const ASTContext &Ctx,
  11553. Expr::SideEffectsKind AllowSideEffects,
  11554. EvalInfo &Info) {
  11555. if (!E->getType()->isFixedPointType())
  11556. return false;
  11557. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  11558. return false;
  11559. if (!ExprResult.Val.isFixedPoint() ||
  11560. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11561. return false;
  11562. return true;
  11563. }
  11564. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  11565. /// any crazy technique (that has nothing to do with language standards) that
  11566. /// we want to. If this function returns true, it returns the folded constant
  11567. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  11568. /// will be applied to the result.
  11569. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  11570. bool InConstantContext) const {
  11571. assert(!isValueDependent() &&
  11572. "Expression evaluator can't be called on a dependent expression.");
  11573. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11574. Info.InConstantContext = InConstantContext;
  11575. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  11576. }
  11577. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  11578. bool InConstantContext) const {
  11579. assert(!isValueDependent() &&
  11580. "Expression evaluator can't be called on a dependent expression.");
  11581. EvalResult Scratch;
  11582. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  11583. HandleConversionToBool(Scratch.Val, Result);
  11584. }
  11585. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  11586. SideEffectsKind AllowSideEffects,
  11587. bool InConstantContext) const {
  11588. assert(!isValueDependent() &&
  11589. "Expression evaluator can't be called on a dependent expression.");
  11590. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11591. Info.InConstantContext = InConstantContext;
  11592. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  11593. }
  11594. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  11595. SideEffectsKind AllowSideEffects,
  11596. bool InConstantContext) const {
  11597. assert(!isValueDependent() &&
  11598. "Expression evaluator can't be called on a dependent expression.");
  11599. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11600. Info.InConstantContext = InConstantContext;
  11601. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  11602. }
  11603. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  11604. SideEffectsKind AllowSideEffects,
  11605. bool InConstantContext) const {
  11606. assert(!isValueDependent() &&
  11607. "Expression evaluator can't be called on a dependent expression.");
  11608. if (!getType()->isRealFloatingType())
  11609. return false;
  11610. EvalResult ExprResult;
  11611. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  11612. !ExprResult.Val.isFloat() ||
  11613. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11614. return false;
  11615. Result = ExprResult.Val.getFloat();
  11616. return true;
  11617. }
  11618. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  11619. bool InConstantContext) const {
  11620. assert(!isValueDependent() &&
  11621. "Expression evaluator can't be called on a dependent expression.");
  11622. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  11623. Info.InConstantContext = InConstantContext;
  11624. LValue LV;
  11625. if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
  11626. Result.HasSideEffects ||
  11627. !CheckLValueConstantExpression(Info, getExprLoc(),
  11628. Ctx.getLValueReferenceType(getType()), LV,
  11629. Expr::EvaluateForCodeGen))
  11630. return false;
  11631. LV.moveInto(Result.Val);
  11632. return true;
  11633. }
  11634. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  11635. const ASTContext &Ctx) const {
  11636. assert(!isValueDependent() &&
  11637. "Expression evaluator can't be called on a dependent expression.");
  11638. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  11639. EvalInfo Info(Ctx, Result, EM);
  11640. Info.InConstantContext = true;
  11641. if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
  11642. return false;
  11643. if (!Info.discardCleanups())
  11644. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11645. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  11646. Usage) &&
  11647. CheckMemoryLeaks(Info);
  11648. }
  11649. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  11650. const VarDecl *VD,
  11651. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  11652. assert(!isValueDependent() &&
  11653. "Expression evaluator can't be called on a dependent expression.");
  11654. // FIXME: Evaluating initializers for large array and record types can cause
  11655. // performance problems. Only do so in C++11 for now.
  11656. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  11657. !Ctx.getLangOpts().CPlusPlus11)
  11658. return false;
  11659. Expr::EvalStatus EStatus;
  11660. EStatus.Diag = &Notes;
  11661. EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
  11662. ? EvalInfo::EM_ConstantExpression
  11663. : EvalInfo::EM_ConstantFold);
  11664. Info.setEvaluatingDecl(VD, Value);
  11665. Info.InConstantContext = true;
  11666. SourceLocation DeclLoc = VD->getLocation();
  11667. QualType DeclTy = VD->getType();
  11668. if (Info.EnableNewConstInterp) {
  11669. auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
  11670. switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
  11671. case interp::InterpResult::Fail:
  11672. // Bail out if an error was encountered.
  11673. return false;
  11674. case interp::InterpResult::Success:
  11675. // Evaluation succeeded and value was set.
  11676. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
  11677. case interp::InterpResult::Bail:
  11678. // Evaluate the value again for the tree evaluator to use.
  11679. break;
  11680. }
  11681. }
  11682. LValue LVal;
  11683. LVal.set(VD);
  11684. // C++11 [basic.start.init]p2:
  11685. // Variables with static storage duration or thread storage duration shall be
  11686. // zero-initialized before any other initialization takes place.
  11687. // This behavior is not present in C.
  11688. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  11689. !DeclTy->isReferenceType()) {
  11690. ImplicitValueInitExpr VIE(DeclTy);
  11691. if (!EvaluateInPlace(Value, Info, LVal, &VIE,
  11692. /*AllowNonLiteralTypes=*/true))
  11693. return false;
  11694. }
  11695. if (!EvaluateInPlace(Value, Info, LVal, this,
  11696. /*AllowNonLiteralTypes=*/true) ||
  11697. EStatus.HasSideEffects)
  11698. return false;
  11699. // At this point, any lifetime-extended temporaries are completely
  11700. // initialized.
  11701. Info.performLifetimeExtension();
  11702. if (!Info.discardCleanups())
  11703. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11704. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
  11705. CheckMemoryLeaks(Info);
  11706. }
  11707. bool VarDecl::evaluateDestruction(
  11708. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  11709. assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
  11710. "cannot evaluate destruction of non-constant-initialized variable");
  11711. Expr::EvalStatus EStatus;
  11712. EStatus.Diag = &Notes;
  11713. // Make a copy of the value for the destructor to mutate.
  11714. APValue DestroyedValue = *getEvaluatedValue();
  11715. EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
  11716. Info.setEvaluatingDecl(this, DestroyedValue,
  11717. EvalInfo::EvaluatingDeclKind::Dtor);
  11718. Info.InConstantContext = true;
  11719. SourceLocation DeclLoc = getLocation();
  11720. QualType DeclTy = getType();
  11721. LValue LVal;
  11722. LVal.set(this);
  11723. // FIXME: Consider storing whether this variable has constant destruction in
  11724. // the EvaluatedStmt so that CodeGen can query it.
  11725. if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
  11726. EStatus.HasSideEffects)
  11727. return false;
  11728. if (!Info.discardCleanups())
  11729. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11730. ensureEvaluatedStmt()->HasConstantDestruction = true;
  11731. return true;
  11732. }
  11733. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  11734. /// constant folded, but discard the result.
  11735. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  11736. assert(!isValueDependent() &&
  11737. "Expression evaluator can't be called on a dependent expression.");
  11738. EvalResult Result;
  11739. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  11740. !hasUnacceptableSideEffect(Result, SEK);
  11741. }
  11742. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  11743. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  11744. assert(!isValueDependent() &&
  11745. "Expression evaluator can't be called on a dependent expression.");
  11746. EvalResult EVResult;
  11747. EVResult.Diag = Diag;
  11748. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11749. Info.InConstantContext = true;
  11750. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  11751. (void)Result;
  11752. assert(Result && "Could not evaluate expression");
  11753. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  11754. return EVResult.Val.getInt();
  11755. }
  11756. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  11757. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  11758. assert(!isValueDependent() &&
  11759. "Expression evaluator can't be called on a dependent expression.");
  11760. EvalResult EVResult;
  11761. EVResult.Diag = Diag;
  11762. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11763. Info.InConstantContext = true;
  11764. Info.CheckingForUndefinedBehavior = true;
  11765. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  11766. (void)Result;
  11767. assert(Result && "Could not evaluate expression");
  11768. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  11769. return EVResult.Val.getInt();
  11770. }
  11771. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  11772. assert(!isValueDependent() &&
  11773. "Expression evaluator can't be called on a dependent expression.");
  11774. bool IsConst;
  11775. EvalResult EVResult;
  11776. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  11777. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  11778. Info.CheckingForUndefinedBehavior = true;
  11779. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  11780. }
  11781. }
  11782. bool Expr::EvalResult::isGlobalLValue() const {
  11783. assert(Val.isLValue());
  11784. return IsGlobalLValue(Val.getLValueBase());
  11785. }
  11786. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  11787. /// an integer constant expression.
  11788. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  11789. /// comma, etc
  11790. // CheckICE - This function does the fundamental ICE checking: the returned
  11791. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  11792. // and a (possibly null) SourceLocation indicating the location of the problem.
  11793. //
  11794. // Note that to reduce code duplication, this helper does no evaluation
  11795. // itself; the caller checks whether the expression is evaluatable, and
  11796. // in the rare cases where CheckICE actually cares about the evaluated
  11797. // value, it calls into Evaluate.
  11798. namespace {
  11799. enum ICEKind {
  11800. /// This expression is an ICE.
  11801. IK_ICE,
  11802. /// This expression is not an ICE, but if it isn't evaluated, it's
  11803. /// a legal subexpression for an ICE. This return value is used to handle
  11804. /// the comma operator in C99 mode, and non-constant subexpressions.
  11805. IK_ICEIfUnevaluated,
  11806. /// This expression is not an ICE, and is not a legal subexpression for one.
  11807. IK_NotICE
  11808. };
  11809. struct ICEDiag {
  11810. ICEKind Kind;
  11811. SourceLocation Loc;
  11812. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  11813. };
  11814. }
  11815. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  11816. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  11817. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  11818. Expr::EvalResult EVResult;
  11819. Expr::EvalStatus Status;
  11820. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  11821. Info.InConstantContext = true;
  11822. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  11823. !EVResult.Val.isInt())
  11824. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11825. return NoDiag();
  11826. }
  11827. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  11828. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  11829. if (!E->getType()->isIntegralOrEnumerationType())
  11830. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11831. switch (E->getStmtClass()) {
  11832. #define ABSTRACT_STMT(Node)
  11833. #define STMT(Node, Base) case Expr::Node##Class:
  11834. #define EXPR(Node, Base)
  11835. #include "clang/AST/StmtNodes.inc"
  11836. case Expr::PredefinedExprClass:
  11837. case Expr::FloatingLiteralClass:
  11838. case Expr::ImaginaryLiteralClass:
  11839. case Expr::StringLiteralClass:
  11840. case Expr::ArraySubscriptExprClass:
  11841. case Expr::OMPArraySectionExprClass:
  11842. case Expr::MemberExprClass:
  11843. case Expr::CompoundAssignOperatorClass:
  11844. case Expr::CompoundLiteralExprClass:
  11845. case Expr::ExtVectorElementExprClass:
  11846. case Expr::DesignatedInitExprClass:
  11847. case Expr::ArrayInitLoopExprClass:
  11848. case Expr::ArrayInitIndexExprClass:
  11849. case Expr::NoInitExprClass:
  11850. case Expr::DesignatedInitUpdateExprClass:
  11851. case Expr::ImplicitValueInitExprClass:
  11852. case Expr::ParenListExprClass:
  11853. case Expr::VAArgExprClass:
  11854. case Expr::AddrLabelExprClass:
  11855. case Expr::StmtExprClass:
  11856. case Expr::CXXMemberCallExprClass:
  11857. case Expr::CUDAKernelCallExprClass:
  11858. case Expr::CXXDynamicCastExprClass:
  11859. case Expr::CXXTypeidExprClass:
  11860. case Expr::CXXUuidofExprClass:
  11861. case Expr::MSPropertyRefExprClass:
  11862. case Expr::MSPropertySubscriptExprClass:
  11863. case Expr::CXXNullPtrLiteralExprClass:
  11864. case Expr::UserDefinedLiteralClass:
  11865. case Expr::CXXThisExprClass:
  11866. case Expr::CXXThrowExprClass:
  11867. case Expr::CXXNewExprClass:
  11868. case Expr::CXXDeleteExprClass:
  11869. case Expr::CXXPseudoDestructorExprClass:
  11870. case Expr::UnresolvedLookupExprClass:
  11871. case Expr::TypoExprClass:
  11872. case Expr::DependentScopeDeclRefExprClass:
  11873. case Expr::CXXConstructExprClass:
  11874. case Expr::CXXInheritedCtorInitExprClass:
  11875. case Expr::CXXStdInitializerListExprClass:
  11876. case Expr::CXXBindTemporaryExprClass:
  11877. case Expr::ExprWithCleanupsClass:
  11878. case Expr::CXXTemporaryObjectExprClass:
  11879. case Expr::CXXUnresolvedConstructExprClass:
  11880. case Expr::CXXDependentScopeMemberExprClass:
  11881. case Expr::UnresolvedMemberExprClass:
  11882. case Expr::ObjCStringLiteralClass:
  11883. case Expr::ObjCBoxedExprClass:
  11884. case Expr::ObjCArrayLiteralClass:
  11885. case Expr::ObjCDictionaryLiteralClass:
  11886. case Expr::ObjCEncodeExprClass:
  11887. case Expr::ObjCMessageExprClass:
  11888. case Expr::ObjCSelectorExprClass:
  11889. case Expr::ObjCProtocolExprClass:
  11890. case Expr::ObjCIvarRefExprClass:
  11891. case Expr::ObjCPropertyRefExprClass:
  11892. case Expr::ObjCSubscriptRefExprClass:
  11893. case Expr::ObjCIsaExprClass:
  11894. case Expr::ObjCAvailabilityCheckExprClass:
  11895. case Expr::ShuffleVectorExprClass:
  11896. case Expr::ConvertVectorExprClass:
  11897. case Expr::BlockExprClass:
  11898. case Expr::NoStmtClass:
  11899. case Expr::OpaqueValueExprClass:
  11900. case Expr::PackExpansionExprClass:
  11901. case Expr::SubstNonTypeTemplateParmPackExprClass:
  11902. case Expr::FunctionParmPackExprClass:
  11903. case Expr::AsTypeExprClass:
  11904. case Expr::ObjCIndirectCopyRestoreExprClass:
  11905. case Expr::MaterializeTemporaryExprClass:
  11906. case Expr::PseudoObjectExprClass:
  11907. case Expr::AtomicExprClass:
  11908. case Expr::LambdaExprClass:
  11909. case Expr::CXXFoldExprClass:
  11910. case Expr::CoawaitExprClass:
  11911. case Expr::DependentCoawaitExprClass:
  11912. case Expr::CoyieldExprClass:
  11913. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11914. case Expr::InitListExprClass: {
  11915. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  11916. // form "T x = { a };" is equivalent to "T x = a;".
  11917. // Unless we're initializing a reference, T is a scalar as it is known to be
  11918. // of integral or enumeration type.
  11919. if (E->isRValue())
  11920. if (cast<InitListExpr>(E)->getNumInits() == 1)
  11921. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  11922. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11923. }
  11924. case Expr::SizeOfPackExprClass:
  11925. case Expr::GNUNullExprClass:
  11926. case Expr::SourceLocExprClass:
  11927. return NoDiag();
  11928. case Expr::SubstNonTypeTemplateParmExprClass:
  11929. return
  11930. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  11931. case Expr::ConstantExprClass:
  11932. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  11933. case Expr::ParenExprClass:
  11934. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  11935. case Expr::GenericSelectionExprClass:
  11936. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  11937. case Expr::IntegerLiteralClass:
  11938. case Expr::FixedPointLiteralClass:
  11939. case Expr::CharacterLiteralClass:
  11940. case Expr::ObjCBoolLiteralExprClass:
  11941. case Expr::CXXBoolLiteralExprClass:
  11942. case Expr::CXXScalarValueInitExprClass:
  11943. case Expr::TypeTraitExprClass:
  11944. case Expr::ArrayTypeTraitExprClass:
  11945. case Expr::ExpressionTraitExprClass:
  11946. case Expr::CXXNoexceptExprClass:
  11947. return NoDiag();
  11948. case Expr::CallExprClass:
  11949. case Expr::CXXOperatorCallExprClass: {
  11950. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  11951. // constant expressions, but they can never be ICEs because an ICE cannot
  11952. // contain an operand of (pointer to) function type.
  11953. const CallExpr *CE = cast<CallExpr>(E);
  11954. if (CE->getBuiltinCallee())
  11955. return CheckEvalInICE(E, Ctx);
  11956. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11957. }
  11958. case Expr::DeclRefExprClass: {
  11959. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  11960. return NoDiag();
  11961. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  11962. if (Ctx.getLangOpts().CPlusPlus &&
  11963. D && IsConstNonVolatile(D->getType())) {
  11964. // Parameter variables are never constants. Without this check,
  11965. // getAnyInitializer() can find a default argument, which leads
  11966. // to chaos.
  11967. if (isa<ParmVarDecl>(D))
  11968. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11969. // C++ 7.1.5.1p2
  11970. // A variable of non-volatile const-qualified integral or enumeration
  11971. // type initialized by an ICE can be used in ICEs.
  11972. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  11973. if (!Dcl->getType()->isIntegralOrEnumerationType())
  11974. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11975. const VarDecl *VD;
  11976. // Look for a declaration of this variable that has an initializer, and
  11977. // check whether it is an ICE.
  11978. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  11979. return NoDiag();
  11980. else
  11981. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  11982. }
  11983. }
  11984. return ICEDiag(IK_NotICE, E->getBeginLoc());
  11985. }
  11986. case Expr::UnaryOperatorClass: {
  11987. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  11988. switch (Exp->getOpcode()) {
  11989. case UO_PostInc:
  11990. case UO_PostDec:
  11991. case UO_PreInc:
  11992. case UO_PreDec:
  11993. case UO_AddrOf:
  11994. case UO_Deref:
  11995. case UO_Coawait:
  11996. // C99 6.6/3 allows increment and decrement within unevaluated
  11997. // subexpressions of constant expressions, but they can never be ICEs
  11998. // because an ICE cannot contain an lvalue operand.
  11999. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12000. case UO_Extension:
  12001. case UO_LNot:
  12002. case UO_Plus:
  12003. case UO_Minus:
  12004. case UO_Not:
  12005. case UO_Real:
  12006. case UO_Imag:
  12007. return CheckICE(Exp->getSubExpr(), Ctx);
  12008. }
  12009. llvm_unreachable("invalid unary operator class");
  12010. }
  12011. case Expr::OffsetOfExprClass: {
  12012. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  12013. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  12014. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  12015. // compliance: we should warn earlier for offsetof expressions with
  12016. // array subscripts that aren't ICEs, and if the array subscripts
  12017. // are ICEs, the value of the offsetof must be an integer constant.
  12018. return CheckEvalInICE(E, Ctx);
  12019. }
  12020. case Expr::UnaryExprOrTypeTraitExprClass: {
  12021. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  12022. if ((Exp->getKind() == UETT_SizeOf) &&
  12023. Exp->getTypeOfArgument()->isVariableArrayType())
  12024. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12025. return NoDiag();
  12026. }
  12027. case Expr::BinaryOperatorClass: {
  12028. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  12029. switch (Exp->getOpcode()) {
  12030. case BO_PtrMemD:
  12031. case BO_PtrMemI:
  12032. case BO_Assign:
  12033. case BO_MulAssign:
  12034. case BO_DivAssign:
  12035. case BO_RemAssign:
  12036. case BO_AddAssign:
  12037. case BO_SubAssign:
  12038. case BO_ShlAssign:
  12039. case BO_ShrAssign:
  12040. case BO_AndAssign:
  12041. case BO_XorAssign:
  12042. case BO_OrAssign:
  12043. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  12044. // constant expressions, but they can never be ICEs because an ICE cannot
  12045. // contain an lvalue operand.
  12046. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12047. case BO_Mul:
  12048. case BO_Div:
  12049. case BO_Rem:
  12050. case BO_Add:
  12051. case BO_Sub:
  12052. case BO_Shl:
  12053. case BO_Shr:
  12054. case BO_LT:
  12055. case BO_GT:
  12056. case BO_LE:
  12057. case BO_GE:
  12058. case BO_EQ:
  12059. case BO_NE:
  12060. case BO_And:
  12061. case BO_Xor:
  12062. case BO_Or:
  12063. case BO_Comma:
  12064. case BO_Cmp: {
  12065. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  12066. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  12067. if (Exp->getOpcode() == BO_Div ||
  12068. Exp->getOpcode() == BO_Rem) {
  12069. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  12070. // we don't evaluate one.
  12071. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  12072. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  12073. if (REval == 0)
  12074. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12075. if (REval.isSigned() && REval.isAllOnesValue()) {
  12076. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  12077. if (LEval.isMinSignedValue())
  12078. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12079. }
  12080. }
  12081. }
  12082. if (Exp->getOpcode() == BO_Comma) {
  12083. if (Ctx.getLangOpts().C99) {
  12084. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  12085. // if it isn't evaluated.
  12086. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  12087. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12088. } else {
  12089. // In both C89 and C++, commas in ICEs are illegal.
  12090. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12091. }
  12092. }
  12093. return Worst(LHSResult, RHSResult);
  12094. }
  12095. case BO_LAnd:
  12096. case BO_LOr: {
  12097. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  12098. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  12099. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  12100. // Rare case where the RHS has a comma "side-effect"; we need
  12101. // to actually check the condition to see whether the side
  12102. // with the comma is evaluated.
  12103. if ((Exp->getOpcode() == BO_LAnd) !=
  12104. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  12105. return RHSResult;
  12106. return NoDiag();
  12107. }
  12108. return Worst(LHSResult, RHSResult);
  12109. }
  12110. }
  12111. llvm_unreachable("invalid binary operator kind");
  12112. }
  12113. case Expr::ImplicitCastExprClass:
  12114. case Expr::CStyleCastExprClass:
  12115. case Expr::CXXFunctionalCastExprClass:
  12116. case Expr::CXXStaticCastExprClass:
  12117. case Expr::CXXReinterpretCastExprClass:
  12118. case Expr::CXXConstCastExprClass:
  12119. case Expr::ObjCBridgedCastExprClass: {
  12120. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  12121. if (isa<ExplicitCastExpr>(E)) {
  12122. if (const FloatingLiteral *FL
  12123. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  12124. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  12125. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  12126. APSInt IgnoredVal(DestWidth, !DestSigned);
  12127. bool Ignored;
  12128. // If the value does not fit in the destination type, the behavior is
  12129. // undefined, so we are not required to treat it as a constant
  12130. // expression.
  12131. if (FL->getValue().convertToInteger(IgnoredVal,
  12132. llvm::APFloat::rmTowardZero,
  12133. &Ignored) & APFloat::opInvalidOp)
  12134. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12135. return NoDiag();
  12136. }
  12137. }
  12138. switch (cast<CastExpr>(E)->getCastKind()) {
  12139. case CK_LValueToRValue:
  12140. case CK_AtomicToNonAtomic:
  12141. case CK_NonAtomicToAtomic:
  12142. case CK_NoOp:
  12143. case CK_IntegralToBoolean:
  12144. case CK_IntegralCast:
  12145. return CheckICE(SubExpr, Ctx);
  12146. default:
  12147. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12148. }
  12149. }
  12150. case Expr::BinaryConditionalOperatorClass: {
  12151. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  12152. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  12153. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  12154. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12155. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  12156. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  12157. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  12158. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  12159. return FalseResult;
  12160. }
  12161. case Expr::ConditionalOperatorClass: {
  12162. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  12163. // If the condition (ignoring parens) is a __builtin_constant_p call,
  12164. // then only the true side is actually considered in an integer constant
  12165. // expression, and it is fully evaluated. This is an important GNU
  12166. // extension. See GCC PR38377 for discussion.
  12167. if (const CallExpr *CallCE
  12168. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  12169. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  12170. return CheckEvalInICE(E, Ctx);
  12171. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  12172. if (CondResult.Kind == IK_NotICE)
  12173. return CondResult;
  12174. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  12175. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12176. if (TrueResult.Kind == IK_NotICE)
  12177. return TrueResult;
  12178. if (FalseResult.Kind == IK_NotICE)
  12179. return FalseResult;
  12180. if (CondResult.Kind == IK_ICEIfUnevaluated)
  12181. return CondResult;
  12182. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  12183. return NoDiag();
  12184. // Rare case where the diagnostics depend on which side is evaluated
  12185. // Note that if we get here, CondResult is 0, and at least one of
  12186. // TrueResult and FalseResult is non-zero.
  12187. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  12188. return FalseResult;
  12189. return TrueResult;
  12190. }
  12191. case Expr::CXXDefaultArgExprClass:
  12192. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  12193. case Expr::CXXDefaultInitExprClass:
  12194. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  12195. case Expr::ChooseExprClass: {
  12196. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  12197. }
  12198. case Expr::BuiltinBitCastExprClass: {
  12199. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  12200. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12201. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  12202. }
  12203. }
  12204. llvm_unreachable("Invalid StmtClass!");
  12205. }
  12206. /// Evaluate an expression as a C++11 integral constant expression.
  12207. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  12208. const Expr *E,
  12209. llvm::APSInt *Value,
  12210. SourceLocation *Loc) {
  12211. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12212. if (Loc) *Loc = E->getExprLoc();
  12213. return false;
  12214. }
  12215. APValue Result;
  12216. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  12217. return false;
  12218. if (!Result.isInt()) {
  12219. if (Loc) *Loc = E->getExprLoc();
  12220. return false;
  12221. }
  12222. if (Value) *Value = Result.getInt();
  12223. return true;
  12224. }
  12225. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  12226. SourceLocation *Loc) const {
  12227. assert(!isValueDependent() &&
  12228. "Expression evaluator can't be called on a dependent expression.");
  12229. if (Ctx.getLangOpts().CPlusPlus11)
  12230. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  12231. ICEDiag D = CheckICE(this, Ctx);
  12232. if (D.Kind != IK_ICE) {
  12233. if (Loc) *Loc = D.Loc;
  12234. return false;
  12235. }
  12236. return true;
  12237. }
  12238. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  12239. SourceLocation *Loc, bool isEvaluated) const {
  12240. assert(!isValueDependent() &&
  12241. "Expression evaluator can't be called on a dependent expression.");
  12242. if (Ctx.getLangOpts().CPlusPlus11)
  12243. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  12244. if (!isIntegerConstantExpr(Ctx, Loc))
  12245. return false;
  12246. // The only possible side-effects here are due to UB discovered in the
  12247. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  12248. // required to treat the expression as an ICE, so we produce the folded
  12249. // value.
  12250. EvalResult ExprResult;
  12251. Expr::EvalStatus Status;
  12252. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  12253. Info.InConstantContext = true;
  12254. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  12255. llvm_unreachable("ICE cannot be evaluated!");
  12256. Value = ExprResult.Val.getInt();
  12257. return true;
  12258. }
  12259. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  12260. assert(!isValueDependent() &&
  12261. "Expression evaluator can't be called on a dependent expression.");
  12262. return CheckICE(this, Ctx).Kind == IK_ICE;
  12263. }
  12264. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  12265. SourceLocation *Loc) const {
  12266. assert(!isValueDependent() &&
  12267. "Expression evaluator can't be called on a dependent expression.");
  12268. // We support this checking in C++98 mode in order to diagnose compatibility
  12269. // issues.
  12270. assert(Ctx.getLangOpts().CPlusPlus);
  12271. // Build evaluation settings.
  12272. Expr::EvalStatus Status;
  12273. SmallVector<PartialDiagnosticAt, 8> Diags;
  12274. Status.Diag = &Diags;
  12275. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  12276. APValue Scratch;
  12277. bool IsConstExpr =
  12278. ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
  12279. // FIXME: We don't produce a diagnostic for this, but the callers that
  12280. // call us on arbitrary full-expressions should generally not care.
  12281. Info.discardCleanups() && !Status.HasSideEffects;
  12282. if (!Diags.empty()) {
  12283. IsConstExpr = false;
  12284. if (Loc) *Loc = Diags[0].first;
  12285. } else if (!IsConstExpr) {
  12286. // FIXME: This shouldn't happen.
  12287. if (Loc) *Loc = getExprLoc();
  12288. }
  12289. return IsConstExpr;
  12290. }
  12291. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  12292. const FunctionDecl *Callee,
  12293. ArrayRef<const Expr*> Args,
  12294. const Expr *This) const {
  12295. assert(!isValueDependent() &&
  12296. "Expression evaluator can't be called on a dependent expression.");
  12297. Expr::EvalStatus Status;
  12298. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  12299. Info.InConstantContext = true;
  12300. LValue ThisVal;
  12301. const LValue *ThisPtr = nullptr;
  12302. if (This) {
  12303. #ifndef NDEBUG
  12304. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  12305. assert(MD && "Don't provide `this` for non-methods.");
  12306. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  12307. #endif
  12308. if (EvaluateObjectArgument(Info, This, ThisVal))
  12309. ThisPtr = &ThisVal;
  12310. if (Info.EvalStatus.HasSideEffects)
  12311. return false;
  12312. }
  12313. ArgVector ArgValues(Args.size());
  12314. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  12315. I != E; ++I) {
  12316. if ((*I)->isValueDependent() ||
  12317. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  12318. // If evaluation fails, throw away the argument entirely.
  12319. ArgValues[I - Args.begin()] = APValue();
  12320. if (Info.EvalStatus.HasSideEffects)
  12321. return false;
  12322. }
  12323. // Build fake call to Callee.
  12324. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  12325. ArgValues.data());
  12326. return Evaluate(Value, Info, this) && Info.discardCleanups() &&
  12327. !Info.EvalStatus.HasSideEffects;
  12328. }
  12329. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  12330. SmallVectorImpl<
  12331. PartialDiagnosticAt> &Diags) {
  12332. // FIXME: It would be useful to check constexpr function templates, but at the
  12333. // moment the constant expression evaluator cannot cope with the non-rigorous
  12334. // ASTs which we build for dependent expressions.
  12335. if (FD->isDependentContext())
  12336. return true;
  12337. Expr::EvalStatus Status;
  12338. Status.Diag = &Diags;
  12339. EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
  12340. Info.InConstantContext = true;
  12341. Info.CheckingPotentialConstantExpression = true;
  12342. // The constexpr VM attempts to compile all methods to bytecode here.
  12343. if (Info.EnableNewConstInterp) {
  12344. auto &InterpCtx = Info.Ctx.getInterpContext();
  12345. switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
  12346. case interp::InterpResult::Success:
  12347. case interp::InterpResult::Fail:
  12348. return Diags.empty();
  12349. case interp::InterpResult::Bail:
  12350. break;
  12351. }
  12352. }
  12353. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  12354. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  12355. // Fabricate an arbitrary expression on the stack and pretend that it
  12356. // is a temporary being used as the 'this' pointer.
  12357. LValue This;
  12358. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  12359. This.set({&VIE, Info.CurrentCall->Index});
  12360. ArrayRef<const Expr*> Args;
  12361. APValue Scratch;
  12362. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  12363. // Evaluate the call as a constant initializer, to allow the construction
  12364. // of objects of non-literal types.
  12365. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  12366. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  12367. } else {
  12368. SourceLocation Loc = FD->getLocation();
  12369. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  12370. Args, FD->getBody(), Info, Scratch, nullptr);
  12371. }
  12372. return Diags.empty();
  12373. }
  12374. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  12375. const FunctionDecl *FD,
  12376. SmallVectorImpl<
  12377. PartialDiagnosticAt> &Diags) {
  12378. assert(!E->isValueDependent() &&
  12379. "Expression evaluator can't be called on a dependent expression.");
  12380. Expr::EvalStatus Status;
  12381. Status.Diag = &Diags;
  12382. EvalInfo Info(FD->getASTContext(), Status,
  12383. EvalInfo::EM_ConstantExpressionUnevaluated);
  12384. Info.InConstantContext = true;
  12385. Info.CheckingPotentialConstantExpression = true;
  12386. // Fabricate a call stack frame to give the arguments a plausible cover story.
  12387. ArrayRef<const Expr*> Args;
  12388. ArgVector ArgValues(0);
  12389. bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
  12390. (void)Success;
  12391. assert(Success &&
  12392. "Failed to set up arguments for potential constant evaluation");
  12393. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  12394. APValue ResultScratch;
  12395. Evaluate(ResultScratch, Info, E);
  12396. return Diags.empty();
  12397. }
  12398. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  12399. unsigned Type) const {
  12400. if (!getType()->isPointerType())
  12401. return false;
  12402. Expr::EvalStatus Status;
  12403. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  12404. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  12405. }