SemaExpr.cpp 827 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  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 semantic analysis for expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TreeTransform.h"
  13. #include "UsedDeclVisitor.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/EvaluatedExprVisitor.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ExprOpenMP.h"
  26. #include "clang/AST/OperationKinds.h"
  27. #include "clang/AST/ParentMapContext.h"
  28. #include "clang/AST/RecursiveASTVisitor.h"
  29. #include "clang/AST/Type.h"
  30. #include "clang/AST/TypeLoc.h"
  31. #include "clang/Basic/Builtins.h"
  32. #include "clang/Basic/DiagnosticSema.h"
  33. #include "clang/Basic/PartialDiagnostic.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Basic/Specifiers.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Lex/LiteralSupport.h"
  38. #include "clang/Lex/Preprocessor.h"
  39. #include "clang/Sema/AnalysisBasedWarnings.h"
  40. #include "clang/Sema/DeclSpec.h"
  41. #include "clang/Sema/DelayedDiagnostic.h"
  42. #include "clang/Sema/Designator.h"
  43. #include "clang/Sema/Initialization.h"
  44. #include "clang/Sema/Lookup.h"
  45. #include "clang/Sema/Overload.h"
  46. #include "clang/Sema/ParsedTemplate.h"
  47. #include "clang/Sema/Scope.h"
  48. #include "clang/Sema/ScopeInfo.h"
  49. #include "clang/Sema/SemaFixItUtils.h"
  50. #include "clang/Sema/SemaInternal.h"
  51. #include "clang/Sema/Template.h"
  52. #include "llvm/ADT/STLExtras.h"
  53. #include "llvm/ADT/StringExtras.h"
  54. #include "llvm/Support/Casting.h"
  55. #include "llvm/Support/ConvertUTF.h"
  56. #include "llvm/Support/SaveAndRestore.h"
  57. #include "llvm/Support/TypeSize.h"
  58. #include <optional>
  59. using namespace clang;
  60. using namespace sema;
  61. /// Determine whether the use of this declaration is valid, without
  62. /// emitting diagnostics.
  63. bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
  64. // See if this is an auto-typed variable whose initializer we are parsing.
  65. if (ParsingInitForAutoVars.count(D))
  66. return false;
  67. // See if this is a deleted function.
  68. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  69. if (FD->isDeleted())
  70. return false;
  71. // If the function has a deduced return type, and we can't deduce it,
  72. // then we can't use it either.
  73. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  74. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  75. return false;
  76. // See if this is an aligned allocation/deallocation function that is
  77. // unavailable.
  78. if (TreatUnavailableAsInvalid &&
  79. isUnavailableAlignedAllocationFunction(*FD))
  80. return false;
  81. }
  82. // See if this function is unavailable.
  83. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  84. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  85. return false;
  86. if (isa<UnresolvedUsingIfExistsDecl>(D))
  87. return false;
  88. return true;
  89. }
  90. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  91. // Warn if this is used but marked unused.
  92. if (const auto *A = D->getAttr<UnusedAttr>()) {
  93. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  94. // should diagnose them.
  95. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  96. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  97. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  98. if (DC && !DC->hasAttr<UnusedAttr>())
  99. S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
  100. }
  101. }
  102. }
  103. /// Emit a note explaining that this function is deleted.
  104. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  105. assert(Decl && Decl->isDeleted());
  106. if (Decl->isDefaulted()) {
  107. // If the method was explicitly defaulted, point at that declaration.
  108. if (!Decl->isImplicit())
  109. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  110. // Try to diagnose why this special member function was implicitly
  111. // deleted. This might fail, if that reason no longer applies.
  112. DiagnoseDeletedDefaultedFunction(Decl);
  113. return;
  114. }
  115. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  116. if (Ctor && Ctor->isInheritingConstructor())
  117. return NoteDeletedInheritingConstructor(Ctor);
  118. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  119. << Decl << 1;
  120. }
  121. /// Determine whether a FunctionDecl was ever declared with an
  122. /// explicit storage class.
  123. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  124. for (auto *I : D->redecls()) {
  125. if (I->getStorageClass() != SC_None)
  126. return true;
  127. }
  128. return false;
  129. }
  130. /// Check whether we're in an extern inline function and referring to a
  131. /// variable or function with internal linkage (C11 6.7.4p3).
  132. ///
  133. /// This is only a warning because we used to silently accept this code, but
  134. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  135. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  136. /// and so while there may still be user mistakes, most of the time we can't
  137. /// prove that there are errors.
  138. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  139. const NamedDecl *D,
  140. SourceLocation Loc) {
  141. // This is disabled under C++; there are too many ways for this to fire in
  142. // contexts where the warning is a false positive, or where it is technically
  143. // correct but benign.
  144. if (S.getLangOpts().CPlusPlus)
  145. return;
  146. // Check if this is an inlined function or method.
  147. FunctionDecl *Current = S.getCurFunctionDecl();
  148. if (!Current)
  149. return;
  150. if (!Current->isInlined())
  151. return;
  152. if (!Current->isExternallyVisible())
  153. return;
  154. // Check if the decl has internal linkage.
  155. if (D->getFormalLinkage() != InternalLinkage)
  156. return;
  157. // Downgrade from ExtWarn to Extension if
  158. // (1) the supposedly external inline function is in the main file,
  159. // and probably won't be included anywhere else.
  160. // (2) the thing we're referencing is a pure function.
  161. // (3) the thing we're referencing is another inline function.
  162. // This last can give us false negatives, but it's better than warning on
  163. // wrappers for simple C library functions.
  164. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  165. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  166. if (!DowngradeWarning && UsedFn)
  167. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  168. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  169. : diag::ext_internal_in_extern_inline)
  170. << /*IsVar=*/!UsedFn << D;
  171. S.MaybeSuggestAddingStaticToDecl(Current);
  172. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  173. << D;
  174. }
  175. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  176. const FunctionDecl *First = Cur->getFirstDecl();
  177. // Suggest "static" on the function, if possible.
  178. if (!hasAnyExplicitStorageClass(First)) {
  179. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  180. Diag(DeclBegin, diag::note_convert_inline_to_static)
  181. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  182. }
  183. }
  184. /// Determine whether the use of this declaration is valid, and
  185. /// emit any corresponding diagnostics.
  186. ///
  187. /// This routine diagnoses various problems with referencing
  188. /// declarations that can occur when using a declaration. For example,
  189. /// it might warn if a deprecated or unavailable declaration is being
  190. /// used, or produce an error (and return true) if a C++0x deleted
  191. /// function is being used.
  192. ///
  193. /// \returns true if there was an error (this declaration cannot be
  194. /// referenced), false otherwise.
  195. ///
  196. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
  197. const ObjCInterfaceDecl *UnknownObjCClass,
  198. bool ObjCPropertyAccess,
  199. bool AvoidPartialAvailabilityChecks,
  200. ObjCInterfaceDecl *ClassReceiver,
  201. bool SkipTrailingRequiresClause) {
  202. SourceLocation Loc = Locs.front();
  203. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  204. // If there were any diagnostics suppressed by template argument deduction,
  205. // emit them now.
  206. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  207. if (Pos != SuppressedDiagnostics.end()) {
  208. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  209. Diag(Suppressed.first, Suppressed.second);
  210. // Clear out the list of suppressed diagnostics, so that we don't emit
  211. // them again for this specialization. However, we don't obsolete this
  212. // entry from the table, because we want to avoid ever emitting these
  213. // diagnostics again.
  214. Pos->second.clear();
  215. }
  216. // C++ [basic.start.main]p3:
  217. // The function 'main' shall not be used within a program.
  218. if (cast<FunctionDecl>(D)->isMain())
  219. Diag(Loc, diag::ext_main_used);
  220. diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
  221. }
  222. // See if this is an auto-typed variable whose initializer we are parsing.
  223. if (ParsingInitForAutoVars.count(D)) {
  224. if (isa<BindingDecl>(D)) {
  225. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  226. << D->getDeclName();
  227. } else {
  228. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  229. << D->getDeclName() << cast<VarDecl>(D)->getType();
  230. }
  231. return true;
  232. }
  233. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  234. // See if this is a deleted function.
  235. if (FD->isDeleted()) {
  236. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  237. if (Ctor && Ctor->isInheritingConstructor())
  238. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  239. << Ctor->getParent()
  240. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  241. else
  242. Diag(Loc, diag::err_deleted_function_use);
  243. NoteDeletedFunction(FD);
  244. return true;
  245. }
  246. // [expr.prim.id]p4
  247. // A program that refers explicitly or implicitly to a function with a
  248. // trailing requires-clause whose constraint-expression is not satisfied,
  249. // other than to declare it, is ill-formed. [...]
  250. //
  251. // See if this is a function with constraints that need to be satisfied.
  252. // Check this before deducing the return type, as it might instantiate the
  253. // definition.
  254. if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
  255. ConstraintSatisfaction Satisfaction;
  256. if (CheckFunctionConstraints(FD, Satisfaction, Loc,
  257. /*ForOverloadResolution*/ true))
  258. // A diagnostic will have already been generated (non-constant
  259. // constraint expression, for example)
  260. return true;
  261. if (!Satisfaction.IsSatisfied) {
  262. Diag(Loc,
  263. diag::err_reference_to_function_with_unsatisfied_constraints)
  264. << D;
  265. DiagnoseUnsatisfiedConstraint(Satisfaction);
  266. return true;
  267. }
  268. }
  269. // If the function has a deduced return type, and we can't deduce it,
  270. // then we can't use it either.
  271. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  272. DeduceReturnType(FD, Loc))
  273. return true;
  274. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  275. return true;
  276. if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
  277. return true;
  278. }
  279. if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  280. // Lambdas are only default-constructible or assignable in C++2a onwards.
  281. if (MD->getParent()->isLambda() &&
  282. ((isa<CXXConstructorDecl>(MD) &&
  283. cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
  284. MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
  285. Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
  286. << !isa<CXXConstructorDecl>(MD);
  287. }
  288. }
  289. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  290. const ObjCPropertyDecl * {
  291. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  292. return MD->findPropertyDecl();
  293. return nullptr;
  294. };
  295. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  296. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  297. return true;
  298. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  299. return true;
  300. }
  301. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  302. // Only the variables omp_in and omp_out are allowed in the combiner.
  303. // Only the variables omp_priv and omp_orig are allowed in the
  304. // initializer-clause.
  305. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  306. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  307. isa<VarDecl>(D)) {
  308. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  309. << getCurFunction()->HasOMPDeclareReductionCombiner;
  310. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  311. return true;
  312. }
  313. // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
  314. // List-items in map clauses on this construct may only refer to the declared
  315. // variable var and entities that could be referenced by a procedure defined
  316. // at the same location.
  317. // [OpenMP 5.2] Also allow iterator declared variables.
  318. if (LangOpts.OpenMP && isa<VarDecl>(D) &&
  319. !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
  320. Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
  321. << getOpenMPDeclareMapperVarName();
  322. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  323. return true;
  324. }
  325. if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
  326. Diag(Loc, diag::err_use_of_empty_using_if_exists);
  327. Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
  328. return true;
  329. }
  330. DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
  331. AvoidPartialAvailabilityChecks, ClassReceiver);
  332. DiagnoseUnusedOfDecl(*this, D, Loc);
  333. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  334. if (auto *VD = dyn_cast<ValueDecl>(D))
  335. checkTypeSupport(VD->getType(), Loc, VD);
  336. if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
  337. if (!Context.getTargetInfo().isTLSSupported())
  338. if (const auto *VD = dyn_cast<VarDecl>(D))
  339. if (VD->getTLSKind() != VarDecl::TLS_None)
  340. targetDiag(*Locs.begin(), diag::err_thread_unsupported);
  341. }
  342. if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
  343. !isUnevaluatedContext()) {
  344. // C++ [expr.prim.req.nested] p3
  345. // A local parameter shall only appear as an unevaluated operand
  346. // (Clause 8) within the constraint-expression.
  347. Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
  348. << D;
  349. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  350. return true;
  351. }
  352. return false;
  353. }
  354. /// DiagnoseSentinelCalls - This routine checks whether a call or
  355. /// message-send is to a declaration with the sentinel attribute, and
  356. /// if so, it checks that the requirements of the sentinel are
  357. /// satisfied.
  358. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  359. ArrayRef<Expr *> Args) {
  360. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  361. if (!attr)
  362. return;
  363. // The number of formal parameters of the declaration.
  364. unsigned numFormalParams;
  365. // The kind of declaration. This is also an index into a %select in
  366. // the diagnostic.
  367. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  368. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  369. numFormalParams = MD->param_size();
  370. calleeType = CT_Method;
  371. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  372. numFormalParams = FD->param_size();
  373. calleeType = CT_Function;
  374. } else if (isa<VarDecl>(D)) {
  375. QualType type = cast<ValueDecl>(D)->getType();
  376. const FunctionType *fn = nullptr;
  377. if (const PointerType *ptr = type->getAs<PointerType>()) {
  378. fn = ptr->getPointeeType()->getAs<FunctionType>();
  379. if (!fn) return;
  380. calleeType = CT_Function;
  381. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  382. fn = ptr->getPointeeType()->castAs<FunctionType>();
  383. calleeType = CT_Block;
  384. } else {
  385. return;
  386. }
  387. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  388. numFormalParams = proto->getNumParams();
  389. } else {
  390. numFormalParams = 0;
  391. }
  392. } else {
  393. return;
  394. }
  395. // "nullPos" is the number of formal parameters at the end which
  396. // effectively count as part of the variadic arguments. This is
  397. // useful if you would prefer to not have *any* formal parameters,
  398. // but the language forces you to have at least one.
  399. unsigned nullPos = attr->getNullPos();
  400. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  401. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  402. // The number of arguments which should follow the sentinel.
  403. unsigned numArgsAfterSentinel = attr->getSentinel();
  404. // If there aren't enough arguments for all the formal parameters,
  405. // the sentinel, and the args after the sentinel, complain.
  406. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  407. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  408. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  409. return;
  410. }
  411. // Otherwise, find the sentinel expression.
  412. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  413. if (!sentinelExpr) return;
  414. if (sentinelExpr->isValueDependent()) return;
  415. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  416. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  417. // or 'NULL' if those are actually defined in the context. Only use
  418. // 'nil' for ObjC methods, where it's much more likely that the
  419. // variadic arguments form a list of object pointers.
  420. SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
  421. std::string NullValue;
  422. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  423. NullValue = "nil";
  424. else if (getLangOpts().CPlusPlus11)
  425. NullValue = "nullptr";
  426. else if (PP.isMacroDefined("NULL"))
  427. NullValue = "NULL";
  428. else
  429. NullValue = "(void*) 0";
  430. if (MissingNilLoc.isInvalid())
  431. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  432. else
  433. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  434. << int(calleeType)
  435. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  436. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  437. }
  438. SourceRange Sema::getExprRange(Expr *E) const {
  439. return E ? E->getSourceRange() : SourceRange();
  440. }
  441. //===----------------------------------------------------------------------===//
  442. // Standard Promotions and Conversions
  443. //===----------------------------------------------------------------------===//
  444. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  445. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  446. // Handle any placeholder expressions which made it here.
  447. if (E->hasPlaceholderType()) {
  448. ExprResult result = CheckPlaceholderExpr(E);
  449. if (result.isInvalid()) return ExprError();
  450. E = result.get();
  451. }
  452. QualType Ty = E->getType();
  453. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  454. if (Ty->isFunctionType()) {
  455. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  456. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  457. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  458. return ExprError();
  459. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  460. CK_FunctionToPointerDecay).get();
  461. } else if (Ty->isArrayType()) {
  462. // In C90 mode, arrays only promote to pointers if the array expression is
  463. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  464. // type 'array of type' is converted to an expression that has type 'pointer
  465. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  466. // that has type 'array of type' ...". The relevant change is "an lvalue"
  467. // (C90) to "an expression" (C99).
  468. //
  469. // C++ 4.2p1:
  470. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  471. // T" can be converted to an rvalue of type "pointer to T".
  472. //
  473. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
  474. ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  475. CK_ArrayToPointerDecay);
  476. if (Res.isInvalid())
  477. return ExprError();
  478. E = Res.get();
  479. }
  480. }
  481. return E;
  482. }
  483. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  484. // Check to see if we are dereferencing a null pointer. If so,
  485. // and if not volatile-qualified, this is undefined behavior that the
  486. // optimizer will delete, so warn about it. People sometimes try to use this
  487. // to get a deterministic trap and are surprised by clang's behavior. This
  488. // only handles the pattern "*null", which is a very syntactic check.
  489. const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
  490. if (UO && UO->getOpcode() == UO_Deref &&
  491. UO->getSubExpr()->getType()->isPointerType()) {
  492. const LangAS AS =
  493. UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
  494. if ((!isTargetAddressSpace(AS) ||
  495. (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
  496. UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
  497. S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  498. !UO->getType().isVolatileQualified()) {
  499. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  500. S.PDiag(diag::warn_indirection_through_null)
  501. << UO->getSubExpr()->getSourceRange());
  502. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  503. S.PDiag(diag::note_indirection_through_null));
  504. }
  505. }
  506. }
  507. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  508. SourceLocation AssignLoc,
  509. const Expr* RHS) {
  510. const ObjCIvarDecl *IV = OIRE->getDecl();
  511. if (!IV)
  512. return;
  513. DeclarationName MemberName = IV->getDeclName();
  514. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  515. if (!Member || !Member->isStr("isa"))
  516. return;
  517. const Expr *Base = OIRE->getBase();
  518. QualType BaseType = Base->getType();
  519. if (OIRE->isArrow())
  520. BaseType = BaseType->getPointeeType();
  521. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  522. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  523. ObjCInterfaceDecl *ClassDeclared = nullptr;
  524. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  525. if (!ClassDeclared->getSuperClass()
  526. && (*ClassDeclared->ivar_begin()) == IV) {
  527. if (RHS) {
  528. NamedDecl *ObjectSetClass =
  529. S.LookupSingleName(S.TUScope,
  530. &S.Context.Idents.get("object_setClass"),
  531. SourceLocation(), S.LookupOrdinaryName);
  532. if (ObjectSetClass) {
  533. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
  534. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
  535. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  536. "object_setClass(")
  537. << FixItHint::CreateReplacement(
  538. SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
  539. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  540. }
  541. else
  542. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  543. } else {
  544. NamedDecl *ObjectGetClass =
  545. S.LookupSingleName(S.TUScope,
  546. &S.Context.Idents.get("object_getClass"),
  547. SourceLocation(), S.LookupOrdinaryName);
  548. if (ObjectGetClass)
  549. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
  550. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  551. "object_getClass(")
  552. << FixItHint::CreateReplacement(
  553. SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
  554. else
  555. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  556. }
  557. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  558. }
  559. }
  560. }
  561. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  562. // Handle any placeholder expressions which made it here.
  563. if (E->hasPlaceholderType()) {
  564. ExprResult result = CheckPlaceholderExpr(E);
  565. if (result.isInvalid()) return ExprError();
  566. E = result.get();
  567. }
  568. // C++ [conv.lval]p1:
  569. // A glvalue of a non-function, non-array type T can be
  570. // converted to a prvalue.
  571. if (!E->isGLValue()) return E;
  572. QualType T = E->getType();
  573. assert(!T.isNull() && "r-value conversion on typeless expression?");
  574. // lvalue-to-rvalue conversion cannot be applied to function or array types.
  575. if (T->isFunctionType() || T->isArrayType())
  576. return E;
  577. // We don't want to throw lvalue-to-rvalue casts on top of
  578. // expressions of certain types in C++.
  579. if (getLangOpts().CPlusPlus &&
  580. (E->getType() == Context.OverloadTy ||
  581. T->isDependentType() ||
  582. T->isRecordType()))
  583. return E;
  584. // The C standard is actually really unclear on this point, and
  585. // DR106 tells us what the result should be but not why. It's
  586. // generally best to say that void types just doesn't undergo
  587. // lvalue-to-rvalue at all. Note that expressions of unqualified
  588. // 'void' type are never l-values, but qualified void can be.
  589. if (T->isVoidType())
  590. return E;
  591. // OpenCL usually rejects direct accesses to values of 'half' type.
  592. if (getLangOpts().OpenCL &&
  593. !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
  594. T->isHalfType()) {
  595. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  596. << 0 << T;
  597. return ExprError();
  598. }
  599. CheckForNullPointerDereference(*this, E);
  600. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  601. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  602. &Context.Idents.get("object_getClass"),
  603. SourceLocation(), LookupOrdinaryName);
  604. if (ObjectGetClass)
  605. Diag(E->getExprLoc(), diag::warn_objc_isa_use)
  606. << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
  607. << FixItHint::CreateReplacement(
  608. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  609. else
  610. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  611. }
  612. else if (const ObjCIvarRefExpr *OIRE =
  613. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  614. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  615. // C++ [conv.lval]p1:
  616. // [...] If T is a non-class type, the type of the prvalue is the
  617. // cv-unqualified version of T. Otherwise, the type of the
  618. // rvalue is T.
  619. //
  620. // C99 6.3.2.1p2:
  621. // If the lvalue has qualified type, the value has the unqualified
  622. // version of the type of the lvalue; otherwise, the value has the
  623. // type of the lvalue.
  624. if (T.hasQualifiers())
  625. T = T.getUnqualifiedType();
  626. // Under the MS ABI, lock down the inheritance model now.
  627. if (T->isMemberPointerType() &&
  628. Context.getTargetInfo().getCXXABI().isMicrosoft())
  629. (void)isCompleteType(E->getExprLoc(), T);
  630. ExprResult Res = CheckLValueToRValueConversionOperand(E);
  631. if (Res.isInvalid())
  632. return Res;
  633. E = Res.get();
  634. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  635. // balance that.
  636. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  637. Cleanup.setExprNeedsCleanups(true);
  638. if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  639. Cleanup.setExprNeedsCleanups(true);
  640. // C++ [conv.lval]p3:
  641. // If T is cv std::nullptr_t, the result is a null pointer constant.
  642. CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
  643. Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
  644. CurFPFeatureOverrides());
  645. // C11 6.3.2.1p2:
  646. // ... if the lvalue has atomic type, the value has the non-atomic version
  647. // of the type of the lvalue ...
  648. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  649. T = Atomic->getValueType().getUnqualifiedType();
  650. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  651. nullptr, VK_PRValue, FPOptionsOverride());
  652. }
  653. return Res;
  654. }
  655. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  656. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  657. if (Res.isInvalid())
  658. return ExprError();
  659. Res = DefaultLvalueConversion(Res.get());
  660. if (Res.isInvalid())
  661. return ExprError();
  662. return Res;
  663. }
  664. /// CallExprUnaryConversions - a special case of an unary conversion
  665. /// performed on a function designator of a call expression.
  666. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  667. QualType Ty = E->getType();
  668. ExprResult Res = E;
  669. // Only do implicit cast for a function type, but not for a pointer
  670. // to function type.
  671. if (Ty->isFunctionType()) {
  672. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  673. CK_FunctionToPointerDecay);
  674. if (Res.isInvalid())
  675. return ExprError();
  676. }
  677. Res = DefaultLvalueConversion(Res.get());
  678. if (Res.isInvalid())
  679. return ExprError();
  680. return Res.get();
  681. }
  682. /// UsualUnaryConversions - Performs various conversions that are common to most
  683. /// operators (C99 6.3). The conversions of array and function types are
  684. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  685. /// apply if the array is an argument to the sizeof or address (&) operators.
  686. /// In these instances, this routine should *not* be called.
  687. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  688. // First, convert to an r-value.
  689. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  690. if (Res.isInvalid())
  691. return ExprError();
  692. E = Res.get();
  693. QualType Ty = E->getType();
  694. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  695. LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
  696. if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
  697. (getLangOpts().getFPEvalMethod() !=
  698. LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
  699. PP.getLastFPEvalPragmaLocation().isValid())) {
  700. switch (EvalMethod) {
  701. default:
  702. llvm_unreachable("Unrecognized float evaluation method");
  703. break;
  704. case LangOptions::FEM_UnsetOnCommandLine:
  705. llvm_unreachable("Float evaluation method should be set by now");
  706. break;
  707. case LangOptions::FEM_Double:
  708. if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
  709. // Widen the expression to double.
  710. return Ty->isComplexType()
  711. ? ImpCastExprToType(E,
  712. Context.getComplexType(Context.DoubleTy),
  713. CK_FloatingComplexCast)
  714. : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
  715. break;
  716. case LangOptions::FEM_Extended:
  717. if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
  718. // Widen the expression to long double.
  719. return Ty->isComplexType()
  720. ? ImpCastExprToType(
  721. E, Context.getComplexType(Context.LongDoubleTy),
  722. CK_FloatingComplexCast)
  723. : ImpCastExprToType(E, Context.LongDoubleTy,
  724. CK_FloatingCast);
  725. break;
  726. }
  727. }
  728. // Half FP have to be promoted to float unless it is natively supported
  729. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  730. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  731. // Try to perform integral promotions if the object has a theoretically
  732. // promotable type.
  733. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  734. // C99 6.3.1.1p2:
  735. //
  736. // The following may be used in an expression wherever an int or
  737. // unsigned int may be used:
  738. // - an object or expression with an integer type whose integer
  739. // conversion rank is less than or equal to the rank of int
  740. // and unsigned int.
  741. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  742. //
  743. // If an int can represent all values of the original type, the
  744. // value is converted to an int; otherwise, it is converted to an
  745. // unsigned int. These are called the integer promotions. All
  746. // other types are unchanged by the integer promotions.
  747. QualType PTy = Context.isPromotableBitField(E);
  748. if (!PTy.isNull()) {
  749. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  750. return E;
  751. }
  752. if (Context.isPromotableIntegerType(Ty)) {
  753. QualType PT = Context.getPromotedIntegerType(Ty);
  754. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  755. return E;
  756. }
  757. }
  758. return E;
  759. }
  760. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  761. /// do not have a prototype. Arguments that have type float or __fp16
  762. /// are promoted to double. All other argument types are converted by
  763. /// UsualUnaryConversions().
  764. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  765. QualType Ty = E->getType();
  766. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  767. ExprResult Res = UsualUnaryConversions(E);
  768. if (Res.isInvalid())
  769. return ExprError();
  770. E = Res.get();
  771. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  772. // promote to double.
  773. // Note that default argument promotion applies only to float (and
  774. // half/fp16); it does not apply to _Float16.
  775. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  776. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  777. BTy->getKind() == BuiltinType::Float)) {
  778. if (getLangOpts().OpenCL &&
  779. !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
  780. if (BTy->getKind() == BuiltinType::Half) {
  781. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  782. }
  783. } else {
  784. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  785. }
  786. }
  787. if (BTy &&
  788. getLangOpts().getExtendIntArgs() ==
  789. LangOptions::ExtendArgsKind::ExtendTo64 &&
  790. Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
  791. Context.getTypeSizeInChars(BTy) <
  792. Context.getTypeSizeInChars(Context.LongLongTy)) {
  793. E = (Ty->isUnsignedIntegerType())
  794. ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
  795. .get()
  796. : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
  797. assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
  798. "Unexpected typesize for LongLongTy");
  799. }
  800. // C++ performs lvalue-to-rvalue conversion as a default argument
  801. // promotion, even on class types, but note:
  802. // C++11 [conv.lval]p2:
  803. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  804. // operand or a subexpression thereof the value contained in the
  805. // referenced object is not accessed. Otherwise, if the glvalue
  806. // has a class type, the conversion copy-initializes a temporary
  807. // of type T from the glvalue and the result of the conversion
  808. // is a prvalue for the temporary.
  809. // FIXME: add some way to gate this entire thing for correctness in
  810. // potentially potentially evaluated contexts.
  811. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  812. ExprResult Temp = PerformCopyInitialization(
  813. InitializedEntity::InitializeTemporary(E->getType()),
  814. E->getExprLoc(), E);
  815. if (Temp.isInvalid())
  816. return ExprError();
  817. E = Temp.get();
  818. }
  819. return E;
  820. }
  821. /// Determine the degree of POD-ness for an expression.
  822. /// Incomplete types are considered POD, since this check can be performed
  823. /// when we're in an unevaluated context.
  824. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  825. if (Ty->isIncompleteType()) {
  826. // C++11 [expr.call]p7:
  827. // After these conversions, if the argument does not have arithmetic,
  828. // enumeration, pointer, pointer to member, or class type, the program
  829. // is ill-formed.
  830. //
  831. // Since we've already performed array-to-pointer and function-to-pointer
  832. // decay, the only such type in C++ is cv void. This also handles
  833. // initializer lists as variadic arguments.
  834. if (Ty->isVoidType())
  835. return VAK_Invalid;
  836. if (Ty->isObjCObjectType())
  837. return VAK_Invalid;
  838. return VAK_Valid;
  839. }
  840. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  841. return VAK_Invalid;
  842. if (Ty.isCXX98PODType(Context))
  843. return VAK_Valid;
  844. // C++11 [expr.call]p7:
  845. // Passing a potentially-evaluated argument of class type (Clause 9)
  846. // having a non-trivial copy constructor, a non-trivial move constructor,
  847. // or a non-trivial destructor, with no corresponding parameter,
  848. // is conditionally-supported with implementation-defined semantics.
  849. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  850. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  851. if (!Record->hasNonTrivialCopyConstructor() &&
  852. !Record->hasNonTrivialMoveConstructor() &&
  853. !Record->hasNonTrivialDestructor())
  854. return VAK_ValidInCXX11;
  855. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  856. return VAK_Valid;
  857. if (Ty->isObjCObjectType())
  858. return VAK_Invalid;
  859. if (getLangOpts().MSVCCompat)
  860. return VAK_MSVCUndefined;
  861. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  862. // permitted to reject them. We should consider doing so.
  863. return VAK_Undefined;
  864. }
  865. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  866. // Don't allow one to pass an Objective-C interface to a vararg.
  867. const QualType &Ty = E->getType();
  868. VarArgKind VAK = isValidVarArgType(Ty);
  869. // Complain about passing non-POD types through varargs.
  870. switch (VAK) {
  871. case VAK_ValidInCXX11:
  872. DiagRuntimeBehavior(
  873. E->getBeginLoc(), nullptr,
  874. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
  875. [[fallthrough]];
  876. case VAK_Valid:
  877. if (Ty->isRecordType()) {
  878. // This is unlikely to be what the user intended. If the class has a
  879. // 'c_str' member function, the user probably meant to call that.
  880. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  881. PDiag(diag::warn_pass_class_arg_to_vararg)
  882. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  883. }
  884. break;
  885. case VAK_Undefined:
  886. case VAK_MSVCUndefined:
  887. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  888. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  889. << getLangOpts().CPlusPlus11 << Ty << CT);
  890. break;
  891. case VAK_Invalid:
  892. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  893. Diag(E->getBeginLoc(),
  894. diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
  895. << Ty << CT;
  896. else if (Ty->isObjCObjectType())
  897. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  898. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  899. << Ty << CT);
  900. else
  901. Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
  902. << isa<InitListExpr>(E) << Ty << CT;
  903. break;
  904. }
  905. }
  906. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  907. /// will create a trap if the resulting type is not a POD type.
  908. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  909. FunctionDecl *FDecl) {
  910. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  911. // Strip the unbridged-cast placeholder expression off, if applicable.
  912. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  913. (CT == VariadicMethod ||
  914. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  915. E = stripARCUnbridgedCast(E);
  916. // Otherwise, do normal placeholder checking.
  917. } else {
  918. ExprResult ExprRes = CheckPlaceholderExpr(E);
  919. if (ExprRes.isInvalid())
  920. return ExprError();
  921. E = ExprRes.get();
  922. }
  923. }
  924. ExprResult ExprRes = DefaultArgumentPromotion(E);
  925. if (ExprRes.isInvalid())
  926. return ExprError();
  927. // Copy blocks to the heap.
  928. if (ExprRes.get()->getType()->isBlockPointerType())
  929. maybeExtendBlockObject(ExprRes);
  930. E = ExprRes.get();
  931. // Diagnostics regarding non-POD argument types are
  932. // emitted along with format string checking in Sema::CheckFunctionCall().
  933. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  934. // Turn this into a trap.
  935. CXXScopeSpec SS;
  936. SourceLocation TemplateKWLoc;
  937. UnqualifiedId Name;
  938. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  939. E->getBeginLoc());
  940. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
  941. /*HasTrailingLParen=*/true,
  942. /*IsAddressOfOperand=*/false);
  943. if (TrapFn.isInvalid())
  944. return ExprError();
  945. ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
  946. std::nullopt, E->getEndLoc());
  947. if (Call.isInvalid())
  948. return ExprError();
  949. ExprResult Comma =
  950. ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
  951. if (Comma.isInvalid())
  952. return ExprError();
  953. return Comma.get();
  954. }
  955. if (!getLangOpts().CPlusPlus &&
  956. RequireCompleteType(E->getExprLoc(), E->getType(),
  957. diag::err_call_incomplete_argument))
  958. return ExprError();
  959. return E;
  960. }
  961. /// Converts an integer to complex float type. Helper function of
  962. /// UsualArithmeticConversions()
  963. ///
  964. /// \return false if the integer expression is an integer type and is
  965. /// successfully converted to the complex type.
  966. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  967. ExprResult &ComplexExpr,
  968. QualType IntTy,
  969. QualType ComplexTy,
  970. bool SkipCast) {
  971. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  972. if (SkipCast) return false;
  973. if (IntTy->isIntegerType()) {
  974. QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
  975. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  976. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  977. CK_FloatingRealToComplex);
  978. } else {
  979. assert(IntTy->isComplexIntegerType());
  980. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  981. CK_IntegralComplexToFloatingComplex);
  982. }
  983. return false;
  984. }
  985. // This handles complex/complex, complex/float, or float/complex.
  986. // When both operands are complex, the shorter operand is converted to the
  987. // type of the longer, and that is the type of the result. This corresponds
  988. // to what is done when combining two real floating-point operands.
  989. // The fun begins when size promotion occur across type domains.
  990. // From H&S 6.3.4: When one operand is complex and the other is a real
  991. // floating-point type, the less precise type is converted, within it's
  992. // real or complex domain, to the precision of the other type. For example,
  993. // when combining a "long double" with a "double _Complex", the
  994. // "double _Complex" is promoted to "long double _Complex".
  995. static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
  996. QualType ShorterType,
  997. QualType LongerType,
  998. bool PromotePrecision) {
  999. bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
  1000. QualType Result =
  1001. LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
  1002. if (PromotePrecision) {
  1003. if (isa<ComplexType>(ShorterType.getCanonicalType())) {
  1004. Shorter =
  1005. S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
  1006. } else {
  1007. if (LongerIsComplex)
  1008. LongerType = LongerType->castAs<ComplexType>()->getElementType();
  1009. Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
  1010. }
  1011. }
  1012. return Result;
  1013. }
  1014. /// Handle arithmetic conversion with complex types. Helper function of
  1015. /// UsualArithmeticConversions()
  1016. static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
  1017. ExprResult &RHS, QualType LHSType,
  1018. QualType RHSType, bool IsCompAssign) {
  1019. // if we have an integer operand, the result is the complex type.
  1020. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  1021. /*SkipCast=*/false))
  1022. return LHSType;
  1023. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  1024. /*SkipCast=*/IsCompAssign))
  1025. return RHSType;
  1026. // Compute the rank of the two types, regardless of whether they are complex.
  1027. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  1028. if (Order < 0)
  1029. // Promote the precision of the LHS if not an assignment.
  1030. return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
  1031. /*PromotePrecision=*/!IsCompAssign);
  1032. // Promote the precision of the RHS unless it is already the same as the LHS.
  1033. return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
  1034. /*PromotePrecision=*/Order > 0);
  1035. }
  1036. /// Handle arithmetic conversion from integer to float. Helper function
  1037. /// of UsualArithmeticConversions()
  1038. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  1039. ExprResult &IntExpr,
  1040. QualType FloatTy, QualType IntTy,
  1041. bool ConvertFloat, bool ConvertInt) {
  1042. if (IntTy->isIntegerType()) {
  1043. if (ConvertInt)
  1044. // Convert intExpr to the lhs floating point type.
  1045. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  1046. CK_IntegralToFloating);
  1047. return FloatTy;
  1048. }
  1049. // Convert both sides to the appropriate complex float.
  1050. assert(IntTy->isComplexIntegerType());
  1051. QualType result = S.Context.getComplexType(FloatTy);
  1052. // _Complex int -> _Complex float
  1053. if (ConvertInt)
  1054. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  1055. CK_IntegralComplexToFloatingComplex);
  1056. // float -> _Complex float
  1057. if (ConvertFloat)
  1058. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  1059. CK_FloatingRealToComplex);
  1060. return result;
  1061. }
  1062. /// Handle arithmethic conversion with floating point types. Helper
  1063. /// function of UsualArithmeticConversions()
  1064. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  1065. ExprResult &RHS, QualType LHSType,
  1066. QualType RHSType, bool IsCompAssign) {
  1067. bool LHSFloat = LHSType->isRealFloatingType();
  1068. bool RHSFloat = RHSType->isRealFloatingType();
  1069. // N1169 4.1.4: If one of the operands has a floating type and the other
  1070. // operand has a fixed-point type, the fixed-point operand
  1071. // is converted to the floating type [...]
  1072. if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
  1073. if (LHSFloat)
  1074. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
  1075. else if (!IsCompAssign)
  1076. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
  1077. return LHSFloat ? LHSType : RHSType;
  1078. }
  1079. // If we have two real floating types, convert the smaller operand
  1080. // to the bigger result.
  1081. if (LHSFloat && RHSFloat) {
  1082. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  1083. if (order > 0) {
  1084. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  1085. return LHSType;
  1086. }
  1087. assert(order < 0 && "illegal float comparison");
  1088. if (!IsCompAssign)
  1089. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  1090. return RHSType;
  1091. }
  1092. if (LHSFloat) {
  1093. // Half FP has to be promoted to float unless it is natively supported
  1094. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  1095. LHSType = S.Context.FloatTy;
  1096. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  1097. /*ConvertFloat=*/!IsCompAssign,
  1098. /*ConvertInt=*/ true);
  1099. }
  1100. assert(RHSFloat);
  1101. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  1102. /*ConvertFloat=*/ true,
  1103. /*ConvertInt=*/!IsCompAssign);
  1104. }
  1105. /// Diagnose attempts to convert between __float128, __ibm128 and
  1106. /// long double if there is no support for such conversion.
  1107. /// Helper function of UsualArithmeticConversions().
  1108. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  1109. QualType RHSType) {
  1110. // No issue if either is not a floating point type.
  1111. if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
  1112. return false;
  1113. // No issue if both have the same 128-bit float semantics.
  1114. auto *LHSComplex = LHSType->getAs<ComplexType>();
  1115. auto *RHSComplex = RHSType->getAs<ComplexType>();
  1116. QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
  1117. QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
  1118. const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
  1119. const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
  1120. if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
  1121. &RHSSem != &llvm::APFloat::IEEEquad()) &&
  1122. (&LHSSem != &llvm::APFloat::IEEEquad() ||
  1123. &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
  1124. return false;
  1125. return true;
  1126. }
  1127. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1128. namespace {
  1129. /// These helper callbacks are placed in an anonymous namespace to
  1130. /// permit their use as function template parameters.
  1131. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1132. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1133. }
  1134. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1135. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1136. CK_IntegralComplexCast);
  1137. }
  1138. }
  1139. /// Handle integer arithmetic conversions. Helper function of
  1140. /// UsualArithmeticConversions()
  1141. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1142. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1143. ExprResult &RHS, QualType LHSType,
  1144. QualType RHSType, bool IsCompAssign) {
  1145. // The rules for this case are in C99 6.3.1.8
  1146. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1147. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1148. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1149. if (LHSSigned == RHSSigned) {
  1150. // Same signedness; use the higher-ranked type
  1151. if (order >= 0) {
  1152. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1153. return LHSType;
  1154. } else if (!IsCompAssign)
  1155. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1156. return RHSType;
  1157. } else if (order != (LHSSigned ? 1 : -1)) {
  1158. // The unsigned type has greater than or equal rank to the
  1159. // signed type, so use the unsigned type
  1160. if (RHSSigned) {
  1161. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1162. return LHSType;
  1163. } else if (!IsCompAssign)
  1164. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1165. return RHSType;
  1166. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1167. // The two types are different widths; if we are here, that
  1168. // means the signed type is larger than the unsigned type, so
  1169. // use the signed type.
  1170. if (LHSSigned) {
  1171. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1172. return LHSType;
  1173. } else if (!IsCompAssign)
  1174. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1175. return RHSType;
  1176. } else {
  1177. // The signed type is higher-ranked than the unsigned type,
  1178. // but isn't actually any bigger (like unsigned int and long
  1179. // on most 32-bit systems). Use the unsigned type corresponding
  1180. // to the signed type.
  1181. QualType result =
  1182. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1183. RHS = (*doRHSCast)(S, RHS.get(), result);
  1184. if (!IsCompAssign)
  1185. LHS = (*doLHSCast)(S, LHS.get(), result);
  1186. return result;
  1187. }
  1188. }
  1189. /// Handle conversions with GCC complex int extension. Helper function
  1190. /// of UsualArithmeticConversions()
  1191. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1192. ExprResult &RHS, QualType LHSType,
  1193. QualType RHSType,
  1194. bool IsCompAssign) {
  1195. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1196. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1197. if (LHSComplexInt && RHSComplexInt) {
  1198. QualType LHSEltType = LHSComplexInt->getElementType();
  1199. QualType RHSEltType = RHSComplexInt->getElementType();
  1200. QualType ScalarType =
  1201. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1202. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1203. return S.Context.getComplexType(ScalarType);
  1204. }
  1205. if (LHSComplexInt) {
  1206. QualType LHSEltType = LHSComplexInt->getElementType();
  1207. QualType ScalarType =
  1208. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1209. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1210. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1211. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1212. CK_IntegralRealToComplex);
  1213. return ComplexType;
  1214. }
  1215. assert(RHSComplexInt);
  1216. QualType RHSEltType = RHSComplexInt->getElementType();
  1217. QualType ScalarType =
  1218. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1219. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1220. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1221. if (!IsCompAssign)
  1222. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1223. CK_IntegralRealToComplex);
  1224. return ComplexType;
  1225. }
  1226. /// Return the rank of a given fixed point or integer type. The value itself
  1227. /// doesn't matter, but the values must be increasing with proper increasing
  1228. /// rank as described in N1169 4.1.1.
  1229. static unsigned GetFixedPointRank(QualType Ty) {
  1230. const auto *BTy = Ty->getAs<BuiltinType>();
  1231. assert(BTy && "Expected a builtin type.");
  1232. switch (BTy->getKind()) {
  1233. case BuiltinType::ShortFract:
  1234. case BuiltinType::UShortFract:
  1235. case BuiltinType::SatShortFract:
  1236. case BuiltinType::SatUShortFract:
  1237. return 1;
  1238. case BuiltinType::Fract:
  1239. case BuiltinType::UFract:
  1240. case BuiltinType::SatFract:
  1241. case BuiltinType::SatUFract:
  1242. return 2;
  1243. case BuiltinType::LongFract:
  1244. case BuiltinType::ULongFract:
  1245. case BuiltinType::SatLongFract:
  1246. case BuiltinType::SatULongFract:
  1247. return 3;
  1248. case BuiltinType::ShortAccum:
  1249. case BuiltinType::UShortAccum:
  1250. case BuiltinType::SatShortAccum:
  1251. case BuiltinType::SatUShortAccum:
  1252. return 4;
  1253. case BuiltinType::Accum:
  1254. case BuiltinType::UAccum:
  1255. case BuiltinType::SatAccum:
  1256. case BuiltinType::SatUAccum:
  1257. return 5;
  1258. case BuiltinType::LongAccum:
  1259. case BuiltinType::ULongAccum:
  1260. case BuiltinType::SatLongAccum:
  1261. case BuiltinType::SatULongAccum:
  1262. return 6;
  1263. default:
  1264. if (BTy->isInteger())
  1265. return 0;
  1266. llvm_unreachable("Unexpected fixed point or integer type");
  1267. }
  1268. }
  1269. /// handleFixedPointConversion - Fixed point operations between fixed
  1270. /// point types and integers or other fixed point types do not fall under
  1271. /// usual arithmetic conversion since these conversions could result in loss
  1272. /// of precsision (N1169 4.1.4). These operations should be calculated with
  1273. /// the full precision of their result type (N1169 4.1.6.2.1).
  1274. static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
  1275. QualType RHSTy) {
  1276. assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
  1277. "Expected at least one of the operands to be a fixed point type");
  1278. assert((LHSTy->isFixedPointOrIntegerType() ||
  1279. RHSTy->isFixedPointOrIntegerType()) &&
  1280. "Special fixed point arithmetic operation conversions are only "
  1281. "applied to ints or other fixed point types");
  1282. // If one operand has signed fixed-point type and the other operand has
  1283. // unsigned fixed-point type, then the unsigned fixed-point operand is
  1284. // converted to its corresponding signed fixed-point type and the resulting
  1285. // type is the type of the converted operand.
  1286. if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
  1287. LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
  1288. else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
  1289. RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
  1290. // The result type is the type with the highest rank, whereby a fixed-point
  1291. // conversion rank is always greater than an integer conversion rank; if the
  1292. // type of either of the operands is a saturating fixedpoint type, the result
  1293. // type shall be the saturating fixed-point type corresponding to the type
  1294. // with the highest rank; the resulting value is converted (taking into
  1295. // account rounding and overflow) to the precision of the resulting type.
  1296. // Same ranks between signed and unsigned types are resolved earlier, so both
  1297. // types are either signed or both unsigned at this point.
  1298. unsigned LHSTyRank = GetFixedPointRank(LHSTy);
  1299. unsigned RHSTyRank = GetFixedPointRank(RHSTy);
  1300. QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
  1301. if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
  1302. ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
  1303. return ResultTy;
  1304. }
  1305. /// Check that the usual arithmetic conversions can be performed on this pair of
  1306. /// expressions that might be of enumeration type.
  1307. static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
  1308. SourceLocation Loc,
  1309. Sema::ArithConvKind ACK) {
  1310. // C++2a [expr.arith.conv]p1:
  1311. // If one operand is of enumeration type and the other operand is of a
  1312. // different enumeration type or a floating-point type, this behavior is
  1313. // deprecated ([depr.arith.conv.enum]).
  1314. //
  1315. // Warn on this in all language modes. Produce a deprecation warning in C++20.
  1316. // Eventually we will presumably reject these cases (in C++23 onwards?).
  1317. QualType L = LHS->getType(), R = RHS->getType();
  1318. bool LEnum = L->isUnscopedEnumerationType(),
  1319. REnum = R->isUnscopedEnumerationType();
  1320. bool IsCompAssign = ACK == Sema::ACK_CompAssign;
  1321. if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
  1322. (REnum && L->isFloatingType())) {
  1323. S.Diag(Loc, S.getLangOpts().CPlusPlus20
  1324. ? diag::warn_arith_conv_enum_float_cxx20
  1325. : diag::warn_arith_conv_enum_float)
  1326. << LHS->getSourceRange() << RHS->getSourceRange()
  1327. << (int)ACK << LEnum << L << R;
  1328. } else if (!IsCompAssign && LEnum && REnum &&
  1329. !S.Context.hasSameUnqualifiedType(L, R)) {
  1330. unsigned DiagID;
  1331. if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
  1332. !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
  1333. // If either enumeration type is unnamed, it's less likely that the
  1334. // user cares about this, but this situation is still deprecated in
  1335. // C++2a. Use a different warning group.
  1336. DiagID = S.getLangOpts().CPlusPlus20
  1337. ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
  1338. : diag::warn_arith_conv_mixed_anon_enum_types;
  1339. } else if (ACK == Sema::ACK_Conditional) {
  1340. // Conditional expressions are separated out because they have
  1341. // historically had a different warning flag.
  1342. DiagID = S.getLangOpts().CPlusPlus20
  1343. ? diag::warn_conditional_mixed_enum_types_cxx20
  1344. : diag::warn_conditional_mixed_enum_types;
  1345. } else if (ACK == Sema::ACK_Comparison) {
  1346. // Comparison expressions are separated out because they have
  1347. // historically had a different warning flag.
  1348. DiagID = S.getLangOpts().CPlusPlus20
  1349. ? diag::warn_comparison_mixed_enum_types_cxx20
  1350. : diag::warn_comparison_mixed_enum_types;
  1351. } else {
  1352. DiagID = S.getLangOpts().CPlusPlus20
  1353. ? diag::warn_arith_conv_mixed_enum_types_cxx20
  1354. : diag::warn_arith_conv_mixed_enum_types;
  1355. }
  1356. S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
  1357. << (int)ACK << L << R;
  1358. }
  1359. }
  1360. /// UsualArithmeticConversions - Performs various conversions that are common to
  1361. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1362. /// routine returns the first non-arithmetic type found. The client is
  1363. /// responsible for emitting appropriate error diagnostics.
  1364. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1365. SourceLocation Loc,
  1366. ArithConvKind ACK) {
  1367. checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
  1368. if (ACK != ACK_CompAssign) {
  1369. LHS = UsualUnaryConversions(LHS.get());
  1370. if (LHS.isInvalid())
  1371. return QualType();
  1372. }
  1373. RHS = UsualUnaryConversions(RHS.get());
  1374. if (RHS.isInvalid())
  1375. return QualType();
  1376. // For conversion purposes, we ignore any qualifiers.
  1377. // For example, "const float" and "float" are equivalent.
  1378. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  1379. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  1380. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1381. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1382. LHSType = AtomicLHS->getValueType();
  1383. // If both types are identical, no conversion is needed.
  1384. if (Context.hasSameType(LHSType, RHSType))
  1385. return Context.getCommonSugaredType(LHSType, RHSType);
  1386. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1387. // The caller can deal with this (e.g. pointer + int).
  1388. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1389. return QualType();
  1390. // Apply unary and bitfield promotions to the LHS's type.
  1391. QualType LHSUnpromotedType = LHSType;
  1392. if (Context.isPromotableIntegerType(LHSType))
  1393. LHSType = Context.getPromotedIntegerType(LHSType);
  1394. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1395. if (!LHSBitfieldPromoteTy.isNull())
  1396. LHSType = LHSBitfieldPromoteTy;
  1397. if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
  1398. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1399. // If both types are identical, no conversion is needed.
  1400. if (Context.hasSameType(LHSType, RHSType))
  1401. return Context.getCommonSugaredType(LHSType, RHSType);
  1402. // At this point, we have two different arithmetic types.
  1403. // Diagnose attempts to convert between __ibm128, __float128 and long double
  1404. // where such conversions currently can't be handled.
  1405. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1406. return QualType();
  1407. // Handle complex types first (C99 6.3.1.8p1).
  1408. if (LHSType->isComplexType() || RHSType->isComplexType())
  1409. return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
  1410. ACK == ACK_CompAssign);
  1411. // Now handle "real" floating types (i.e. float, double, long double).
  1412. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1413. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1414. ACK == ACK_CompAssign);
  1415. // Handle GCC complex int extension.
  1416. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1417. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1418. ACK == ACK_CompAssign);
  1419. if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
  1420. return handleFixedPointConversion(*this, LHSType, RHSType);
  1421. // Finally, we have two differing integer types.
  1422. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1423. (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
  1424. }
  1425. //===----------------------------------------------------------------------===//
  1426. // Semantic Analysis for various Expression Types
  1427. //===----------------------------------------------------------------------===//
  1428. ExprResult
  1429. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1430. SourceLocation DefaultLoc,
  1431. SourceLocation RParenLoc,
  1432. Expr *ControllingExpr,
  1433. ArrayRef<ParsedType> ArgTypes,
  1434. ArrayRef<Expr *> ArgExprs) {
  1435. unsigned NumAssocs = ArgTypes.size();
  1436. assert(NumAssocs == ArgExprs.size());
  1437. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1438. for (unsigned i = 0; i < NumAssocs; ++i) {
  1439. if (ArgTypes[i])
  1440. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1441. else
  1442. Types[i] = nullptr;
  1443. }
  1444. ExprResult ER =
  1445. CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr,
  1446. llvm::ArrayRef(Types, NumAssocs), ArgExprs);
  1447. delete [] Types;
  1448. return ER;
  1449. }
  1450. ExprResult
  1451. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1452. SourceLocation DefaultLoc,
  1453. SourceLocation RParenLoc,
  1454. Expr *ControllingExpr,
  1455. ArrayRef<TypeSourceInfo *> Types,
  1456. ArrayRef<Expr *> Exprs) {
  1457. unsigned NumAssocs = Types.size();
  1458. assert(NumAssocs == Exprs.size());
  1459. // Decay and strip qualifiers for the controlling expression type, and handle
  1460. // placeholder type replacement. See committee discussion from WG14 DR423.
  1461. {
  1462. EnterExpressionEvaluationContext Unevaluated(
  1463. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1464. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1465. if (R.isInvalid())
  1466. return ExprError();
  1467. ControllingExpr = R.get();
  1468. }
  1469. bool TypeErrorFound = false,
  1470. IsResultDependent = ControllingExpr->isTypeDependent(),
  1471. ContainsUnexpandedParameterPack
  1472. = ControllingExpr->containsUnexpandedParameterPack();
  1473. // The controlling expression is an unevaluated operand, so side effects are
  1474. // likely unintended.
  1475. if (!inTemplateInstantiation() && !IsResultDependent &&
  1476. ControllingExpr->HasSideEffects(Context, false))
  1477. Diag(ControllingExpr->getExprLoc(),
  1478. diag::warn_side_effects_unevaluated_context);
  1479. for (unsigned i = 0; i < NumAssocs; ++i) {
  1480. if (Exprs[i]->containsUnexpandedParameterPack())
  1481. ContainsUnexpandedParameterPack = true;
  1482. if (Types[i]) {
  1483. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1484. ContainsUnexpandedParameterPack = true;
  1485. if (Types[i]->getType()->isDependentType()) {
  1486. IsResultDependent = true;
  1487. } else {
  1488. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1489. // complete object type other than a variably modified type."
  1490. unsigned D = 0;
  1491. if (Types[i]->getType()->isIncompleteType())
  1492. D = diag::err_assoc_type_incomplete;
  1493. else if (!Types[i]->getType()->isObjectType())
  1494. D = diag::err_assoc_type_nonobject;
  1495. else if (Types[i]->getType()->isVariablyModifiedType())
  1496. D = diag::err_assoc_type_variably_modified;
  1497. else {
  1498. // Because the controlling expression undergoes lvalue conversion,
  1499. // array conversion, and function conversion, an association which is
  1500. // of array type, function type, or is qualified can never be
  1501. // reached. We will warn about this so users are less surprised by
  1502. // the unreachable association. However, we don't have to handle
  1503. // function types; that's not an object type, so it's handled above.
  1504. //
  1505. // The logic is somewhat different for C++ because C++ has different
  1506. // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
  1507. // If T is a non-class type, the type of the prvalue is the cv-
  1508. // unqualified version of T. Otherwise, the type of the prvalue is T.
  1509. // The result of these rules is that all qualified types in an
  1510. // association in C are unreachable, and in C++, only qualified non-
  1511. // class types are unreachable.
  1512. unsigned Reason = 0;
  1513. QualType QT = Types[i]->getType();
  1514. if (QT->isArrayType())
  1515. Reason = 1;
  1516. else if (QT.hasQualifiers() &&
  1517. (!LangOpts.CPlusPlus || !QT->isRecordType()))
  1518. Reason = 2;
  1519. if (Reason)
  1520. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1521. diag::warn_unreachable_association)
  1522. << QT << (Reason - 1);
  1523. }
  1524. if (D != 0) {
  1525. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1526. << Types[i]->getTypeLoc().getSourceRange()
  1527. << Types[i]->getType();
  1528. TypeErrorFound = true;
  1529. }
  1530. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1531. // selection shall specify compatible types."
  1532. for (unsigned j = i+1; j < NumAssocs; ++j)
  1533. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1534. Context.typesAreCompatible(Types[i]->getType(),
  1535. Types[j]->getType())) {
  1536. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1537. diag::err_assoc_compatible_types)
  1538. << Types[j]->getTypeLoc().getSourceRange()
  1539. << Types[j]->getType()
  1540. << Types[i]->getType();
  1541. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1542. diag::note_compat_assoc)
  1543. << Types[i]->getTypeLoc().getSourceRange()
  1544. << Types[i]->getType();
  1545. TypeErrorFound = true;
  1546. }
  1547. }
  1548. }
  1549. }
  1550. if (TypeErrorFound)
  1551. return ExprError();
  1552. // If we determined that the generic selection is result-dependent, don't
  1553. // try to compute the result expression.
  1554. if (IsResultDependent)
  1555. return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
  1556. Exprs, DefaultLoc, RParenLoc,
  1557. ContainsUnexpandedParameterPack);
  1558. SmallVector<unsigned, 1> CompatIndices;
  1559. unsigned DefaultIndex = -1U;
  1560. // Look at the canonical type of the controlling expression in case it was a
  1561. // deduced type like __auto_type. However, when issuing diagnostics, use the
  1562. // type the user wrote in source rather than the canonical one.
  1563. for (unsigned i = 0; i < NumAssocs; ++i) {
  1564. if (!Types[i])
  1565. DefaultIndex = i;
  1566. else if (Context.typesAreCompatible(
  1567. ControllingExpr->getType().getCanonicalType(),
  1568. Types[i]->getType()))
  1569. CompatIndices.push_back(i);
  1570. }
  1571. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1572. // type compatible with at most one of the types named in its generic
  1573. // association list."
  1574. if (CompatIndices.size() > 1) {
  1575. // We strip parens here because the controlling expression is typically
  1576. // parenthesized in macro definitions.
  1577. ControllingExpr = ControllingExpr->IgnoreParens();
  1578. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
  1579. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1580. << (unsigned)CompatIndices.size();
  1581. for (unsigned I : CompatIndices) {
  1582. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1583. diag::note_compat_assoc)
  1584. << Types[I]->getTypeLoc().getSourceRange()
  1585. << Types[I]->getType();
  1586. }
  1587. return ExprError();
  1588. }
  1589. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1590. // its controlling expression shall have type compatible with exactly one of
  1591. // the types named in its generic association list."
  1592. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1593. // We strip parens here because the controlling expression is typically
  1594. // parenthesized in macro definitions.
  1595. ControllingExpr = ControllingExpr->IgnoreParens();
  1596. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
  1597. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1598. return ExprError();
  1599. }
  1600. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1601. // type name that is compatible with the type of the controlling expression,
  1602. // then the result expression of the generic selection is the expression
  1603. // in that generic association. Otherwise, the result expression of the
  1604. // generic selection is the expression in the default generic association."
  1605. unsigned ResultIndex =
  1606. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1607. return GenericSelectionExpr::Create(
  1608. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1609. ContainsUnexpandedParameterPack, ResultIndex);
  1610. }
  1611. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1612. /// location of the token and the offset of the ud-suffix within it.
  1613. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1614. unsigned Offset) {
  1615. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1616. S.getLangOpts());
  1617. }
  1618. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1619. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1620. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1621. IdentifierInfo *UDSuffix,
  1622. SourceLocation UDSuffixLoc,
  1623. ArrayRef<Expr*> Args,
  1624. SourceLocation LitEndLoc) {
  1625. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1626. QualType ArgTy[2];
  1627. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1628. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1629. if (ArgTy[ArgIdx]->isArrayType())
  1630. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1631. }
  1632. DeclarationName OpName =
  1633. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1634. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1635. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1636. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1637. if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
  1638. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1639. /*AllowStringTemplatePack*/ false,
  1640. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1641. return ExprError();
  1642. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1643. }
  1644. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1645. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1646. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1647. /// multiple tokens. However, the common case is that StringToks points to one
  1648. /// string.
  1649. ///
  1650. ExprResult
  1651. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1652. assert(!StringToks.empty() && "Must have at least one string!");
  1653. StringLiteralParser Literal(StringToks, PP);
  1654. if (Literal.hadError)
  1655. return ExprError();
  1656. SmallVector<SourceLocation, 4> StringTokLocs;
  1657. for (const Token &Tok : StringToks)
  1658. StringTokLocs.push_back(Tok.getLocation());
  1659. QualType CharTy = Context.CharTy;
  1660. StringLiteral::StringKind Kind = StringLiteral::Ordinary;
  1661. if (Literal.isWide()) {
  1662. CharTy = Context.getWideCharType();
  1663. Kind = StringLiteral::Wide;
  1664. } else if (Literal.isUTF8()) {
  1665. if (getLangOpts().Char8)
  1666. CharTy = Context.Char8Ty;
  1667. Kind = StringLiteral::UTF8;
  1668. } else if (Literal.isUTF16()) {
  1669. CharTy = Context.Char16Ty;
  1670. Kind = StringLiteral::UTF16;
  1671. } else if (Literal.isUTF32()) {
  1672. CharTy = Context.Char32Ty;
  1673. Kind = StringLiteral::UTF32;
  1674. } else if (Literal.isPascal()) {
  1675. CharTy = Context.UnsignedCharTy;
  1676. }
  1677. // Warn on initializing an array of char from a u8 string literal; this
  1678. // becomes ill-formed in C++2a.
  1679. if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
  1680. !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
  1681. Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
  1682. // Create removals for all 'u8' prefixes in the string literal(s). This
  1683. // ensures C++2a compatibility (but may change the program behavior when
  1684. // built by non-Clang compilers for which the execution character set is
  1685. // not always UTF-8).
  1686. auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
  1687. SourceLocation RemovalDiagLoc;
  1688. for (const Token &Tok : StringToks) {
  1689. if (Tok.getKind() == tok::utf8_string_literal) {
  1690. if (RemovalDiagLoc.isInvalid())
  1691. RemovalDiagLoc = Tok.getLocation();
  1692. RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
  1693. Tok.getLocation(),
  1694. Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
  1695. getSourceManager(), getLangOpts())));
  1696. }
  1697. }
  1698. Diag(RemovalDiagLoc, RemovalDiag);
  1699. }
  1700. QualType StrTy =
  1701. Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
  1702. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1703. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1704. Kind, Literal.Pascal, StrTy,
  1705. &StringTokLocs[0],
  1706. StringTokLocs.size());
  1707. if (Literal.getUDSuffix().empty())
  1708. return Lit;
  1709. // We're building a user-defined literal.
  1710. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1711. SourceLocation UDSuffixLoc =
  1712. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1713. Literal.getUDSuffixOffset());
  1714. // Make sure we're allowed user-defined literals here.
  1715. if (!UDLScope)
  1716. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1717. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1718. // operator "" X (str, len)
  1719. QualType SizeType = Context.getSizeType();
  1720. DeclarationName OpName =
  1721. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1722. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1723. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1724. QualType ArgTy[] = {
  1725. Context.getArrayDecayedType(StrTy), SizeType
  1726. };
  1727. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1728. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1729. /*AllowRaw*/ false, /*AllowTemplate*/ true,
  1730. /*AllowStringTemplatePack*/ true,
  1731. /*DiagnoseMissing*/ true, Lit)) {
  1732. case LOLR_Cooked: {
  1733. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1734. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1735. StringTokLocs[0]);
  1736. Expr *Args[] = { Lit, LenArg };
  1737. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1738. }
  1739. case LOLR_Template: {
  1740. TemplateArgumentListInfo ExplicitArgs;
  1741. TemplateArgument Arg(Lit);
  1742. TemplateArgumentLocInfo ArgInfo(Lit);
  1743. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1744. return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
  1745. StringTokLocs.back(), &ExplicitArgs);
  1746. }
  1747. case LOLR_StringTemplatePack: {
  1748. TemplateArgumentListInfo ExplicitArgs;
  1749. unsigned CharBits = Context.getIntWidth(CharTy);
  1750. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1751. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1752. TemplateArgument TypeArg(CharTy);
  1753. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1754. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1755. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1756. Value = Lit->getCodeUnit(I);
  1757. TemplateArgument Arg(Context, Value, CharTy);
  1758. TemplateArgumentLocInfo ArgInfo;
  1759. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1760. }
  1761. return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
  1762. StringTokLocs.back(), &ExplicitArgs);
  1763. }
  1764. case LOLR_Raw:
  1765. case LOLR_ErrorNoDiagnostic:
  1766. llvm_unreachable("unexpected literal operator lookup result");
  1767. case LOLR_Error:
  1768. return ExprError();
  1769. }
  1770. llvm_unreachable("unexpected literal operator lookup result");
  1771. }
  1772. DeclRefExpr *
  1773. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1774. SourceLocation Loc,
  1775. const CXXScopeSpec *SS) {
  1776. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1777. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1778. }
  1779. DeclRefExpr *
  1780. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1781. const DeclarationNameInfo &NameInfo,
  1782. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1783. SourceLocation TemplateKWLoc,
  1784. const TemplateArgumentListInfo *TemplateArgs) {
  1785. NestedNameSpecifierLoc NNS =
  1786. SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
  1787. return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
  1788. TemplateArgs);
  1789. }
  1790. // CUDA/HIP: Check whether a captured reference variable is referencing a
  1791. // host variable in a device or host device lambda.
  1792. static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
  1793. VarDecl *VD) {
  1794. if (!S.getLangOpts().CUDA || !VD->hasInit())
  1795. return false;
  1796. assert(VD->getType()->isReferenceType());
  1797. // Check whether the reference variable is referencing a host variable.
  1798. auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
  1799. if (!DRE)
  1800. return false;
  1801. auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
  1802. if (!Referee || !Referee->hasGlobalStorage() ||
  1803. Referee->hasAttr<CUDADeviceAttr>())
  1804. return false;
  1805. // Check whether the current function is a device or host device lambda.
  1806. // Check whether the reference variable is a capture by getDeclContext()
  1807. // since refersToEnclosingVariableOrCapture() is not ready at this point.
  1808. auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
  1809. if (MD && MD->getParent()->isLambda() &&
  1810. MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
  1811. VD->getDeclContext() != MD)
  1812. return true;
  1813. return false;
  1814. }
  1815. NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
  1816. // A declaration named in an unevaluated operand never constitutes an odr-use.
  1817. if (isUnevaluatedContext())
  1818. return NOUR_Unevaluated;
  1819. // C++2a [basic.def.odr]p4:
  1820. // A variable x whose name appears as a potentially-evaluated expression e
  1821. // is odr-used by e unless [...] x is a reference that is usable in
  1822. // constant expressions.
  1823. // CUDA/HIP:
  1824. // If a reference variable referencing a host variable is captured in a
  1825. // device or host device lambda, the value of the referee must be copied
  1826. // to the capture and the reference variable must be treated as odr-use
  1827. // since the value of the referee is not known at compile time and must
  1828. // be loaded from the captured.
  1829. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1830. if (VD->getType()->isReferenceType() &&
  1831. !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
  1832. !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
  1833. VD->isUsableInConstantExpressions(Context))
  1834. return NOUR_Constant;
  1835. }
  1836. // All remaining non-variable cases constitute an odr-use. For variables, we
  1837. // need to wait and see how the expression is used.
  1838. return NOUR_None;
  1839. }
  1840. /// BuildDeclRefExpr - Build an expression that references a
  1841. /// declaration that does not require a closure capture.
  1842. DeclRefExpr *
  1843. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1844. const DeclarationNameInfo &NameInfo,
  1845. NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
  1846. SourceLocation TemplateKWLoc,
  1847. const TemplateArgumentListInfo *TemplateArgs) {
  1848. bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
  1849. NeedToCaptureVariable(D, NameInfo.getLoc());
  1850. DeclRefExpr *E = DeclRefExpr::Create(
  1851. Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
  1852. VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
  1853. MarkDeclRefReferenced(E);
  1854. // C++ [except.spec]p17:
  1855. // An exception-specification is considered to be needed when:
  1856. // - in an expression, the function is the unique lookup result or
  1857. // the selected member of a set of overloaded functions.
  1858. //
  1859. // We delay doing this until after we've built the function reference and
  1860. // marked it as used so that:
  1861. // a) if the function is defaulted, we get errors from defining it before /
  1862. // instead of errors from computing its exception specification, and
  1863. // b) if the function is a defaulted comparison, we can use the body we
  1864. // build when defining it as input to the exception specification
  1865. // computation rather than computing a new body.
  1866. if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
  1867. if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
  1868. if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
  1869. E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
  1870. }
  1871. }
  1872. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1873. Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
  1874. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
  1875. getCurFunction()->recordUseOfWeak(E);
  1876. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1877. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1878. FD = IFD->getAnonField();
  1879. if (FD) {
  1880. UnusedPrivateFields.remove(FD);
  1881. // Just in case we're building an illegal pointer-to-member.
  1882. if (FD->isBitField())
  1883. E->setObjectKind(OK_BitField);
  1884. }
  1885. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1886. // designates a bit-field.
  1887. if (auto *BD = dyn_cast<BindingDecl>(D))
  1888. if (auto *BE = BD->getBinding())
  1889. E->setObjectKind(BE->getObjectKind());
  1890. return E;
  1891. }
  1892. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1893. /// possibly a list of template arguments.
  1894. ///
  1895. /// If this produces template arguments, it is permitted to call
  1896. /// DecomposeTemplateName.
  1897. ///
  1898. /// This actually loses a lot of source location information for
  1899. /// non-standard name kinds; we should consider preserving that in
  1900. /// some way.
  1901. void
  1902. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1903. TemplateArgumentListInfo &Buffer,
  1904. DeclarationNameInfo &NameInfo,
  1905. const TemplateArgumentListInfo *&TemplateArgs) {
  1906. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
  1907. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1908. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1909. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1910. Id.TemplateId->NumArgs);
  1911. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1912. TemplateName TName = Id.TemplateId->Template.get();
  1913. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1914. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1915. TemplateArgs = &Buffer;
  1916. } else {
  1917. NameInfo = GetNameFromUnqualifiedId(Id);
  1918. TemplateArgs = nullptr;
  1919. }
  1920. }
  1921. static void emitEmptyLookupTypoDiagnostic(
  1922. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1923. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1924. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1925. DeclContext *Ctx =
  1926. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1927. if (!TC) {
  1928. // Emit a special diagnostic for failed member lookups.
  1929. // FIXME: computing the declaration context might fail here (?)
  1930. if (Ctx)
  1931. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1932. << SS.getRange();
  1933. else
  1934. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1935. return;
  1936. }
  1937. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1938. bool DroppedSpecifier =
  1939. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1940. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1941. ? diag::note_implicit_param_decl
  1942. : diag::note_previous_decl;
  1943. if (!Ctx)
  1944. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1945. SemaRef.PDiag(NoteID));
  1946. else
  1947. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1948. << Typo << Ctx << DroppedSpecifier
  1949. << SS.getRange(),
  1950. SemaRef.PDiag(NoteID));
  1951. }
  1952. /// Diagnose a lookup that found results in an enclosing class during error
  1953. /// recovery. This usually indicates that the results were found in a dependent
  1954. /// base class that could not be searched as part of a template definition.
  1955. /// Always issues a diagnostic (though this may be only a warning in MS
  1956. /// compatibility mode).
  1957. ///
  1958. /// Return \c true if the error is unrecoverable, or \c false if the caller
  1959. /// should attempt to recover using these lookup results.
  1960. bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
  1961. // During a default argument instantiation the CurContext points
  1962. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1963. // function parameter list, hence add an explicit check.
  1964. bool isDefaultArgument =
  1965. !CodeSynthesisContexts.empty() &&
  1966. CodeSynthesisContexts.back().Kind ==
  1967. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1968. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1969. bool isInstance = CurMethod && CurMethod->isInstance() &&
  1970. R.getNamingClass() == CurMethod->getParent() &&
  1971. !isDefaultArgument;
  1972. // There are two ways we can find a class-scope declaration during template
  1973. // instantiation that we did not find in the template definition: if it is a
  1974. // member of a dependent base class, or if it is declared after the point of
  1975. // use in the same class. Distinguish these by comparing the class in which
  1976. // the member was found to the naming class of the lookup.
  1977. unsigned DiagID = diag::err_found_in_dependent_base;
  1978. unsigned NoteID = diag::note_member_declared_at;
  1979. if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
  1980. DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
  1981. : diag::err_found_later_in_class;
  1982. } else if (getLangOpts().MSVCCompat) {
  1983. DiagID = diag::ext_found_in_dependent_base;
  1984. NoteID = diag::note_dependent_member_use;
  1985. }
  1986. if (isInstance) {
  1987. // Give a code modification hint to insert 'this->'.
  1988. Diag(R.getNameLoc(), DiagID)
  1989. << R.getLookupName()
  1990. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1991. CheckCXXThisCapture(R.getNameLoc());
  1992. } else {
  1993. // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
  1994. // they're not shadowed).
  1995. Diag(R.getNameLoc(), DiagID) << R.getLookupName();
  1996. }
  1997. for (NamedDecl *D : R)
  1998. Diag(D->getLocation(), NoteID);
  1999. // Return true if we are inside a default argument instantiation
  2000. // and the found name refers to an instance member function, otherwise
  2001. // the caller will try to create an implicit member call and this is wrong
  2002. // for default arguments.
  2003. //
  2004. // FIXME: Is this special case necessary? We could allow the caller to
  2005. // diagnose this.
  2006. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  2007. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  2008. return true;
  2009. }
  2010. // Tell the callee to try to recover.
  2011. return false;
  2012. }
  2013. /// Diagnose an empty lookup.
  2014. ///
  2015. /// \return false if new lookup candidates were found
  2016. bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  2017. CorrectionCandidateCallback &CCC,
  2018. TemplateArgumentListInfo *ExplicitTemplateArgs,
  2019. ArrayRef<Expr *> Args, TypoExpr **Out) {
  2020. DeclarationName Name = R.getLookupName();
  2021. unsigned diagnostic = diag::err_undeclared_var_use;
  2022. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  2023. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  2024. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  2025. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  2026. diagnostic = diag::err_undeclared_use;
  2027. diagnostic_suggest = diag::err_undeclared_use_suggest;
  2028. }
  2029. // If the original lookup was an unqualified lookup, fake an
  2030. // unqualified lookup. This is useful when (for example) the
  2031. // original lookup would not have found something because it was a
  2032. // dependent name.
  2033. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  2034. while (DC) {
  2035. if (isa<CXXRecordDecl>(DC)) {
  2036. LookupQualifiedName(R, DC);
  2037. if (!R.empty()) {
  2038. // Don't give errors about ambiguities in this lookup.
  2039. R.suppressDiagnostics();
  2040. // If there's a best viable function among the results, only mention
  2041. // that one in the notes.
  2042. OverloadCandidateSet Candidates(R.getNameLoc(),
  2043. OverloadCandidateSet::CSK_Normal);
  2044. AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
  2045. OverloadCandidateSet::iterator Best;
  2046. if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
  2047. OR_Success) {
  2048. R.clear();
  2049. R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
  2050. R.resolveKind();
  2051. }
  2052. return DiagnoseDependentMemberLookup(R);
  2053. }
  2054. R.clear();
  2055. }
  2056. DC = DC->getLookupParent();
  2057. }
  2058. // We didn't find anything, so try to correct for a typo.
  2059. TypoCorrection Corrected;
  2060. if (S && Out) {
  2061. SourceLocation TypoLoc = R.getNameLoc();
  2062. assert(!ExplicitTemplateArgs &&
  2063. "Diagnosing an empty lookup with explicit template args!");
  2064. *Out = CorrectTypoDelayed(
  2065. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  2066. [=](const TypoCorrection &TC) {
  2067. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  2068. diagnostic, diagnostic_suggest);
  2069. },
  2070. nullptr, CTK_ErrorRecovery);
  2071. if (*Out)
  2072. return true;
  2073. } else if (S &&
  2074. (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
  2075. S, &SS, CCC, CTK_ErrorRecovery))) {
  2076. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  2077. bool DroppedSpecifier =
  2078. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  2079. R.setLookupName(Corrected.getCorrection());
  2080. bool AcceptableWithRecovery = false;
  2081. bool AcceptableWithoutRecovery = false;
  2082. NamedDecl *ND = Corrected.getFoundDecl();
  2083. if (ND) {
  2084. if (Corrected.isOverloaded()) {
  2085. OverloadCandidateSet OCS(R.getNameLoc(),
  2086. OverloadCandidateSet::CSK_Normal);
  2087. OverloadCandidateSet::iterator Best;
  2088. for (NamedDecl *CD : Corrected) {
  2089. if (FunctionTemplateDecl *FTD =
  2090. dyn_cast<FunctionTemplateDecl>(CD))
  2091. AddTemplateOverloadCandidate(
  2092. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  2093. Args, OCS);
  2094. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  2095. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  2096. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  2097. Args, OCS);
  2098. }
  2099. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  2100. case OR_Success:
  2101. ND = Best->FoundDecl;
  2102. Corrected.setCorrectionDecl(ND);
  2103. break;
  2104. default:
  2105. // FIXME: Arbitrarily pick the first declaration for the note.
  2106. Corrected.setCorrectionDecl(ND);
  2107. break;
  2108. }
  2109. }
  2110. R.addDecl(ND);
  2111. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  2112. CXXRecordDecl *Record = nullptr;
  2113. if (Corrected.getCorrectionSpecifier()) {
  2114. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  2115. Record = Ty->getAsCXXRecordDecl();
  2116. }
  2117. if (!Record)
  2118. Record = cast<CXXRecordDecl>(
  2119. ND->getDeclContext()->getRedeclContext());
  2120. R.setNamingClass(Record);
  2121. }
  2122. auto *UnderlyingND = ND->getUnderlyingDecl();
  2123. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  2124. isa<FunctionTemplateDecl>(UnderlyingND);
  2125. // FIXME: If we ended up with a typo for a type name or
  2126. // Objective-C class name, we're in trouble because the parser
  2127. // is in the wrong place to recover. Suggest the typo
  2128. // correction, but don't make it a fix-it since we're not going
  2129. // to recover well anyway.
  2130. AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
  2131. getAsTypeTemplateDecl(UnderlyingND) ||
  2132. isa<ObjCInterfaceDecl>(UnderlyingND);
  2133. } else {
  2134. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  2135. // because we aren't able to recover.
  2136. AcceptableWithoutRecovery = true;
  2137. }
  2138. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  2139. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  2140. ? diag::note_implicit_param_decl
  2141. : diag::note_previous_decl;
  2142. if (SS.isEmpty())
  2143. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  2144. PDiag(NoteID), AcceptableWithRecovery);
  2145. else
  2146. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  2147. << Name << computeDeclContext(SS, false)
  2148. << DroppedSpecifier << SS.getRange(),
  2149. PDiag(NoteID), AcceptableWithRecovery);
  2150. // Tell the callee whether to try to recover.
  2151. return !AcceptableWithRecovery;
  2152. }
  2153. }
  2154. R.clear();
  2155. // Emit a special diagnostic for failed member lookups.
  2156. // FIXME: computing the declaration context might fail here (?)
  2157. if (!SS.isEmpty()) {
  2158. Diag(R.getNameLoc(), diag::err_no_member)
  2159. << Name << computeDeclContext(SS, false)
  2160. << SS.getRange();
  2161. return true;
  2162. }
  2163. // Give up, we can't recover.
  2164. Diag(R.getNameLoc(), diagnostic) << Name;
  2165. return true;
  2166. }
  2167. /// In Microsoft mode, if we are inside a template class whose parent class has
  2168. /// dependent base classes, and we can't resolve an unqualified identifier, then
  2169. /// assume the identifier is a member of a dependent base class. We can only
  2170. /// recover successfully in static methods, instance methods, and other contexts
  2171. /// where 'this' is available. This doesn't precisely match MSVC's
  2172. /// instantiation model, but it's close enough.
  2173. static Expr *
  2174. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  2175. DeclarationNameInfo &NameInfo,
  2176. SourceLocation TemplateKWLoc,
  2177. const TemplateArgumentListInfo *TemplateArgs) {
  2178. // Only try to recover from lookup into dependent bases in static methods or
  2179. // contexts where 'this' is available.
  2180. QualType ThisType = S.getCurrentThisType();
  2181. const CXXRecordDecl *RD = nullptr;
  2182. if (!ThisType.isNull())
  2183. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  2184. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  2185. RD = MD->getParent();
  2186. if (!RD || !RD->hasAnyDependentBases())
  2187. return nullptr;
  2188. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  2189. // is available, suggest inserting 'this->' as a fixit.
  2190. SourceLocation Loc = NameInfo.getLoc();
  2191. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  2192. DB << NameInfo.getName() << RD;
  2193. if (!ThisType.isNull()) {
  2194. DB << FixItHint::CreateInsertion(Loc, "this->");
  2195. return CXXDependentScopeMemberExpr::Create(
  2196. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  2197. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  2198. /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
  2199. }
  2200. // Synthesize a fake NNS that points to the derived class. This will
  2201. // perform name lookup during template instantiation.
  2202. CXXScopeSpec SS;
  2203. auto *NNS =
  2204. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  2205. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  2206. return DependentScopeDeclRefExpr::Create(
  2207. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  2208. TemplateArgs);
  2209. }
  2210. ExprResult
  2211. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  2212. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  2213. bool HasTrailingLParen, bool IsAddressOfOperand,
  2214. CorrectionCandidateCallback *CCC,
  2215. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  2216. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  2217. "cannot be direct & operand and have a trailing lparen");
  2218. if (SS.isInvalid())
  2219. return ExprError();
  2220. TemplateArgumentListInfo TemplateArgsBuffer;
  2221. // Decompose the UnqualifiedId into the following data.
  2222. DeclarationNameInfo NameInfo;
  2223. const TemplateArgumentListInfo *TemplateArgs;
  2224. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  2225. DeclarationName Name = NameInfo.getName();
  2226. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2227. SourceLocation NameLoc = NameInfo.getLoc();
  2228. if (II && II->isEditorPlaceholder()) {
  2229. // FIXME: When typed placeholders are supported we can create a typed
  2230. // placeholder expression node.
  2231. return ExprError();
  2232. }
  2233. // C++ [temp.dep.expr]p3:
  2234. // An id-expression is type-dependent if it contains:
  2235. // -- an identifier that was declared with a dependent type,
  2236. // (note: handled after lookup)
  2237. // -- a template-id that is dependent,
  2238. // (note: handled in BuildTemplateIdExpr)
  2239. // -- a conversion-function-id that specifies a dependent type,
  2240. // -- a nested-name-specifier that contains a class-name that
  2241. // names a dependent type.
  2242. // Determine whether this is a member of an unknown specialization;
  2243. // we need to handle these differently.
  2244. bool DependentID = false;
  2245. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  2246. Name.getCXXNameType()->isDependentType()) {
  2247. DependentID = true;
  2248. } else if (SS.isSet()) {
  2249. if (DeclContext *DC = computeDeclContext(SS, false)) {
  2250. if (RequireCompleteDeclContext(SS, DC))
  2251. return ExprError();
  2252. } else {
  2253. DependentID = true;
  2254. }
  2255. }
  2256. if (DependentID)
  2257. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  2258. IsAddressOfOperand, TemplateArgs);
  2259. // Perform the required lookup.
  2260. LookupResult R(*this, NameInfo,
  2261. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  2262. ? LookupObjCImplicitSelfParam
  2263. : LookupOrdinaryName);
  2264. if (TemplateKWLoc.isValid() || TemplateArgs) {
  2265. // Lookup the template name again to correctly establish the context in
  2266. // which it was found. This is really unfortunate as we already did the
  2267. // lookup to determine that it was a template name in the first place. If
  2268. // this becomes a performance hit, we can work harder to preserve those
  2269. // results until we get here but it's likely not worth it.
  2270. bool MemberOfUnknownSpecialization;
  2271. AssumedTemplateKind AssumedTemplate;
  2272. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  2273. MemberOfUnknownSpecialization, TemplateKWLoc,
  2274. &AssumedTemplate))
  2275. return ExprError();
  2276. if (MemberOfUnknownSpecialization ||
  2277. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  2278. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  2279. IsAddressOfOperand, TemplateArgs);
  2280. } else {
  2281. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  2282. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  2283. // If the result might be in a dependent base class, this is a dependent
  2284. // id-expression.
  2285. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2286. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  2287. IsAddressOfOperand, TemplateArgs);
  2288. // If this reference is in an Objective-C method, then we need to do
  2289. // some special Objective-C lookup, too.
  2290. if (IvarLookupFollowUp) {
  2291. ExprResult E(LookupInObjCMethod(R, S, II, true));
  2292. if (E.isInvalid())
  2293. return ExprError();
  2294. if (Expr *Ex = E.getAs<Expr>())
  2295. return Ex;
  2296. }
  2297. }
  2298. if (R.isAmbiguous())
  2299. return ExprError();
  2300. // This could be an implicitly declared function reference if the language
  2301. // mode allows it as a feature.
  2302. if (R.empty() && HasTrailingLParen && II &&
  2303. getLangOpts().implicitFunctionsAllowed()) {
  2304. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  2305. if (D) R.addDecl(D);
  2306. }
  2307. // Determine whether this name might be a candidate for
  2308. // argument-dependent lookup.
  2309. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  2310. if (R.empty() && !ADL) {
  2311. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  2312. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  2313. TemplateKWLoc, TemplateArgs))
  2314. return E;
  2315. }
  2316. // Don't diagnose an empty lookup for inline assembly.
  2317. if (IsInlineAsmIdentifier)
  2318. return ExprError();
  2319. // If this name wasn't predeclared and if this is not a function
  2320. // call, diagnose the problem.
  2321. TypoExpr *TE = nullptr;
  2322. DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
  2323. : nullptr);
  2324. DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
  2325. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  2326. "Typo correction callback misconfigured");
  2327. if (CCC) {
  2328. // Make sure the callback knows what the typo being diagnosed is.
  2329. CCC->setTypoName(II);
  2330. if (SS.isValid())
  2331. CCC->setTypoNNS(SS.getScopeRep());
  2332. }
  2333. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  2334. // a template name, but we happen to have always already looked up the name
  2335. // before we get here if it must be a template name.
  2336. if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
  2337. std::nullopt, &TE)) {
  2338. if (TE && KeywordReplacement) {
  2339. auto &State = getTypoExprState(TE);
  2340. auto BestTC = State.Consumer->getNextCorrection();
  2341. if (BestTC.isKeyword()) {
  2342. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  2343. if (State.DiagHandler)
  2344. State.DiagHandler(BestTC);
  2345. KeywordReplacement->startToken();
  2346. KeywordReplacement->setKind(II->getTokenID());
  2347. KeywordReplacement->setIdentifierInfo(II);
  2348. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  2349. // Clean up the state associated with the TypoExpr, since it has
  2350. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  2351. clearDelayedTypo(TE);
  2352. // Signal that a correction to a keyword was performed by returning a
  2353. // valid-but-null ExprResult.
  2354. return (Expr*)nullptr;
  2355. }
  2356. State.Consumer->resetCorrectionStream();
  2357. }
  2358. return TE ? TE : ExprError();
  2359. }
  2360. assert(!R.empty() &&
  2361. "DiagnoseEmptyLookup returned false but added no results");
  2362. // If we found an Objective-C instance variable, let
  2363. // LookupInObjCMethod build the appropriate expression to
  2364. // reference the ivar.
  2365. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  2366. R.clear();
  2367. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  2368. // In a hopelessly buggy code, Objective-C instance variable
  2369. // lookup fails and no expression will be built to reference it.
  2370. if (!E.isInvalid() && !E.get())
  2371. return ExprError();
  2372. return E;
  2373. }
  2374. }
  2375. // This is guaranteed from this point on.
  2376. assert(!R.empty() || ADL);
  2377. // Check whether this might be a C++ implicit instance member access.
  2378. // C++ [class.mfct.non-static]p3:
  2379. // When an id-expression that is not part of a class member access
  2380. // syntax and not used to form a pointer to member is used in the
  2381. // body of a non-static member function of class X, if name lookup
  2382. // resolves the name in the id-expression to a non-static non-type
  2383. // member of some class C, the id-expression is transformed into a
  2384. // class member access expression using (*this) as the
  2385. // postfix-expression to the left of the . operator.
  2386. //
  2387. // But we don't actually need to do this for '&' operands if R
  2388. // resolved to a function or overloaded function set, because the
  2389. // expression is ill-formed if it actually works out to be a
  2390. // non-static member function:
  2391. //
  2392. // C++ [expr.ref]p4:
  2393. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2394. // [t]he expression can be used only as the left-hand operand of a
  2395. // member function call.
  2396. //
  2397. // There are other safeguards against such uses, but it's important
  2398. // to get this right here so that we don't end up making a
  2399. // spuriously dependent expression if we're inside a dependent
  2400. // instance method.
  2401. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2402. bool MightBeImplicitMember;
  2403. if (!IsAddressOfOperand)
  2404. MightBeImplicitMember = true;
  2405. else if (!SS.isEmpty())
  2406. MightBeImplicitMember = false;
  2407. else if (R.isOverloadedResult())
  2408. MightBeImplicitMember = false;
  2409. else if (R.isUnresolvableResult())
  2410. MightBeImplicitMember = true;
  2411. else
  2412. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2413. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2414. isa<MSPropertyDecl>(R.getFoundDecl());
  2415. if (MightBeImplicitMember)
  2416. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2417. R, TemplateArgs, S);
  2418. }
  2419. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2420. // In C++1y, if this is a variable template id, then check it
  2421. // in BuildTemplateIdExpr().
  2422. // The single lookup result must be a variable template declaration.
  2423. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  2424. Id.TemplateId->Kind == TNK_Var_template) {
  2425. assert(R.getAsSingle<VarTemplateDecl>() &&
  2426. "There should only be one declaration found.");
  2427. }
  2428. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2429. }
  2430. return BuildDeclarationNameExpr(SS, R, ADL);
  2431. }
  2432. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2433. /// declaration name, generally during template instantiation.
  2434. /// There's a large number of things which don't need to be done along
  2435. /// this path.
  2436. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2437. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2438. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2439. if (NameInfo.getName().isDependentName())
  2440. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2441. NameInfo, /*TemplateArgs=*/nullptr);
  2442. DeclContext *DC = computeDeclContext(SS, false);
  2443. if (!DC)
  2444. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2445. NameInfo, /*TemplateArgs=*/nullptr);
  2446. if (RequireCompleteDeclContext(SS, DC))
  2447. return ExprError();
  2448. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2449. LookupQualifiedName(R, DC);
  2450. if (R.isAmbiguous())
  2451. return ExprError();
  2452. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2453. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2454. NameInfo, /*TemplateArgs=*/nullptr);
  2455. if (R.empty()) {
  2456. // Don't diagnose problems with invalid record decl, the secondary no_member
  2457. // diagnostic during template instantiation is likely bogus, e.g. if a class
  2458. // is invalid because it's derived from an invalid base class, then missing
  2459. // members were likely supposed to be inherited.
  2460. if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
  2461. if (CD->isInvalidDecl())
  2462. return ExprError();
  2463. Diag(NameInfo.getLoc(), diag::err_no_member)
  2464. << NameInfo.getName() << DC << SS.getRange();
  2465. return ExprError();
  2466. }
  2467. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2468. // Diagnose a missing typename if this resolved unambiguously to a type in
  2469. // a dependent context. If we can recover with a type, downgrade this to
  2470. // a warning in Microsoft compatibility mode.
  2471. unsigned DiagID = diag::err_typename_missing;
  2472. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2473. DiagID = diag::ext_typename_missing;
  2474. SourceLocation Loc = SS.getBeginLoc();
  2475. auto D = Diag(Loc, DiagID);
  2476. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2477. << SourceRange(Loc, NameInfo.getEndLoc());
  2478. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2479. // context.
  2480. if (!RecoveryTSI)
  2481. return ExprError();
  2482. // Only issue the fixit if we're prepared to recover.
  2483. D << FixItHint::CreateInsertion(Loc, "typename ");
  2484. // Recover by pretending this was an elaborated type.
  2485. QualType Ty = Context.getTypeDeclType(TD);
  2486. TypeLocBuilder TLB;
  2487. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2488. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2489. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2490. QTL.setElaboratedKeywordLoc(SourceLocation());
  2491. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2492. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2493. return ExprEmpty();
  2494. }
  2495. // Defend against this resolving to an implicit member access. We usually
  2496. // won't get here if this might be a legitimate a class member (we end up in
  2497. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2498. // a pointer-to-member or in an unevaluated context in C++11.
  2499. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2500. return BuildPossibleImplicitMemberExpr(SS,
  2501. /*TemplateKWLoc=*/SourceLocation(),
  2502. R, /*TemplateArgs=*/nullptr, S);
  2503. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2504. }
  2505. /// The parser has read a name in, and Sema has detected that we're currently
  2506. /// inside an ObjC method. Perform some additional checks and determine if we
  2507. /// should form a reference to an ivar.
  2508. ///
  2509. /// Ideally, most of this would be done by lookup, but there's
  2510. /// actually quite a lot of extra work involved.
  2511. DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
  2512. IdentifierInfo *II) {
  2513. SourceLocation Loc = Lookup.getNameLoc();
  2514. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2515. // Check for error condition which is already reported.
  2516. if (!CurMethod)
  2517. return DeclResult(true);
  2518. // There are two cases to handle here. 1) scoped lookup could have failed,
  2519. // in which case we should look for an ivar. 2) scoped lookup could have
  2520. // found a decl, but that decl is outside the current instance method (i.e.
  2521. // a global variable). In these two cases, we do a lookup for an ivar with
  2522. // this name, if the lookup sucedes, we replace it our current decl.
  2523. // If we're in a class method, we don't normally want to look for
  2524. // ivars. But if we don't find anything else, and there's an
  2525. // ivar, that's an error.
  2526. bool IsClassMethod = CurMethod->isClassMethod();
  2527. bool LookForIvars;
  2528. if (Lookup.empty())
  2529. LookForIvars = true;
  2530. else if (IsClassMethod)
  2531. LookForIvars = false;
  2532. else
  2533. LookForIvars = (Lookup.isSingleResult() &&
  2534. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2535. ObjCInterfaceDecl *IFace = nullptr;
  2536. if (LookForIvars) {
  2537. IFace = CurMethod->getClassInterface();
  2538. ObjCInterfaceDecl *ClassDeclared;
  2539. ObjCIvarDecl *IV = nullptr;
  2540. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2541. // Diagnose using an ivar in a class method.
  2542. if (IsClassMethod) {
  2543. Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
  2544. return DeclResult(true);
  2545. }
  2546. // Diagnose the use of an ivar outside of the declaring class.
  2547. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2548. !declaresSameEntity(ClassDeclared, IFace) &&
  2549. !getLangOpts().DebuggerSupport)
  2550. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2551. // Success.
  2552. return IV;
  2553. }
  2554. } else if (CurMethod->isInstanceMethod()) {
  2555. // We should warn if a local variable hides an ivar.
  2556. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2557. ObjCInterfaceDecl *ClassDeclared;
  2558. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2559. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2560. declaresSameEntity(IFace, ClassDeclared))
  2561. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2562. }
  2563. }
  2564. } else if (Lookup.isSingleResult() &&
  2565. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2566. // If accessing a stand-alone ivar in a class method, this is an error.
  2567. if (const ObjCIvarDecl *IV =
  2568. dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
  2569. Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
  2570. return DeclResult(true);
  2571. }
  2572. }
  2573. // Didn't encounter an error, didn't find an ivar.
  2574. return DeclResult(false);
  2575. }
  2576. ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
  2577. ObjCIvarDecl *IV) {
  2578. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2579. assert(CurMethod && CurMethod->isInstanceMethod() &&
  2580. "should not reference ivar from this context");
  2581. ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
  2582. assert(IFace && "should not reference ivar from this context");
  2583. // If we're referencing an invalid decl, just return this as a silent
  2584. // error node. The error diagnostic was already emitted on the decl.
  2585. if (IV->isInvalidDecl())
  2586. return ExprError();
  2587. // Check if referencing a field with __attribute__((deprecated)).
  2588. if (DiagnoseUseOfDecl(IV, Loc))
  2589. return ExprError();
  2590. // FIXME: This should use a new expr for a direct reference, don't
  2591. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2592. IdentifierInfo &II = Context.Idents.get("self");
  2593. UnqualifiedId SelfName;
  2594. SelfName.setImplicitSelfParam(&II);
  2595. CXXScopeSpec SelfScopeSpec;
  2596. SourceLocation TemplateKWLoc;
  2597. ExprResult SelfExpr =
  2598. ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
  2599. /*HasTrailingLParen=*/false,
  2600. /*IsAddressOfOperand=*/false);
  2601. if (SelfExpr.isInvalid())
  2602. return ExprError();
  2603. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2604. if (SelfExpr.isInvalid())
  2605. return ExprError();
  2606. MarkAnyDeclReferenced(Loc, IV, true);
  2607. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2608. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2609. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2610. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2611. ObjCIvarRefExpr *Result = new (Context)
  2612. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2613. IV->getLocation(), SelfExpr.get(), true, true);
  2614. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2615. if (!isUnevaluatedContext() &&
  2616. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2617. getCurFunction()->recordUseOfWeak(Result);
  2618. }
  2619. if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
  2620. if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
  2621. ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
  2622. return Result;
  2623. }
  2624. /// The parser has read a name in, and Sema has detected that we're currently
  2625. /// inside an ObjC method. Perform some additional checks and determine if we
  2626. /// should form a reference to an ivar. If so, build an expression referencing
  2627. /// that ivar.
  2628. ExprResult
  2629. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2630. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2631. // FIXME: Integrate this lookup step into LookupParsedName.
  2632. DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
  2633. if (Ivar.isInvalid())
  2634. return ExprError();
  2635. if (Ivar.isUsable())
  2636. return BuildIvarRefExpr(S, Lookup.getNameLoc(),
  2637. cast<ObjCIvarDecl>(Ivar.get()));
  2638. if (Lookup.empty() && II && AllowBuiltinCreation)
  2639. LookupBuiltin(Lookup);
  2640. // Sentinel value saying that we didn't do anything special.
  2641. return ExprResult(false);
  2642. }
  2643. /// Cast a base object to a member's actual type.
  2644. ///
  2645. /// There are two relevant checks:
  2646. ///
  2647. /// C++ [class.access.base]p7:
  2648. ///
  2649. /// If a class member access operator [...] is used to access a non-static
  2650. /// data member or non-static member function, the reference is ill-formed if
  2651. /// the left operand [...] cannot be implicitly converted to a pointer to the
  2652. /// naming class of the right operand.
  2653. ///
  2654. /// C++ [expr.ref]p7:
  2655. ///
  2656. /// If E2 is a non-static data member or a non-static member function, the
  2657. /// program is ill-formed if the class of which E2 is directly a member is an
  2658. /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
  2659. ///
  2660. /// Note that the latter check does not consider access; the access of the
  2661. /// "real" base class is checked as appropriate when checking the access of the
  2662. /// member name.
  2663. ExprResult
  2664. Sema::PerformObjectMemberConversion(Expr *From,
  2665. NestedNameSpecifier *Qualifier,
  2666. NamedDecl *FoundDecl,
  2667. NamedDecl *Member) {
  2668. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2669. if (!RD)
  2670. return From;
  2671. QualType DestRecordType;
  2672. QualType DestType;
  2673. QualType FromRecordType;
  2674. QualType FromType = From->getType();
  2675. bool PointerConversions = false;
  2676. if (isa<FieldDecl>(Member)) {
  2677. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2678. auto FromPtrType = FromType->getAs<PointerType>();
  2679. DestRecordType = Context.getAddrSpaceQualType(
  2680. DestRecordType, FromPtrType
  2681. ? FromType->getPointeeType().getAddressSpace()
  2682. : FromType.getAddressSpace());
  2683. if (FromPtrType) {
  2684. DestType = Context.getPointerType(DestRecordType);
  2685. FromRecordType = FromPtrType->getPointeeType();
  2686. PointerConversions = true;
  2687. } else {
  2688. DestType = DestRecordType;
  2689. FromRecordType = FromType;
  2690. }
  2691. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2692. if (Method->isStatic())
  2693. return From;
  2694. DestType = Method->getThisType();
  2695. DestRecordType = DestType->getPointeeType();
  2696. if (FromType->getAs<PointerType>()) {
  2697. FromRecordType = FromType->getPointeeType();
  2698. PointerConversions = true;
  2699. } else {
  2700. FromRecordType = FromType;
  2701. DestType = DestRecordType;
  2702. }
  2703. LangAS FromAS = FromRecordType.getAddressSpace();
  2704. LangAS DestAS = DestRecordType.getAddressSpace();
  2705. if (FromAS != DestAS) {
  2706. QualType FromRecordTypeWithoutAS =
  2707. Context.removeAddrSpaceQualType(FromRecordType);
  2708. QualType FromTypeWithDestAS =
  2709. Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
  2710. if (PointerConversions)
  2711. FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
  2712. From = ImpCastExprToType(From, FromTypeWithDestAS,
  2713. CK_AddressSpaceConversion, From->getValueKind())
  2714. .get();
  2715. }
  2716. } else {
  2717. // No conversion necessary.
  2718. return From;
  2719. }
  2720. if (DestType->isDependentType() || FromType->isDependentType())
  2721. return From;
  2722. // If the unqualified types are the same, no conversion is necessary.
  2723. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2724. return From;
  2725. SourceRange FromRange = From->getSourceRange();
  2726. SourceLocation FromLoc = FromRange.getBegin();
  2727. ExprValueKind VK = From->getValueKind();
  2728. // C++ [class.member.lookup]p8:
  2729. // [...] Ambiguities can often be resolved by qualifying a name with its
  2730. // class name.
  2731. //
  2732. // If the member was a qualified name and the qualified referred to a
  2733. // specific base subobject type, we'll cast to that intermediate type
  2734. // first and then to the object in which the member is declared. That allows
  2735. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2736. //
  2737. // class Base { public: int x; };
  2738. // class Derived1 : public Base { };
  2739. // class Derived2 : public Base { };
  2740. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2741. //
  2742. // void VeryDerived::f() {
  2743. // x = 17; // error: ambiguous base subobjects
  2744. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2745. // }
  2746. if (Qualifier && Qualifier->getAsType()) {
  2747. QualType QType = QualType(Qualifier->getAsType(), 0);
  2748. assert(QType->isRecordType() && "lookup done with non-record type");
  2749. QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
  2750. // In C++98, the qualifier type doesn't actually have to be a base
  2751. // type of the object type, in which case we just ignore it.
  2752. // Otherwise build the appropriate casts.
  2753. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2754. CXXCastPath BasePath;
  2755. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2756. FromLoc, FromRange, &BasePath))
  2757. return ExprError();
  2758. if (PointerConversions)
  2759. QType = Context.getPointerType(QType);
  2760. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2761. VK, &BasePath).get();
  2762. FromType = QType;
  2763. FromRecordType = QRecordType;
  2764. // If the qualifier type was the same as the destination type,
  2765. // we're done.
  2766. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2767. return From;
  2768. }
  2769. }
  2770. CXXCastPath BasePath;
  2771. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2772. FromLoc, FromRange, &BasePath,
  2773. /*IgnoreAccess=*/true))
  2774. return ExprError();
  2775. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2776. VK, &BasePath);
  2777. }
  2778. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2779. const LookupResult &R,
  2780. bool HasTrailingLParen) {
  2781. // Only when used directly as the postfix-expression of a call.
  2782. if (!HasTrailingLParen)
  2783. return false;
  2784. // Never if a scope specifier was provided.
  2785. if (SS.isSet())
  2786. return false;
  2787. // Only in C++ or ObjC++.
  2788. if (!getLangOpts().CPlusPlus)
  2789. return false;
  2790. // Turn off ADL when we find certain kinds of declarations during
  2791. // normal lookup:
  2792. for (NamedDecl *D : R) {
  2793. // C++0x [basic.lookup.argdep]p3:
  2794. // -- a declaration of a class member
  2795. // Since using decls preserve this property, we check this on the
  2796. // original decl.
  2797. if (D->isCXXClassMember())
  2798. return false;
  2799. // C++0x [basic.lookup.argdep]p3:
  2800. // -- a block-scope function declaration that is not a
  2801. // using-declaration
  2802. // NOTE: we also trigger this for function templates (in fact, we
  2803. // don't check the decl type at all, since all other decl types
  2804. // turn off ADL anyway).
  2805. if (isa<UsingShadowDecl>(D))
  2806. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2807. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2808. return false;
  2809. // C++0x [basic.lookup.argdep]p3:
  2810. // -- a declaration that is neither a function or a function
  2811. // template
  2812. // And also for builtin functions.
  2813. if (isa<FunctionDecl>(D)) {
  2814. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2815. // But also builtin functions.
  2816. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2817. return false;
  2818. } else if (!isa<FunctionTemplateDecl>(D))
  2819. return false;
  2820. }
  2821. return true;
  2822. }
  2823. /// Diagnoses obvious problems with the use of the given declaration
  2824. /// as an expression. This is only actually called for lookups that
  2825. /// were not overloaded, and it doesn't promise that the declaration
  2826. /// will in fact be used.
  2827. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
  2828. bool AcceptInvalid) {
  2829. if (D->isInvalidDecl() && !AcceptInvalid)
  2830. return true;
  2831. if (isa<TypedefNameDecl>(D)) {
  2832. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2833. return true;
  2834. }
  2835. if (isa<ObjCInterfaceDecl>(D)) {
  2836. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2837. return true;
  2838. }
  2839. if (isa<NamespaceDecl>(D)) {
  2840. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2841. return true;
  2842. }
  2843. return false;
  2844. }
  2845. // Certain multiversion types should be treated as overloaded even when there is
  2846. // only one result.
  2847. static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
  2848. assert(R.isSingleResult() && "Expected only a single result");
  2849. const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  2850. return FD &&
  2851. (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
  2852. }
  2853. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2854. LookupResult &R, bool NeedsADL,
  2855. bool AcceptInvalidDecl) {
  2856. // If this is a single, fully-resolved result and we don't need ADL,
  2857. // just build an ordinary singleton decl ref.
  2858. if (!NeedsADL && R.isSingleResult() &&
  2859. !R.getAsSingle<FunctionTemplateDecl>() &&
  2860. !ShouldLookupResultBeMultiVersionOverload(R))
  2861. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2862. R.getRepresentativeDecl(), nullptr,
  2863. AcceptInvalidDecl);
  2864. // We only need to check the declaration if there's exactly one
  2865. // result, because in the overloaded case the results can only be
  2866. // functions and function templates.
  2867. if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
  2868. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
  2869. AcceptInvalidDecl))
  2870. return ExprError();
  2871. // Otherwise, just build an unresolved lookup expression. Suppress
  2872. // any lookup-related diagnostics; we'll hash these out later, when
  2873. // we've picked a target.
  2874. R.suppressDiagnostics();
  2875. UnresolvedLookupExpr *ULE
  2876. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2877. SS.getWithLocInContext(Context),
  2878. R.getLookupNameInfo(),
  2879. NeedsADL, R.isOverloadedResult(),
  2880. R.begin(), R.end());
  2881. return ULE;
  2882. }
  2883. static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
  2884. SourceLocation loc,
  2885. ValueDecl *var);
  2886. /// Complete semantic analysis for a reference to the given declaration.
  2887. ExprResult Sema::BuildDeclarationNameExpr(
  2888. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2889. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2890. bool AcceptInvalidDecl) {
  2891. assert(D && "Cannot refer to a NULL declaration");
  2892. assert(!isa<FunctionTemplateDecl>(D) &&
  2893. "Cannot refer unambiguously to a function template");
  2894. SourceLocation Loc = NameInfo.getLoc();
  2895. if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
  2896. // Recovery from invalid cases (e.g. D is an invalid Decl).
  2897. // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
  2898. // diagnostics, as invalid decls use int as a fallback type.
  2899. return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
  2900. }
  2901. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2902. // Specifically diagnose references to class templates that are missing
  2903. // a template argument list.
  2904. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2905. return ExprError();
  2906. }
  2907. // Make sure that we're referring to a value.
  2908. if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
  2909. Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
  2910. Diag(D->getLocation(), diag::note_declared_at);
  2911. return ExprError();
  2912. }
  2913. // Check whether this declaration can be used. Note that we suppress
  2914. // this check when we're going to perform argument-dependent lookup
  2915. // on this function name, because this might not be the function
  2916. // that overload resolution actually selects.
  2917. if (DiagnoseUseOfDecl(D, Loc))
  2918. return ExprError();
  2919. auto *VD = cast<ValueDecl>(D);
  2920. // Only create DeclRefExpr's for valid Decl's.
  2921. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2922. return ExprError();
  2923. // Handle members of anonymous structs and unions. If we got here,
  2924. // and the reference is to a class member indirect field, then this
  2925. // must be the subject of a pointer-to-member expression.
  2926. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2927. if (!indirectField->isCXXClassMember())
  2928. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2929. indirectField);
  2930. QualType type = VD->getType();
  2931. if (type.isNull())
  2932. return ExprError();
  2933. ExprValueKind valueKind = VK_PRValue;
  2934. // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
  2935. // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
  2936. // is expanded by some outer '...' in the context of the use.
  2937. type = type.getNonPackExpansionType();
  2938. switch (D->getKind()) {
  2939. // Ignore all the non-ValueDecl kinds.
  2940. #define ABSTRACT_DECL(kind)
  2941. #define VALUE(type, base)
  2942. #define DECL(type, base) case Decl::type:
  2943. #include "clang/AST/DeclNodes.inc"
  2944. llvm_unreachable("invalid value decl kind");
  2945. // These shouldn't make it here.
  2946. case Decl::ObjCAtDefsField:
  2947. llvm_unreachable("forming non-member reference to ivar?");
  2948. // Enum constants are always r-values and never references.
  2949. // Unresolved using declarations are dependent.
  2950. case Decl::EnumConstant:
  2951. case Decl::UnresolvedUsingValue:
  2952. case Decl::OMPDeclareReduction:
  2953. case Decl::OMPDeclareMapper:
  2954. valueKind = VK_PRValue;
  2955. break;
  2956. // Fields and indirect fields that got here must be for
  2957. // pointer-to-member expressions; we just call them l-values for
  2958. // internal consistency, because this subexpression doesn't really
  2959. // exist in the high-level semantics.
  2960. case Decl::Field:
  2961. case Decl::IndirectField:
  2962. case Decl::ObjCIvar:
  2963. assert(getLangOpts().CPlusPlus && "building reference to field in C?");
  2964. // These can't have reference type in well-formed programs, but
  2965. // for internal consistency we do this anyway.
  2966. type = type.getNonReferenceType();
  2967. valueKind = VK_LValue;
  2968. break;
  2969. // Non-type template parameters are either l-values or r-values
  2970. // depending on the type.
  2971. case Decl::NonTypeTemplateParm: {
  2972. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2973. type = reftype->getPointeeType();
  2974. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2975. break;
  2976. }
  2977. // [expr.prim.id.unqual]p2:
  2978. // If the entity is a template parameter object for a template
  2979. // parameter of type T, the type of the expression is const T.
  2980. // [...] The expression is an lvalue if the entity is a [...] template
  2981. // parameter object.
  2982. if (type->isRecordType()) {
  2983. type = type.getUnqualifiedType().withConst();
  2984. valueKind = VK_LValue;
  2985. break;
  2986. }
  2987. // For non-references, we need to strip qualifiers just in case
  2988. // the template parameter was declared as 'const int' or whatever.
  2989. valueKind = VK_PRValue;
  2990. type = type.getUnqualifiedType();
  2991. break;
  2992. }
  2993. case Decl::Var:
  2994. case Decl::VarTemplateSpecialization:
  2995. case Decl::VarTemplatePartialSpecialization:
  2996. case Decl::Decomposition:
  2997. case Decl::OMPCapturedExpr:
  2998. // In C, "extern void blah;" is valid and is an r-value.
  2999. if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
  3000. type->isVoidType()) {
  3001. valueKind = VK_PRValue;
  3002. break;
  3003. }
  3004. [[fallthrough]];
  3005. case Decl::ImplicitParam:
  3006. case Decl::ParmVar: {
  3007. // These are always l-values.
  3008. valueKind = VK_LValue;
  3009. type = type.getNonReferenceType();
  3010. // FIXME: Does the addition of const really only apply in
  3011. // potentially-evaluated contexts? Since the variable isn't actually
  3012. // captured in an unevaluated context, it seems that the answer is no.
  3013. if (!isUnevaluatedContext()) {
  3014. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  3015. if (!CapturedType.isNull())
  3016. type = CapturedType;
  3017. }
  3018. break;
  3019. }
  3020. case Decl::Binding:
  3021. // These are always lvalues.
  3022. valueKind = VK_LValue;
  3023. type = type.getNonReferenceType();
  3024. break;
  3025. case Decl::Function: {
  3026. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  3027. if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
  3028. type = Context.BuiltinFnTy;
  3029. valueKind = VK_PRValue;
  3030. break;
  3031. }
  3032. }
  3033. const FunctionType *fty = type->castAs<FunctionType>();
  3034. // If we're referring to a function with an __unknown_anytype
  3035. // result type, make the entire expression __unknown_anytype.
  3036. if (fty->getReturnType() == Context.UnknownAnyTy) {
  3037. type = Context.UnknownAnyTy;
  3038. valueKind = VK_PRValue;
  3039. break;
  3040. }
  3041. // Functions are l-values in C++.
  3042. if (getLangOpts().CPlusPlus) {
  3043. valueKind = VK_LValue;
  3044. break;
  3045. }
  3046. // C99 DR 316 says that, if a function type comes from a
  3047. // function definition (without a prototype), that type is only
  3048. // used for checking compatibility. Therefore, when referencing
  3049. // the function, we pretend that we don't have the full function
  3050. // type.
  3051. if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
  3052. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  3053. fty->getExtInfo());
  3054. // Functions are r-values in C.
  3055. valueKind = VK_PRValue;
  3056. break;
  3057. }
  3058. case Decl::CXXDeductionGuide:
  3059. llvm_unreachable("building reference to deduction guide");
  3060. case Decl::MSProperty:
  3061. case Decl::MSGuid:
  3062. case Decl::TemplateParamObject:
  3063. // FIXME: Should MSGuidDecl and template parameter objects be subject to
  3064. // capture in OpenMP, or duplicated between host and device?
  3065. valueKind = VK_LValue;
  3066. break;
  3067. case Decl::UnnamedGlobalConstant:
  3068. valueKind = VK_LValue;
  3069. break;
  3070. case Decl::CXXMethod:
  3071. // If we're referring to a method with an __unknown_anytype
  3072. // result type, make the entire expression __unknown_anytype.
  3073. // This should only be possible with a type written directly.
  3074. if (const FunctionProtoType *proto =
  3075. dyn_cast<FunctionProtoType>(VD->getType()))
  3076. if (proto->getReturnType() == Context.UnknownAnyTy) {
  3077. type = Context.UnknownAnyTy;
  3078. valueKind = VK_PRValue;
  3079. break;
  3080. }
  3081. // C++ methods are l-values if static, r-values if non-static.
  3082. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  3083. valueKind = VK_LValue;
  3084. break;
  3085. }
  3086. [[fallthrough]];
  3087. case Decl::CXXConversion:
  3088. case Decl::CXXDestructor:
  3089. case Decl::CXXConstructor:
  3090. valueKind = VK_PRValue;
  3091. break;
  3092. }
  3093. auto *E =
  3094. BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  3095. /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
  3096. // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
  3097. // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
  3098. // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
  3099. // diagnostics).
  3100. if (VD->isInvalidDecl() && E)
  3101. return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
  3102. return E;
  3103. }
  3104. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  3105. SmallString<32> &Target) {
  3106. Target.resize(CharByteWidth * (Source.size() + 1));
  3107. char *ResultPtr = &Target[0];
  3108. const llvm::UTF8 *ErrorPtr;
  3109. bool success =
  3110. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  3111. (void)success;
  3112. assert(success);
  3113. Target.resize(ResultPtr - &Target[0]);
  3114. }
  3115. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  3116. PredefinedExpr::IdentKind IK) {
  3117. // Pick the current block, lambda, captured statement or function.
  3118. Decl *currentDecl = nullptr;
  3119. if (const BlockScopeInfo *BSI = getCurBlock())
  3120. currentDecl = BSI->TheDecl;
  3121. else if (const LambdaScopeInfo *LSI = getCurLambda())
  3122. currentDecl = LSI->CallOperator;
  3123. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  3124. currentDecl = CSI->TheCapturedDecl;
  3125. else
  3126. currentDecl = getCurFunctionOrMethodDecl();
  3127. if (!currentDecl) {
  3128. Diag(Loc, diag::ext_predef_outside_function);
  3129. currentDecl = Context.getTranslationUnitDecl();
  3130. }
  3131. QualType ResTy;
  3132. StringLiteral *SL = nullptr;
  3133. if (cast<DeclContext>(currentDecl)->isDependentContext())
  3134. ResTy = Context.DependentTy;
  3135. else {
  3136. // Pre-defined identifiers are of type char[x], where x is the length of
  3137. // the string.
  3138. auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
  3139. unsigned Length = Str.length();
  3140. llvm::APInt LengthI(32, Length + 1);
  3141. if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
  3142. ResTy =
  3143. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  3144. SmallString<32> RawChars;
  3145. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  3146. Str, RawChars);
  3147. ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
  3148. ArrayType::Normal,
  3149. /*IndexTypeQuals*/ 0);
  3150. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  3151. /*Pascal*/ false, ResTy, Loc);
  3152. } else {
  3153. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  3154. ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
  3155. ArrayType::Normal,
  3156. /*IndexTypeQuals*/ 0);
  3157. SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary,
  3158. /*Pascal*/ false, ResTy, Loc);
  3159. }
  3160. }
  3161. return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
  3162. }
  3163. ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
  3164. SourceLocation LParen,
  3165. SourceLocation RParen,
  3166. TypeSourceInfo *TSI) {
  3167. return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
  3168. }
  3169. ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
  3170. SourceLocation LParen,
  3171. SourceLocation RParen,
  3172. ParsedType ParsedTy) {
  3173. TypeSourceInfo *TSI = nullptr;
  3174. QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
  3175. if (Ty.isNull())
  3176. return ExprError();
  3177. if (!TSI)
  3178. TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
  3179. return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
  3180. }
  3181. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  3182. PredefinedExpr::IdentKind IK;
  3183. switch (Kind) {
  3184. default: llvm_unreachable("Unknown simple primary expr!");
  3185. case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  3186. case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
  3187. case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
  3188. case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
  3189. case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
  3190. case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
  3191. case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
  3192. }
  3193. return BuildPredefinedExpr(Loc, IK);
  3194. }
  3195. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  3196. SmallString<16> CharBuffer;
  3197. bool Invalid = false;
  3198. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  3199. if (Invalid)
  3200. return ExprError();
  3201. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  3202. PP, Tok.getKind());
  3203. if (Literal.hadError())
  3204. return ExprError();
  3205. QualType Ty;
  3206. if (Literal.isWide())
  3207. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  3208. else if (Literal.isUTF8() && getLangOpts().C2x)
  3209. Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
  3210. else if (Literal.isUTF8() && getLangOpts().Char8)
  3211. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  3212. else if (Literal.isUTF16())
  3213. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  3214. else if (Literal.isUTF32())
  3215. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  3216. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  3217. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  3218. else
  3219. Ty = Context.CharTy; // 'x' -> char in C++;
  3220. // u8'x' -> char in C11-C17 and in C++ without char8_t.
  3221. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  3222. if (Literal.isWide())
  3223. Kind = CharacterLiteral::Wide;
  3224. else if (Literal.isUTF16())
  3225. Kind = CharacterLiteral::UTF16;
  3226. else if (Literal.isUTF32())
  3227. Kind = CharacterLiteral::UTF32;
  3228. else if (Literal.isUTF8())
  3229. Kind = CharacterLiteral::UTF8;
  3230. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  3231. Tok.getLocation());
  3232. if (Literal.getUDSuffix().empty())
  3233. return Lit;
  3234. // We're building a user-defined literal.
  3235. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  3236. SourceLocation UDSuffixLoc =
  3237. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  3238. // Make sure we're allowed user-defined literals here.
  3239. if (!UDLScope)
  3240. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  3241. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  3242. // operator "" X (ch)
  3243. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  3244. Lit, Tok.getLocation());
  3245. }
  3246. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  3247. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3248. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  3249. Context.IntTy, Loc);
  3250. }
  3251. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  3252. QualType Ty, SourceLocation Loc) {
  3253. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  3254. using llvm::APFloat;
  3255. APFloat Val(Format);
  3256. APFloat::opStatus result = Literal.GetFloatValue(Val);
  3257. // Overflow is always an error, but underflow is only an error if
  3258. // we underflowed to zero (APFloat reports denormals as underflow).
  3259. if ((result & APFloat::opOverflow) ||
  3260. ((result & APFloat::opUnderflow) && Val.isZero())) {
  3261. unsigned diagnostic;
  3262. SmallString<20> buffer;
  3263. if (result & APFloat::opOverflow) {
  3264. diagnostic = diag::warn_float_overflow;
  3265. APFloat::getLargest(Format).toString(buffer);
  3266. } else {
  3267. diagnostic = diag::warn_float_underflow;
  3268. APFloat::getSmallest(Format).toString(buffer);
  3269. }
  3270. S.Diag(Loc, diagnostic)
  3271. << Ty
  3272. << StringRef(buffer.data(), buffer.size());
  3273. }
  3274. bool isExact = (result == APFloat::opOK);
  3275. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  3276. }
  3277. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  3278. assert(E && "Invalid expression");
  3279. if (E->isValueDependent())
  3280. return false;
  3281. QualType QT = E->getType();
  3282. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  3283. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  3284. return true;
  3285. }
  3286. llvm::APSInt ValueAPS;
  3287. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  3288. if (R.isInvalid())
  3289. return true;
  3290. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  3291. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  3292. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  3293. << toString(ValueAPS, 10) << ValueIsPositive;
  3294. return true;
  3295. }
  3296. return false;
  3297. }
  3298. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  3299. // Fast path for a single digit (which is quite common). A single digit
  3300. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  3301. if (Tok.getLength() == 1) {
  3302. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  3303. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  3304. }
  3305. SmallString<128> SpellingBuffer;
  3306. // NumericLiteralParser wants to overread by one character. Add padding to
  3307. // the buffer in case the token is copied to the buffer. If getSpelling()
  3308. // returns a StringRef to the memory buffer, it should have a null char at
  3309. // the EOF, so it is also safe.
  3310. SpellingBuffer.resize(Tok.getLength() + 1);
  3311. // Get the spelling of the token, which eliminates trigraphs, etc.
  3312. bool Invalid = false;
  3313. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  3314. if (Invalid)
  3315. return ExprError();
  3316. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
  3317. PP.getSourceManager(), PP.getLangOpts(),
  3318. PP.getTargetInfo(), PP.getDiagnostics());
  3319. if (Literal.hadError)
  3320. return ExprError();
  3321. if (Literal.hasUDSuffix()) {
  3322. // We're building a user-defined literal.
  3323. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  3324. SourceLocation UDSuffixLoc =
  3325. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  3326. // Make sure we're allowed user-defined literals here.
  3327. if (!UDLScope)
  3328. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  3329. QualType CookedTy;
  3330. if (Literal.isFloatingLiteral()) {
  3331. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  3332. // long double, the literal is treated as a call of the form
  3333. // operator "" X (f L)
  3334. CookedTy = Context.LongDoubleTy;
  3335. } else {
  3336. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  3337. // unsigned long long, the literal is treated as a call of the form
  3338. // operator "" X (n ULL)
  3339. CookedTy = Context.UnsignedLongLongTy;
  3340. }
  3341. DeclarationName OpName =
  3342. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  3343. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  3344. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  3345. SourceLocation TokLoc = Tok.getLocation();
  3346. // Perform literal operator lookup to determine if we're building a raw
  3347. // literal or a cooked one.
  3348. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  3349. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  3350. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  3351. /*AllowStringTemplatePack*/ false,
  3352. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  3353. case LOLR_ErrorNoDiagnostic:
  3354. // Lookup failure for imaginary constants isn't fatal, there's still the
  3355. // GNU extension producing _Complex types.
  3356. break;
  3357. case LOLR_Error:
  3358. return ExprError();
  3359. case LOLR_Cooked: {
  3360. Expr *Lit;
  3361. if (Literal.isFloatingLiteral()) {
  3362. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  3363. } else {
  3364. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  3365. if (Literal.GetIntegerValue(ResultVal))
  3366. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3367. << /* Unsigned */ 1;
  3368. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  3369. Tok.getLocation());
  3370. }
  3371. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3372. }
  3373. case LOLR_Raw: {
  3374. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  3375. // literal is treated as a call of the form
  3376. // operator "" X ("n")
  3377. unsigned Length = Literal.getUDSuffixOffset();
  3378. QualType StrTy = Context.getConstantArrayType(
  3379. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  3380. llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
  3381. Expr *Lit =
  3382. StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
  3383. StringLiteral::Ordinary,
  3384. /*Pascal*/ false, StrTy, &TokLoc, 1);
  3385. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3386. }
  3387. case LOLR_Template: {
  3388. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  3389. // template), L is treated as a call fo the form
  3390. // operator "" X <'c1', 'c2', ... 'ck'>()
  3391. // where n is the source character sequence c1 c2 ... ck.
  3392. TemplateArgumentListInfo ExplicitArgs;
  3393. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  3394. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  3395. llvm::APSInt Value(CharBits, CharIsUnsigned);
  3396. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  3397. Value = TokSpelling[I];
  3398. TemplateArgument Arg(Context, Value, Context.CharTy);
  3399. TemplateArgumentLocInfo ArgInfo;
  3400. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  3401. }
  3402. return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
  3403. &ExplicitArgs);
  3404. }
  3405. case LOLR_StringTemplatePack:
  3406. llvm_unreachable("unexpected literal operator lookup result");
  3407. }
  3408. }
  3409. Expr *Res;
  3410. if (Literal.isFixedPointLiteral()) {
  3411. QualType Ty;
  3412. if (Literal.isAccum) {
  3413. if (Literal.isHalf) {
  3414. Ty = Context.ShortAccumTy;
  3415. } else if (Literal.isLong) {
  3416. Ty = Context.LongAccumTy;
  3417. } else {
  3418. Ty = Context.AccumTy;
  3419. }
  3420. } else if (Literal.isFract) {
  3421. if (Literal.isHalf) {
  3422. Ty = Context.ShortFractTy;
  3423. } else if (Literal.isLong) {
  3424. Ty = Context.LongFractTy;
  3425. } else {
  3426. Ty = Context.FractTy;
  3427. }
  3428. }
  3429. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  3430. bool isSigned = !Literal.isUnsigned;
  3431. unsigned scale = Context.getFixedPointScale(Ty);
  3432. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  3433. llvm::APInt Val(bit_width, 0, isSigned);
  3434. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  3435. bool ValIsZero = Val.isZero() && !Overflowed;
  3436. auto MaxVal = Context.getFixedPointMax(Ty).getValue();
  3437. if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
  3438. // Clause 6.4.4 - The value of a constant shall be in the range of
  3439. // representable values for its type, with exception for constants of a
  3440. // fract type with a value of exactly 1; such a constant shall denote
  3441. // the maximal value for the type.
  3442. --Val;
  3443. else if (Val.ugt(MaxVal) || Overflowed)
  3444. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  3445. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  3446. Tok.getLocation(), scale);
  3447. } else if (Literal.isFloatingLiteral()) {
  3448. QualType Ty;
  3449. if (Literal.isHalf){
  3450. if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
  3451. Ty = Context.HalfTy;
  3452. else {
  3453. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  3454. return ExprError();
  3455. }
  3456. } else if (Literal.isFloat)
  3457. Ty = Context.FloatTy;
  3458. else if (Literal.isLong)
  3459. Ty = Context.LongDoubleTy;
  3460. else if (Literal.isFloat16)
  3461. Ty = Context.Float16Ty;
  3462. else if (Literal.isFloat128)
  3463. Ty = Context.Float128Ty;
  3464. else
  3465. Ty = Context.DoubleTy;
  3466. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  3467. if (Ty == Context.DoubleTy) {
  3468. if (getLangOpts().SinglePrecisionConstants) {
  3469. if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
  3470. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3471. }
  3472. } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
  3473. "cl_khr_fp64", getLangOpts())) {
  3474. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  3475. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
  3476. << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
  3477. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3478. }
  3479. }
  3480. } else if (!Literal.isIntegerLiteral()) {
  3481. return ExprError();
  3482. } else {
  3483. QualType Ty;
  3484. // 'z/uz' literals are a C++2b feature.
  3485. if (Literal.isSizeT)
  3486. Diag(Tok.getLocation(), getLangOpts().CPlusPlus
  3487. ? getLangOpts().CPlusPlus2b
  3488. ? diag::warn_cxx20_compat_size_t_suffix
  3489. : diag::ext_cxx2b_size_t_suffix
  3490. : diag::err_cxx2b_size_t_suffix);
  3491. // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
  3492. // but we do not currently support the suffix in C++ mode because it's not
  3493. // entirely clear whether WG21 will prefer this suffix to return a library
  3494. // type such as std::bit_int instead of returning a _BitInt.
  3495. if (Literal.isBitInt && !getLangOpts().CPlusPlus)
  3496. PP.Diag(Tok.getLocation(), getLangOpts().C2x
  3497. ? diag::warn_c2x_compat_bitint_suffix
  3498. : diag::ext_c2x_bitint_suffix);
  3499. // Get the value in the widest-possible width. What is "widest" depends on
  3500. // whether the literal is a bit-precise integer or not. For a bit-precise
  3501. // integer type, try to scan the source to determine how many bits are
  3502. // needed to represent the value. This may seem a bit expensive, but trying
  3503. // to get the integer value from an overly-wide APInt is *extremely*
  3504. // expensive, so the naive approach of assuming
  3505. // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
  3506. unsigned BitsNeeded =
  3507. Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
  3508. Literal.getLiteralDigits(), Literal.getRadix())
  3509. : Context.getTargetInfo().getIntMaxTWidth();
  3510. llvm::APInt ResultVal(BitsNeeded, 0);
  3511. if (Literal.GetIntegerValue(ResultVal)) {
  3512. // If this value didn't fit into uintmax_t, error and force to ull.
  3513. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3514. << /* Unsigned */ 1;
  3515. Ty = Context.UnsignedLongLongTy;
  3516. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3517. "long long is not intmax_t?");
  3518. } else {
  3519. // If this value fits into a ULL, try to figure out what else it fits into
  3520. // according to the rules of C99 6.4.4.1p5.
  3521. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3522. // be an unsigned int.
  3523. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3524. // Check from smallest to largest, picking the smallest type we can.
  3525. unsigned Width = 0;
  3526. // Microsoft specific integer suffixes are explicitly sized.
  3527. if (Literal.MicrosoftInteger) {
  3528. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3529. Width = 8;
  3530. Ty = Context.CharTy;
  3531. } else {
  3532. Width = Literal.MicrosoftInteger;
  3533. Ty = Context.getIntTypeForBitwidth(Width,
  3534. /*Signed=*/!Literal.isUnsigned);
  3535. }
  3536. }
  3537. // Bit-precise integer literals are automagically-sized based on the
  3538. // width required by the literal.
  3539. if (Literal.isBitInt) {
  3540. // The signed version has one more bit for the sign value. There are no
  3541. // zero-width bit-precise integers, even if the literal value is 0.
  3542. Width = std::max(ResultVal.getActiveBits(), 1u) +
  3543. (Literal.isUnsigned ? 0u : 1u);
  3544. // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
  3545. // and reset the type to the largest supported width.
  3546. unsigned int MaxBitIntWidth =
  3547. Context.getTargetInfo().getMaxBitIntWidth();
  3548. if (Width > MaxBitIntWidth) {
  3549. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3550. << Literal.isUnsigned;
  3551. Width = MaxBitIntWidth;
  3552. }
  3553. // Reset the result value to the smaller APInt and select the correct
  3554. // type to be used. Note, we zext even for signed values because the
  3555. // literal itself is always an unsigned value (a preceeding - is a
  3556. // unary operator, not part of the literal).
  3557. ResultVal = ResultVal.zextOrTrunc(Width);
  3558. Ty = Context.getBitIntType(Literal.isUnsigned, Width);
  3559. }
  3560. // Check C++2b size_t literals.
  3561. if (Literal.isSizeT) {
  3562. assert(!Literal.MicrosoftInteger &&
  3563. "size_t literals can't be Microsoft literals");
  3564. unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
  3565. Context.getTargetInfo().getSizeType());
  3566. // Does it fit in size_t?
  3567. if (ResultVal.isIntN(SizeTSize)) {
  3568. // Does it fit in ssize_t?
  3569. if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
  3570. Ty = Context.getSignedSizeType();
  3571. else if (AllowUnsigned)
  3572. Ty = Context.getSizeType();
  3573. Width = SizeTSize;
  3574. }
  3575. }
  3576. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
  3577. !Literal.isSizeT) {
  3578. // Are int/unsigned possibilities?
  3579. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3580. // Does it fit in a unsigned int?
  3581. if (ResultVal.isIntN(IntSize)) {
  3582. // Does it fit in a signed int?
  3583. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3584. Ty = Context.IntTy;
  3585. else if (AllowUnsigned)
  3586. Ty = Context.UnsignedIntTy;
  3587. Width = IntSize;
  3588. }
  3589. }
  3590. // Are long/unsigned long possibilities?
  3591. if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
  3592. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3593. // Does it fit in a unsigned long?
  3594. if (ResultVal.isIntN(LongSize)) {
  3595. // Does it fit in a signed long?
  3596. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3597. Ty = Context.LongTy;
  3598. else if (AllowUnsigned)
  3599. Ty = Context.UnsignedLongTy;
  3600. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3601. // is compatible.
  3602. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3603. const unsigned LongLongSize =
  3604. Context.getTargetInfo().getLongLongWidth();
  3605. Diag(Tok.getLocation(),
  3606. getLangOpts().CPlusPlus
  3607. ? Literal.isLong
  3608. ? diag::warn_old_implicitly_unsigned_long_cxx
  3609. : /*C++98 UB*/ diag::
  3610. ext_old_implicitly_unsigned_long_cxx
  3611. : diag::warn_old_implicitly_unsigned_long)
  3612. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3613. : /*will be ill-formed*/ 1);
  3614. Ty = Context.UnsignedLongTy;
  3615. }
  3616. Width = LongSize;
  3617. }
  3618. }
  3619. // Check long long if needed.
  3620. if (Ty.isNull() && !Literal.isSizeT) {
  3621. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3622. // Does it fit in a unsigned long long?
  3623. if (ResultVal.isIntN(LongLongSize)) {
  3624. // Does it fit in a signed long long?
  3625. // To be compatible with MSVC, hex integer literals ending with the
  3626. // LL or i64 suffix are always signed in Microsoft mode.
  3627. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3628. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3629. Ty = Context.LongLongTy;
  3630. else if (AllowUnsigned)
  3631. Ty = Context.UnsignedLongLongTy;
  3632. Width = LongLongSize;
  3633. // 'long long' is a C99 or C++11 feature, whether the literal
  3634. // explicitly specified 'long long' or we needed the extra width.
  3635. if (getLangOpts().CPlusPlus)
  3636. Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
  3637. ? diag::warn_cxx98_compat_longlong
  3638. : diag::ext_cxx11_longlong);
  3639. else if (!getLangOpts().C99)
  3640. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3641. }
  3642. }
  3643. // If we still couldn't decide a type, we either have 'size_t' literal
  3644. // that is out of range, or a decimal literal that does not fit in a
  3645. // signed long long and has no U suffix.
  3646. if (Ty.isNull()) {
  3647. if (Literal.isSizeT)
  3648. Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
  3649. << Literal.isUnsigned;
  3650. else
  3651. Diag(Tok.getLocation(),
  3652. diag::ext_integer_literal_too_large_for_signed);
  3653. Ty = Context.UnsignedLongLongTy;
  3654. Width = Context.getTargetInfo().getLongLongWidth();
  3655. }
  3656. if (ResultVal.getBitWidth() != Width)
  3657. ResultVal = ResultVal.trunc(Width);
  3658. }
  3659. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3660. }
  3661. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3662. if (Literal.isImaginary) {
  3663. Res = new (Context) ImaginaryLiteral(Res,
  3664. Context.getComplexType(Res->getType()));
  3665. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3666. }
  3667. return Res;
  3668. }
  3669. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3670. assert(E && "ActOnParenExpr() missing expr");
  3671. QualType ExprTy = E->getType();
  3672. if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
  3673. !E->isLValue() && ExprTy->hasFloatingRepresentation())
  3674. return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
  3675. return new (Context) ParenExpr(L, R, E);
  3676. }
  3677. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3678. SourceLocation Loc,
  3679. SourceRange ArgRange) {
  3680. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3681. // scalar or vector data type argument..."
  3682. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3683. // type (C99 6.2.5p18) or void.
  3684. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3685. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3686. << T << ArgRange;
  3687. return true;
  3688. }
  3689. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3690. "Scalar types should always be complete");
  3691. return false;
  3692. }
  3693. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3694. SourceLocation Loc,
  3695. SourceRange ArgRange,
  3696. UnaryExprOrTypeTrait TraitKind) {
  3697. // Invalid types must be hard errors for SFINAE in C++.
  3698. if (S.LangOpts.CPlusPlus)
  3699. return true;
  3700. // C99 6.5.3.4p1:
  3701. if (T->isFunctionType() &&
  3702. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
  3703. TraitKind == UETT_PreferredAlignOf)) {
  3704. // sizeof(function)/alignof(function) is allowed as an extension.
  3705. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3706. << getTraitSpelling(TraitKind) << ArgRange;
  3707. return false;
  3708. }
  3709. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3710. // this is an error (OpenCL v1.1 s6.3.k)
  3711. if (T->isVoidType()) {
  3712. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3713. : diag::ext_sizeof_alignof_void_type;
  3714. S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
  3715. return false;
  3716. }
  3717. return true;
  3718. }
  3719. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3720. SourceLocation Loc,
  3721. SourceRange ArgRange,
  3722. UnaryExprOrTypeTrait TraitKind) {
  3723. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3724. // runtime doesn't allow it.
  3725. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3726. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3727. << T << (TraitKind == UETT_SizeOf)
  3728. << ArgRange;
  3729. return true;
  3730. }
  3731. return false;
  3732. }
  3733. /// Check whether E is a pointer from a decayed array type (the decayed
  3734. /// pointer type is equal to T) and emit a warning if it is.
  3735. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3736. Expr *E) {
  3737. // Don't warn if the operation changed the type.
  3738. if (T != E->getType())
  3739. return;
  3740. // Now look for array decays.
  3741. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3742. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3743. return;
  3744. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3745. << ICE->getType()
  3746. << ICE->getSubExpr()->getType();
  3747. }
  3748. /// Check the constraints on expression operands to unary type expression
  3749. /// and type traits.
  3750. ///
  3751. /// Completes any types necessary and validates the constraints on the operand
  3752. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3753. /// the expression as it completes the type for that expression through template
  3754. /// instantiation, etc.
  3755. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3756. UnaryExprOrTypeTrait ExprKind) {
  3757. QualType ExprTy = E->getType();
  3758. assert(!ExprTy->isReferenceType());
  3759. bool IsUnevaluatedOperand =
  3760. (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
  3761. ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
  3762. if (IsUnevaluatedOperand) {
  3763. ExprResult Result = CheckUnevaluatedOperand(E);
  3764. if (Result.isInvalid())
  3765. return true;
  3766. E = Result.get();
  3767. }
  3768. // The operand for sizeof and alignof is in an unevaluated expression context,
  3769. // so side effects could result in unintended consequences.
  3770. // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
  3771. // used to build SFINAE gadgets.
  3772. // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
  3773. if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
  3774. !E->isInstantiationDependent() &&
  3775. !E->getType()->isVariableArrayType() &&
  3776. E->HasSideEffects(Context, false))
  3777. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3778. if (ExprKind == UETT_VecStep)
  3779. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3780. E->getSourceRange());
  3781. // Explicitly list some types as extensions.
  3782. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3783. E->getSourceRange(), ExprKind))
  3784. return false;
  3785. // 'alignof' applied to an expression only requires the base element type of
  3786. // the expression to be complete. 'sizeof' requires the expression's type to
  3787. // be complete (and will attempt to complete it if it's an array of unknown
  3788. // bound).
  3789. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3790. if (RequireCompleteSizedType(
  3791. E->getExprLoc(), Context.getBaseElementType(E->getType()),
  3792. diag::err_sizeof_alignof_incomplete_or_sizeless_type,
  3793. getTraitSpelling(ExprKind), E->getSourceRange()))
  3794. return true;
  3795. } else {
  3796. if (RequireCompleteSizedExprType(
  3797. E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
  3798. getTraitSpelling(ExprKind), E->getSourceRange()))
  3799. return true;
  3800. }
  3801. // Completing the expression's type may have changed it.
  3802. ExprTy = E->getType();
  3803. assert(!ExprTy->isReferenceType());
  3804. if (ExprTy->isFunctionType()) {
  3805. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3806. << getTraitSpelling(ExprKind) << E->getSourceRange();
  3807. return true;
  3808. }
  3809. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3810. E->getSourceRange(), ExprKind))
  3811. return true;
  3812. if (ExprKind == UETT_SizeOf) {
  3813. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3814. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3815. QualType OType = PVD->getOriginalType();
  3816. QualType Type = PVD->getType();
  3817. if (Type->isPointerType() && OType->isArrayType()) {
  3818. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3819. << Type << OType;
  3820. Diag(PVD->getLocation(), diag::note_declared_at);
  3821. }
  3822. }
  3823. }
  3824. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3825. // decays into a pointer and returns an unintended result. This is most
  3826. // likely a typo for "sizeof(array) op x".
  3827. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3828. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3829. BO->getLHS());
  3830. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3831. BO->getRHS());
  3832. }
  3833. }
  3834. return false;
  3835. }
  3836. /// Check the constraints on operands to unary expression and type
  3837. /// traits.
  3838. ///
  3839. /// This will complete any types necessary, and validate the various constraints
  3840. /// on those operands.
  3841. ///
  3842. /// The UsualUnaryConversions() function is *not* called by this routine.
  3843. /// C99 6.3.2.1p[2-4] all state:
  3844. /// Except when it is the operand of the sizeof operator ...
  3845. ///
  3846. /// C++ [expr.sizeof]p4
  3847. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3848. /// standard conversions are not applied to the operand of sizeof.
  3849. ///
  3850. /// This policy is followed for all of the unary trait expressions.
  3851. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3852. SourceLocation OpLoc,
  3853. SourceRange ExprRange,
  3854. UnaryExprOrTypeTrait ExprKind) {
  3855. if (ExprType->isDependentType())
  3856. return false;
  3857. // C++ [expr.sizeof]p2:
  3858. // When applied to a reference or a reference type, the result
  3859. // is the size of the referenced type.
  3860. // C++11 [expr.alignof]p3:
  3861. // When alignof is applied to a reference type, the result
  3862. // shall be the alignment of the referenced type.
  3863. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3864. ExprType = Ref->getPointeeType();
  3865. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3866. // When alignof or _Alignof is applied to an array type, the result
  3867. // is the alignment of the element type.
  3868. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
  3869. ExprKind == UETT_OpenMPRequiredSimdAlign)
  3870. ExprType = Context.getBaseElementType(ExprType);
  3871. if (ExprKind == UETT_VecStep)
  3872. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3873. // Explicitly list some types as extensions.
  3874. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3875. ExprKind))
  3876. return false;
  3877. if (RequireCompleteSizedType(
  3878. OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
  3879. getTraitSpelling(ExprKind), ExprRange))
  3880. return true;
  3881. if (ExprType->isFunctionType()) {
  3882. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3883. << getTraitSpelling(ExprKind) << ExprRange;
  3884. return true;
  3885. }
  3886. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3887. ExprKind))
  3888. return true;
  3889. return false;
  3890. }
  3891. static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
  3892. // Cannot know anything else if the expression is dependent.
  3893. if (E->isTypeDependent())
  3894. return false;
  3895. if (E->getObjectKind() == OK_BitField) {
  3896. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3897. << 1 << E->getSourceRange();
  3898. return true;
  3899. }
  3900. ValueDecl *D = nullptr;
  3901. Expr *Inner = E->IgnoreParens();
  3902. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
  3903. D = DRE->getDecl();
  3904. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
  3905. D = ME->getMemberDecl();
  3906. }
  3907. // If it's a field, require the containing struct to have a
  3908. // complete definition so that we can compute the layout.
  3909. //
  3910. // This can happen in C++11 onwards, either by naming the member
  3911. // in a way that is not transformed into a member access expression
  3912. // (in an unevaluated operand, for instance), or by naming the member
  3913. // in a trailing-return-type.
  3914. //
  3915. // For the record, since __alignof__ on expressions is a GCC
  3916. // extension, GCC seems to permit this but always gives the
  3917. // nonsensical answer 0.
  3918. //
  3919. // We don't really need the layout here --- we could instead just
  3920. // directly check for all the appropriate alignment-lowing
  3921. // attributes --- but that would require duplicating a lot of
  3922. // logic that just isn't worth duplicating for such a marginal
  3923. // use-case.
  3924. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3925. // Fast path this check, since we at least know the record has a
  3926. // definition if we can find a member of it.
  3927. if (!FD->getParent()->isCompleteDefinition()) {
  3928. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3929. << E->getSourceRange();
  3930. return true;
  3931. }
  3932. // Otherwise, if it's a field, and the field doesn't have
  3933. // reference type, then it must have a complete type (or be a
  3934. // flexible array member, which we explicitly want to
  3935. // white-list anyway), which makes the following checks trivial.
  3936. if (!FD->getType()->isReferenceType())
  3937. return false;
  3938. }
  3939. return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
  3940. }
  3941. bool Sema::CheckVecStepExpr(Expr *E) {
  3942. E = E->IgnoreParens();
  3943. // Cannot know anything else if the expression is dependent.
  3944. if (E->isTypeDependent())
  3945. return false;
  3946. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3947. }
  3948. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3949. CapturingScopeInfo *CSI) {
  3950. assert(T->isVariablyModifiedType());
  3951. assert(CSI != nullptr);
  3952. // We're going to walk down into the type and look for VLA expressions.
  3953. do {
  3954. const Type *Ty = T.getTypePtr();
  3955. switch (Ty->getTypeClass()) {
  3956. #define TYPE(Class, Base)
  3957. #define ABSTRACT_TYPE(Class, Base)
  3958. #define NON_CANONICAL_TYPE(Class, Base)
  3959. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3960. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3961. #include "clang/AST/TypeNodes.inc"
  3962. T = QualType();
  3963. break;
  3964. // These types are never variably-modified.
  3965. case Type::Builtin:
  3966. case Type::Complex:
  3967. case Type::Vector:
  3968. case Type::ExtVector:
  3969. case Type::ConstantMatrix:
  3970. case Type::Record:
  3971. case Type::Enum:
  3972. case Type::TemplateSpecialization:
  3973. case Type::ObjCObject:
  3974. case Type::ObjCInterface:
  3975. case Type::ObjCObjectPointer:
  3976. case Type::ObjCTypeParam:
  3977. case Type::Pipe:
  3978. case Type::BitInt:
  3979. llvm_unreachable("type class is never variably-modified!");
  3980. case Type::Elaborated:
  3981. T = cast<ElaboratedType>(Ty)->getNamedType();
  3982. break;
  3983. case Type::Adjusted:
  3984. T = cast<AdjustedType>(Ty)->getOriginalType();
  3985. break;
  3986. case Type::Decayed:
  3987. T = cast<DecayedType>(Ty)->getPointeeType();
  3988. break;
  3989. case Type::Pointer:
  3990. T = cast<PointerType>(Ty)->getPointeeType();
  3991. break;
  3992. case Type::BlockPointer:
  3993. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3994. break;
  3995. case Type::LValueReference:
  3996. case Type::RValueReference:
  3997. T = cast<ReferenceType>(Ty)->getPointeeType();
  3998. break;
  3999. case Type::MemberPointer:
  4000. T = cast<MemberPointerType>(Ty)->getPointeeType();
  4001. break;
  4002. case Type::ConstantArray:
  4003. case Type::IncompleteArray:
  4004. // Losing element qualification here is fine.
  4005. T = cast<ArrayType>(Ty)->getElementType();
  4006. break;
  4007. case Type::VariableArray: {
  4008. // Losing element qualification here is fine.
  4009. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  4010. // Unknown size indication requires no size computation.
  4011. // Otherwise, evaluate and record it.
  4012. auto Size = VAT->getSizeExpr();
  4013. if (Size && !CSI->isVLATypeCaptured(VAT) &&
  4014. (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
  4015. CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
  4016. T = VAT->getElementType();
  4017. break;
  4018. }
  4019. case Type::FunctionProto:
  4020. case Type::FunctionNoProto:
  4021. T = cast<FunctionType>(Ty)->getReturnType();
  4022. break;
  4023. case Type::Paren:
  4024. case Type::TypeOf:
  4025. case Type::UnaryTransform:
  4026. case Type::Attributed:
  4027. case Type::BTFTagAttributed:
  4028. case Type::SubstTemplateTypeParm:
  4029. case Type::MacroQualified:
  4030. // Keep walking after single level desugaring.
  4031. T = T.getSingleStepDesugaredType(Context);
  4032. break;
  4033. case Type::Typedef:
  4034. T = cast<TypedefType>(Ty)->desugar();
  4035. break;
  4036. case Type::Decltype:
  4037. T = cast<DecltypeType>(Ty)->desugar();
  4038. break;
  4039. case Type::Using:
  4040. T = cast<UsingType>(Ty)->desugar();
  4041. break;
  4042. case Type::Auto:
  4043. case Type::DeducedTemplateSpecialization:
  4044. T = cast<DeducedType>(Ty)->getDeducedType();
  4045. break;
  4046. case Type::TypeOfExpr:
  4047. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  4048. break;
  4049. case Type::Atomic:
  4050. T = cast<AtomicType>(Ty)->getValueType();
  4051. break;
  4052. }
  4053. } while (!T.isNull() && T->isVariablyModifiedType());
  4054. }
  4055. /// Build a sizeof or alignof expression given a type operand.
  4056. ExprResult
  4057. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  4058. SourceLocation OpLoc,
  4059. UnaryExprOrTypeTrait ExprKind,
  4060. SourceRange R) {
  4061. if (!TInfo)
  4062. return ExprError();
  4063. QualType T = TInfo->getType();
  4064. if (!T->isDependentType() &&
  4065. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  4066. return ExprError();
  4067. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  4068. if (auto *TT = T->getAs<TypedefType>()) {
  4069. for (auto I = FunctionScopes.rbegin(),
  4070. E = std::prev(FunctionScopes.rend());
  4071. I != E; ++I) {
  4072. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  4073. if (CSI == nullptr)
  4074. break;
  4075. DeclContext *DC = nullptr;
  4076. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  4077. DC = LSI->CallOperator;
  4078. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  4079. DC = CRSI->TheCapturedDecl;
  4080. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  4081. DC = BSI->TheDecl;
  4082. if (DC) {
  4083. if (DC->containsDecl(TT->getDecl()))
  4084. break;
  4085. captureVariablyModifiedType(Context, T, CSI);
  4086. }
  4087. }
  4088. }
  4089. }
  4090. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  4091. if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
  4092. TInfo->getType()->isVariablyModifiedType())
  4093. TInfo = TransformToPotentiallyEvaluated(TInfo);
  4094. return new (Context) UnaryExprOrTypeTraitExpr(
  4095. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  4096. }
  4097. /// Build a sizeof or alignof expression given an expression
  4098. /// operand.
  4099. ExprResult
  4100. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  4101. UnaryExprOrTypeTrait ExprKind) {
  4102. ExprResult PE = CheckPlaceholderExpr(E);
  4103. if (PE.isInvalid())
  4104. return ExprError();
  4105. E = PE.get();
  4106. // Verify that the operand is valid.
  4107. bool isInvalid = false;
  4108. if (E->isTypeDependent()) {
  4109. // Delay type-checking for type-dependent expressions.
  4110. } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  4111. isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
  4112. } else if (ExprKind == UETT_VecStep) {
  4113. isInvalid = CheckVecStepExpr(E);
  4114. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  4115. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  4116. isInvalid = true;
  4117. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  4118. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  4119. isInvalid = true;
  4120. } else {
  4121. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  4122. }
  4123. if (isInvalid)
  4124. return ExprError();
  4125. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  4126. PE = TransformToPotentiallyEvaluated(E);
  4127. if (PE.isInvalid()) return ExprError();
  4128. E = PE.get();
  4129. }
  4130. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  4131. return new (Context) UnaryExprOrTypeTraitExpr(
  4132. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  4133. }
  4134. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  4135. /// expr and the same for @c alignof and @c __alignof
  4136. /// Note that the ArgRange is invalid if isType is false.
  4137. ExprResult
  4138. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  4139. UnaryExprOrTypeTrait ExprKind, bool IsType,
  4140. void *TyOrEx, SourceRange ArgRange) {
  4141. // If error parsing type, ignore.
  4142. if (!TyOrEx) return ExprError();
  4143. if (IsType) {
  4144. TypeSourceInfo *TInfo;
  4145. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  4146. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  4147. }
  4148. Expr *ArgEx = (Expr *)TyOrEx;
  4149. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  4150. return Result;
  4151. }
  4152. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  4153. bool IsReal) {
  4154. if (V.get()->isTypeDependent())
  4155. return S.Context.DependentTy;
  4156. // _Real and _Imag are only l-values for normal l-values.
  4157. if (V.get()->getObjectKind() != OK_Ordinary) {
  4158. V = S.DefaultLvalueConversion(V.get());
  4159. if (V.isInvalid())
  4160. return QualType();
  4161. }
  4162. // These operators return the element type of a complex type.
  4163. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  4164. return CT->getElementType();
  4165. // Otherwise they pass through real integer and floating point types here.
  4166. if (V.get()->getType()->isArithmeticType())
  4167. return V.get()->getType();
  4168. // Test for placeholders.
  4169. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  4170. if (PR.isInvalid()) return QualType();
  4171. if (PR.get() != V.get()) {
  4172. V = PR;
  4173. return CheckRealImagOperand(S, V, Loc, IsReal);
  4174. }
  4175. // Reject anything else.
  4176. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  4177. << (IsReal ? "__real" : "__imag");
  4178. return QualType();
  4179. }
  4180. ExprResult
  4181. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  4182. tok::TokenKind Kind, Expr *Input) {
  4183. UnaryOperatorKind Opc;
  4184. switch (Kind) {
  4185. default: llvm_unreachable("Unknown unary op!");
  4186. case tok::plusplus: Opc = UO_PostInc; break;
  4187. case tok::minusminus: Opc = UO_PostDec; break;
  4188. }
  4189. // Since this might is a postfix expression, get rid of ParenListExprs.
  4190. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  4191. if (Result.isInvalid()) return ExprError();
  4192. Input = Result.get();
  4193. return BuildUnaryOp(S, OpLoc, Opc, Input);
  4194. }
  4195. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  4196. ///
  4197. /// \return true on error
  4198. static bool checkArithmeticOnObjCPointer(Sema &S,
  4199. SourceLocation opLoc,
  4200. Expr *op) {
  4201. assert(op->getType()->isObjCObjectPointerType());
  4202. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  4203. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  4204. return false;
  4205. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  4206. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  4207. << op->getSourceRange();
  4208. return true;
  4209. }
  4210. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  4211. auto *BaseNoParens = Base->IgnoreParens();
  4212. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  4213. return MSProp->getPropertyDecl()->getType()->isArrayType();
  4214. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  4215. }
  4216. // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
  4217. // Typically this is DependentTy, but can sometimes be more precise.
  4218. //
  4219. // There are cases when we could determine a non-dependent type:
  4220. // - LHS and RHS may have non-dependent types despite being type-dependent
  4221. // (e.g. unbounded array static members of the current instantiation)
  4222. // - one may be a dependent-sized array with known element type
  4223. // - one may be a dependent-typed valid index (enum in current instantiation)
  4224. //
  4225. // We *always* return a dependent type, in such cases it is DependentTy.
  4226. // This avoids creating type-dependent expressions with non-dependent types.
  4227. // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
  4228. static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
  4229. const ASTContext &Ctx) {
  4230. assert(LHS->isTypeDependent() || RHS->isTypeDependent());
  4231. QualType LTy = LHS->getType(), RTy = RHS->getType();
  4232. QualType Result = Ctx.DependentTy;
  4233. if (RTy->isIntegralOrUnscopedEnumerationType()) {
  4234. if (const PointerType *PT = LTy->getAs<PointerType>())
  4235. Result = PT->getPointeeType();
  4236. else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
  4237. Result = AT->getElementType();
  4238. } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
  4239. if (const PointerType *PT = RTy->getAs<PointerType>())
  4240. Result = PT->getPointeeType();
  4241. else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
  4242. Result = AT->getElementType();
  4243. }
  4244. // Ensure we return a dependent type.
  4245. return Result->isDependentType() ? Result : Ctx.DependentTy;
  4246. }
  4247. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
  4248. ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
  4249. SourceLocation lbLoc,
  4250. MultiExprArg ArgExprs,
  4251. SourceLocation rbLoc) {
  4252. if (base && !base->getType().isNull() &&
  4253. base->hasPlaceholderType(BuiltinType::OMPArraySection))
  4254. return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
  4255. SourceLocation(), /*Length*/ nullptr,
  4256. /*Stride=*/nullptr, rbLoc);
  4257. // Since this might be a postfix expression, get rid of ParenListExprs.
  4258. if (isa<ParenListExpr>(base)) {
  4259. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  4260. if (result.isInvalid())
  4261. return ExprError();
  4262. base = result.get();
  4263. }
  4264. // Check if base and idx form a MatrixSubscriptExpr.
  4265. //
  4266. // Helper to check for comma expressions, which are not allowed as indices for
  4267. // matrix subscript expressions.
  4268. auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
  4269. if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
  4270. Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
  4271. << SourceRange(base->getBeginLoc(), rbLoc);
  4272. return true;
  4273. }
  4274. return false;
  4275. };
  4276. // The matrix subscript operator ([][])is considered a single operator.
  4277. // Separating the index expressions by parenthesis is not allowed.
  4278. if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
  4279. !isa<MatrixSubscriptExpr>(base)) {
  4280. Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
  4281. << SourceRange(base->getBeginLoc(), rbLoc);
  4282. return ExprError();
  4283. }
  4284. // If the base is a MatrixSubscriptExpr, try to create a new
  4285. // MatrixSubscriptExpr.
  4286. auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
  4287. if (matSubscriptE) {
  4288. assert(ArgExprs.size() == 1);
  4289. if (CheckAndReportCommaError(ArgExprs.front()))
  4290. return ExprError();
  4291. assert(matSubscriptE->isIncomplete() &&
  4292. "base has to be an incomplete matrix subscript");
  4293. return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
  4294. matSubscriptE->getRowIdx(),
  4295. ArgExprs.front(), rbLoc);
  4296. }
  4297. // Handle any non-overload placeholder types in the base and index
  4298. // expressions. We can't handle overloads here because the other
  4299. // operand might be an overloadable type, in which case the overload
  4300. // resolution for the operator overload should get the first crack
  4301. // at the overload.
  4302. bool IsMSPropertySubscript = false;
  4303. if (base->getType()->isNonOverloadPlaceholderType()) {
  4304. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  4305. if (!IsMSPropertySubscript) {
  4306. ExprResult result = CheckPlaceholderExpr(base);
  4307. if (result.isInvalid())
  4308. return ExprError();
  4309. base = result.get();
  4310. }
  4311. }
  4312. // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
  4313. if (base->getType()->isMatrixType()) {
  4314. assert(ArgExprs.size() == 1);
  4315. if (CheckAndReportCommaError(ArgExprs.front()))
  4316. return ExprError();
  4317. return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
  4318. rbLoc);
  4319. }
  4320. if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
  4321. Expr *idx = ArgExprs[0];
  4322. if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
  4323. (isa<CXXOperatorCallExpr>(idx) &&
  4324. cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
  4325. Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
  4326. << SourceRange(base->getBeginLoc(), rbLoc);
  4327. }
  4328. }
  4329. if (ArgExprs.size() == 1 &&
  4330. ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
  4331. ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
  4332. if (result.isInvalid())
  4333. return ExprError();
  4334. ArgExprs[0] = result.get();
  4335. } else {
  4336. if (checkArgsForPlaceholders(*this, ArgExprs))
  4337. return ExprError();
  4338. }
  4339. // Build an unanalyzed expression if either operand is type-dependent.
  4340. if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
  4341. (base->isTypeDependent() ||
  4342. Expr::hasAnyTypeDependentArguments(ArgExprs))) {
  4343. return new (Context) ArraySubscriptExpr(
  4344. base, ArgExprs.front(),
  4345. getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
  4346. VK_LValue, OK_Ordinary, rbLoc);
  4347. }
  4348. // MSDN, property (C++)
  4349. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  4350. // This attribute can also be used in the declaration of an empty array in a
  4351. // class or structure definition. For example:
  4352. // __declspec(property(get=GetX, put=PutX)) int x[];
  4353. // The above statement indicates that x[] can be used with one or more array
  4354. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  4355. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  4356. if (IsMSPropertySubscript) {
  4357. assert(ArgExprs.size() == 1);
  4358. // Build MS property subscript expression if base is MS property reference
  4359. // or MS property subscript.
  4360. return new (Context)
  4361. MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
  4362. VK_LValue, OK_Ordinary, rbLoc);
  4363. }
  4364. // Use C++ overloaded-operator rules if either operand has record
  4365. // type. The spec says to do this if either type is *overloadable*,
  4366. // but enum types can't declare subscript operators or conversion
  4367. // operators, so there's nothing interesting for overload resolution
  4368. // to do if there aren't any record types involved.
  4369. //
  4370. // ObjC pointers have their own subscripting logic that is not tied
  4371. // to overload resolution and so should not take this path.
  4372. if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
  4373. ((base->getType()->isRecordType() ||
  4374. (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
  4375. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
  4376. }
  4377. ExprResult Res =
  4378. CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
  4379. if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
  4380. CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
  4381. return Res;
  4382. }
  4383. ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
  4384. InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
  4385. InitializationKind Kind =
  4386. InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
  4387. InitializationSequence InitSeq(*this, Entity, Kind, E);
  4388. return InitSeq.Perform(*this, Entity, Kind, E);
  4389. }
  4390. ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
  4391. Expr *ColumnIdx,
  4392. SourceLocation RBLoc) {
  4393. ExprResult BaseR = CheckPlaceholderExpr(Base);
  4394. if (BaseR.isInvalid())
  4395. return BaseR;
  4396. Base = BaseR.get();
  4397. ExprResult RowR = CheckPlaceholderExpr(RowIdx);
  4398. if (RowR.isInvalid())
  4399. return RowR;
  4400. RowIdx = RowR.get();
  4401. if (!ColumnIdx)
  4402. return new (Context) MatrixSubscriptExpr(
  4403. Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
  4404. // Build an unanalyzed expression if any of the operands is type-dependent.
  4405. if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
  4406. ColumnIdx->isTypeDependent())
  4407. return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
  4408. Context.DependentTy, RBLoc);
  4409. ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
  4410. if (ColumnR.isInvalid())
  4411. return ColumnR;
  4412. ColumnIdx = ColumnR.get();
  4413. // Check that IndexExpr is an integer expression. If it is a constant
  4414. // expression, check that it is less than Dim (= the number of elements in the
  4415. // corresponding dimension).
  4416. auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
  4417. bool IsColumnIdx) -> Expr * {
  4418. if (!IndexExpr->getType()->isIntegerType() &&
  4419. !IndexExpr->isTypeDependent()) {
  4420. Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
  4421. << IsColumnIdx;
  4422. return nullptr;
  4423. }
  4424. if (std::optional<llvm::APSInt> Idx =
  4425. IndexExpr->getIntegerConstantExpr(Context)) {
  4426. if ((*Idx < 0 || *Idx >= Dim)) {
  4427. Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
  4428. << IsColumnIdx << Dim;
  4429. return nullptr;
  4430. }
  4431. }
  4432. ExprResult ConvExpr =
  4433. tryConvertExprToType(IndexExpr, Context.getSizeType());
  4434. assert(!ConvExpr.isInvalid() &&
  4435. "should be able to convert any integer type to size type");
  4436. return ConvExpr.get();
  4437. };
  4438. auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
  4439. RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
  4440. ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
  4441. if (!RowIdx || !ColumnIdx)
  4442. return ExprError();
  4443. return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
  4444. MTy->getElementType(), RBLoc);
  4445. }
  4446. void Sema::CheckAddressOfNoDeref(const Expr *E) {
  4447. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  4448. const Expr *StrippedExpr = E->IgnoreParenImpCasts();
  4449. // For expressions like `&(*s).b`, the base is recorded and what should be
  4450. // checked.
  4451. const MemberExpr *Member = nullptr;
  4452. while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
  4453. StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
  4454. LastRecord.PossibleDerefs.erase(StrippedExpr);
  4455. }
  4456. void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
  4457. if (isUnevaluatedContext())
  4458. return;
  4459. QualType ResultTy = E->getType();
  4460. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  4461. // Bail if the element is an array since it is not memory access.
  4462. if (isa<ArrayType>(ResultTy))
  4463. return;
  4464. if (ResultTy->hasAttr(attr::NoDeref)) {
  4465. LastRecord.PossibleDerefs.insert(E);
  4466. return;
  4467. }
  4468. // Check if the base type is a pointer to a member access of a struct
  4469. // marked with noderef.
  4470. const Expr *Base = E->getBase();
  4471. QualType BaseTy = Base->getType();
  4472. if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
  4473. // Not a pointer access
  4474. return;
  4475. const MemberExpr *Member = nullptr;
  4476. while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
  4477. Member->isArrow())
  4478. Base = Member->getBase();
  4479. if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
  4480. if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
  4481. LastRecord.PossibleDerefs.insert(E);
  4482. }
  4483. }
  4484. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  4485. Expr *LowerBound,
  4486. SourceLocation ColonLocFirst,
  4487. SourceLocation ColonLocSecond,
  4488. Expr *Length, Expr *Stride,
  4489. SourceLocation RBLoc) {
  4490. if (Base->hasPlaceholderType() &&
  4491. !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
  4492. ExprResult Result = CheckPlaceholderExpr(Base);
  4493. if (Result.isInvalid())
  4494. return ExprError();
  4495. Base = Result.get();
  4496. }
  4497. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  4498. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  4499. if (Result.isInvalid())
  4500. return ExprError();
  4501. Result = DefaultLvalueConversion(Result.get());
  4502. if (Result.isInvalid())
  4503. return ExprError();
  4504. LowerBound = Result.get();
  4505. }
  4506. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  4507. ExprResult Result = CheckPlaceholderExpr(Length);
  4508. if (Result.isInvalid())
  4509. return ExprError();
  4510. Result = DefaultLvalueConversion(Result.get());
  4511. if (Result.isInvalid())
  4512. return ExprError();
  4513. Length = Result.get();
  4514. }
  4515. if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
  4516. ExprResult Result = CheckPlaceholderExpr(Stride);
  4517. if (Result.isInvalid())
  4518. return ExprError();
  4519. Result = DefaultLvalueConversion(Result.get());
  4520. if (Result.isInvalid())
  4521. return ExprError();
  4522. Stride = Result.get();
  4523. }
  4524. // Build an unanalyzed expression if either operand is type-dependent.
  4525. if (Base->isTypeDependent() ||
  4526. (LowerBound &&
  4527. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  4528. (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
  4529. (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
  4530. return new (Context) OMPArraySectionExpr(
  4531. Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
  4532. OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
  4533. }
  4534. // Perform default conversions.
  4535. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  4536. QualType ResultTy;
  4537. if (OriginalTy->isAnyPointerType()) {
  4538. ResultTy = OriginalTy->getPointeeType();
  4539. } else if (OriginalTy->isArrayType()) {
  4540. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  4541. } else {
  4542. return ExprError(
  4543. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  4544. << Base->getSourceRange());
  4545. }
  4546. // C99 6.5.2.1p1
  4547. if (LowerBound) {
  4548. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  4549. LowerBound);
  4550. if (Res.isInvalid())
  4551. return ExprError(Diag(LowerBound->getExprLoc(),
  4552. diag::err_omp_typecheck_section_not_integer)
  4553. << 0 << LowerBound->getSourceRange());
  4554. LowerBound = Res.get();
  4555. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4556. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4557. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  4558. << 0 << LowerBound->getSourceRange();
  4559. }
  4560. if (Length) {
  4561. auto Res =
  4562. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  4563. if (Res.isInvalid())
  4564. return ExprError(Diag(Length->getExprLoc(),
  4565. diag::err_omp_typecheck_section_not_integer)
  4566. << 1 << Length->getSourceRange());
  4567. Length = Res.get();
  4568. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4569. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4570. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  4571. << 1 << Length->getSourceRange();
  4572. }
  4573. if (Stride) {
  4574. ExprResult Res =
  4575. PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
  4576. if (Res.isInvalid())
  4577. return ExprError(Diag(Stride->getExprLoc(),
  4578. diag::err_omp_typecheck_section_not_integer)
  4579. << 1 << Stride->getSourceRange());
  4580. Stride = Res.get();
  4581. if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4582. Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4583. Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
  4584. << 1 << Stride->getSourceRange();
  4585. }
  4586. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  4587. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  4588. // type. Note that functions are not objects, and that (in C99 parlance)
  4589. // incomplete types are not object types.
  4590. if (ResultTy->isFunctionType()) {
  4591. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  4592. << ResultTy << Base->getSourceRange();
  4593. return ExprError();
  4594. }
  4595. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  4596. diag::err_omp_section_incomplete_type, Base))
  4597. return ExprError();
  4598. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  4599. Expr::EvalResult Result;
  4600. if (LowerBound->EvaluateAsInt(Result, Context)) {
  4601. // OpenMP 5.0, [2.1.5 Array Sections]
  4602. // The array section must be a subset of the original array.
  4603. llvm::APSInt LowerBoundValue = Result.Val.getInt();
  4604. if (LowerBoundValue.isNegative()) {
  4605. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  4606. << LowerBound->getSourceRange();
  4607. return ExprError();
  4608. }
  4609. }
  4610. }
  4611. if (Length) {
  4612. Expr::EvalResult Result;
  4613. if (Length->EvaluateAsInt(Result, Context)) {
  4614. // OpenMP 5.0, [2.1.5 Array Sections]
  4615. // The length must evaluate to non-negative integers.
  4616. llvm::APSInt LengthValue = Result.Val.getInt();
  4617. if (LengthValue.isNegative()) {
  4618. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  4619. << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
  4620. << Length->getSourceRange();
  4621. return ExprError();
  4622. }
  4623. }
  4624. } else if (ColonLocFirst.isValid() &&
  4625. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  4626. !OriginalTy->isVariableArrayType()))) {
  4627. // OpenMP 5.0, [2.1.5 Array Sections]
  4628. // When the size of the array dimension is not known, the length must be
  4629. // specified explicitly.
  4630. Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
  4631. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  4632. return ExprError();
  4633. }
  4634. if (Stride) {
  4635. Expr::EvalResult Result;
  4636. if (Stride->EvaluateAsInt(Result, Context)) {
  4637. // OpenMP 5.0, [2.1.5 Array Sections]
  4638. // The stride must evaluate to a positive integer.
  4639. llvm::APSInt StrideValue = Result.Val.getInt();
  4640. if (!StrideValue.isStrictlyPositive()) {
  4641. Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
  4642. << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
  4643. << Stride->getSourceRange();
  4644. return ExprError();
  4645. }
  4646. }
  4647. }
  4648. if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
  4649. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  4650. if (Result.isInvalid())
  4651. return ExprError();
  4652. Base = Result.get();
  4653. }
  4654. return new (Context) OMPArraySectionExpr(
  4655. Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
  4656. OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
  4657. }
  4658. ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
  4659. SourceLocation RParenLoc,
  4660. ArrayRef<Expr *> Dims,
  4661. ArrayRef<SourceRange> Brackets) {
  4662. if (Base->hasPlaceholderType()) {
  4663. ExprResult Result = CheckPlaceholderExpr(Base);
  4664. if (Result.isInvalid())
  4665. return ExprError();
  4666. Result = DefaultLvalueConversion(Result.get());
  4667. if (Result.isInvalid())
  4668. return ExprError();
  4669. Base = Result.get();
  4670. }
  4671. QualType BaseTy = Base->getType();
  4672. // Delay analysis of the types/expressions if instantiation/specialization is
  4673. // required.
  4674. if (!BaseTy->isPointerType() && Base->isTypeDependent())
  4675. return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
  4676. LParenLoc, RParenLoc, Dims, Brackets);
  4677. if (!BaseTy->isPointerType() ||
  4678. (!Base->isTypeDependent() &&
  4679. BaseTy->getPointeeType()->isIncompleteType()))
  4680. return ExprError(Diag(Base->getExprLoc(),
  4681. diag::err_omp_non_pointer_type_array_shaping_base)
  4682. << Base->getSourceRange());
  4683. SmallVector<Expr *, 4> NewDims;
  4684. bool ErrorFound = false;
  4685. for (Expr *Dim : Dims) {
  4686. if (Dim->hasPlaceholderType()) {
  4687. ExprResult Result = CheckPlaceholderExpr(Dim);
  4688. if (Result.isInvalid()) {
  4689. ErrorFound = true;
  4690. continue;
  4691. }
  4692. Result = DefaultLvalueConversion(Result.get());
  4693. if (Result.isInvalid()) {
  4694. ErrorFound = true;
  4695. continue;
  4696. }
  4697. Dim = Result.get();
  4698. }
  4699. if (!Dim->isTypeDependent()) {
  4700. ExprResult Result =
  4701. PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
  4702. if (Result.isInvalid()) {
  4703. ErrorFound = true;
  4704. Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
  4705. << Dim->getSourceRange();
  4706. continue;
  4707. }
  4708. Dim = Result.get();
  4709. Expr::EvalResult EvResult;
  4710. if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
  4711. // OpenMP 5.0, [2.1.4 Array Shaping]
  4712. // Each si is an integral type expression that must evaluate to a
  4713. // positive integer.
  4714. llvm::APSInt Value = EvResult.Val.getInt();
  4715. if (!Value.isStrictlyPositive()) {
  4716. Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
  4717. << toString(Value, /*Radix=*/10, /*Signed=*/true)
  4718. << Dim->getSourceRange();
  4719. ErrorFound = true;
  4720. continue;
  4721. }
  4722. }
  4723. }
  4724. NewDims.push_back(Dim);
  4725. }
  4726. if (ErrorFound)
  4727. return ExprError();
  4728. return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
  4729. LParenLoc, RParenLoc, NewDims, Brackets);
  4730. }
  4731. ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
  4732. SourceLocation LLoc, SourceLocation RLoc,
  4733. ArrayRef<OMPIteratorData> Data) {
  4734. SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
  4735. bool IsCorrect = true;
  4736. for (const OMPIteratorData &D : Data) {
  4737. TypeSourceInfo *TInfo = nullptr;
  4738. SourceLocation StartLoc;
  4739. QualType DeclTy;
  4740. if (!D.Type.getAsOpaquePtr()) {
  4741. // OpenMP 5.0, 2.1.6 Iterators
  4742. // In an iterator-specifier, if the iterator-type is not specified then
  4743. // the type of that iterator is of int type.
  4744. DeclTy = Context.IntTy;
  4745. StartLoc = D.DeclIdentLoc;
  4746. } else {
  4747. DeclTy = GetTypeFromParser(D.Type, &TInfo);
  4748. StartLoc = TInfo->getTypeLoc().getBeginLoc();
  4749. }
  4750. bool IsDeclTyDependent = DeclTy->isDependentType() ||
  4751. DeclTy->containsUnexpandedParameterPack() ||
  4752. DeclTy->isInstantiationDependentType();
  4753. if (!IsDeclTyDependent) {
  4754. if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
  4755. // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
  4756. // The iterator-type must be an integral or pointer type.
  4757. Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
  4758. << DeclTy;
  4759. IsCorrect = false;
  4760. continue;
  4761. }
  4762. if (DeclTy.isConstant(Context)) {
  4763. // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
  4764. // The iterator-type must not be const qualified.
  4765. Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
  4766. << DeclTy;
  4767. IsCorrect = false;
  4768. continue;
  4769. }
  4770. }
  4771. // Iterator declaration.
  4772. assert(D.DeclIdent && "Identifier expected.");
  4773. // Always try to create iterator declarator to avoid extra error messages
  4774. // about unknown declarations use.
  4775. auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
  4776. D.DeclIdent, DeclTy, TInfo, SC_None);
  4777. VD->setImplicit();
  4778. if (S) {
  4779. // Check for conflicting previous declaration.
  4780. DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
  4781. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4782. ForVisibleRedeclaration);
  4783. Previous.suppressDiagnostics();
  4784. LookupName(Previous, S);
  4785. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
  4786. /*AllowInlineNamespace=*/false);
  4787. if (!Previous.empty()) {
  4788. NamedDecl *Old = Previous.getRepresentativeDecl();
  4789. Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
  4790. Diag(Old->getLocation(), diag::note_previous_definition);
  4791. } else {
  4792. PushOnScopeChains(VD, S);
  4793. }
  4794. } else {
  4795. CurContext->addDecl(VD);
  4796. }
  4797. /// Act on the iterator variable declaration.
  4798. ActOnOpenMPIteratorVarDecl(VD);
  4799. Expr *Begin = D.Range.Begin;
  4800. if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
  4801. ExprResult BeginRes =
  4802. PerformImplicitConversion(Begin, DeclTy, AA_Converting);
  4803. Begin = BeginRes.get();
  4804. }
  4805. Expr *End = D.Range.End;
  4806. if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
  4807. ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
  4808. End = EndRes.get();
  4809. }
  4810. Expr *Step = D.Range.Step;
  4811. if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
  4812. if (!Step->getType()->isIntegralType(Context)) {
  4813. Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
  4814. << Step << Step->getSourceRange();
  4815. IsCorrect = false;
  4816. continue;
  4817. }
  4818. std::optional<llvm::APSInt> Result =
  4819. Step->getIntegerConstantExpr(Context);
  4820. // OpenMP 5.0, 2.1.6 Iterators, Restrictions
  4821. // If the step expression of a range-specification equals zero, the
  4822. // behavior is unspecified.
  4823. if (Result && Result->isZero()) {
  4824. Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
  4825. << Step << Step->getSourceRange();
  4826. IsCorrect = false;
  4827. continue;
  4828. }
  4829. }
  4830. if (!Begin || !End || !IsCorrect) {
  4831. IsCorrect = false;
  4832. continue;
  4833. }
  4834. OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
  4835. IDElem.IteratorDecl = VD;
  4836. IDElem.AssignmentLoc = D.AssignLoc;
  4837. IDElem.Range.Begin = Begin;
  4838. IDElem.Range.End = End;
  4839. IDElem.Range.Step = Step;
  4840. IDElem.ColonLoc = D.ColonLoc;
  4841. IDElem.SecondColonLoc = D.SecColonLoc;
  4842. }
  4843. if (!IsCorrect) {
  4844. // Invalidate all created iterator declarations if error is found.
  4845. for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
  4846. if (Decl *ID = D.IteratorDecl)
  4847. ID->setInvalidDecl();
  4848. }
  4849. return ExprError();
  4850. }
  4851. SmallVector<OMPIteratorHelperData, 4> Helpers;
  4852. if (!CurContext->isDependentContext()) {
  4853. // Build number of ityeration for each iteration range.
  4854. // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
  4855. // ((Begini-Stepi-1-Endi) / -Stepi);
  4856. for (OMPIteratorExpr::IteratorDefinition &D : ID) {
  4857. // (Endi - Begini)
  4858. ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
  4859. D.Range.Begin);
  4860. if(!Res.isUsable()) {
  4861. IsCorrect = false;
  4862. continue;
  4863. }
  4864. ExprResult St, St1;
  4865. if (D.Range.Step) {
  4866. St = D.Range.Step;
  4867. // (Endi - Begini) + Stepi
  4868. Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
  4869. if (!Res.isUsable()) {
  4870. IsCorrect = false;
  4871. continue;
  4872. }
  4873. // (Endi - Begini) + Stepi - 1
  4874. Res =
  4875. CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
  4876. ActOnIntegerConstant(D.AssignmentLoc, 1).get());
  4877. if (!Res.isUsable()) {
  4878. IsCorrect = false;
  4879. continue;
  4880. }
  4881. // ((Endi - Begini) + Stepi - 1) / Stepi
  4882. Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
  4883. if (!Res.isUsable()) {
  4884. IsCorrect = false;
  4885. continue;
  4886. }
  4887. St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
  4888. // (Begini - Endi)
  4889. ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
  4890. D.Range.Begin, D.Range.End);
  4891. if (!Res1.isUsable()) {
  4892. IsCorrect = false;
  4893. continue;
  4894. }
  4895. // (Begini - Endi) - Stepi
  4896. Res1 =
  4897. CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
  4898. if (!Res1.isUsable()) {
  4899. IsCorrect = false;
  4900. continue;
  4901. }
  4902. // (Begini - Endi) - Stepi - 1
  4903. Res1 =
  4904. CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
  4905. ActOnIntegerConstant(D.AssignmentLoc, 1).get());
  4906. if (!Res1.isUsable()) {
  4907. IsCorrect = false;
  4908. continue;
  4909. }
  4910. // ((Begini - Endi) - Stepi - 1) / (-Stepi)
  4911. Res1 =
  4912. CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
  4913. if (!Res1.isUsable()) {
  4914. IsCorrect = false;
  4915. continue;
  4916. }
  4917. // Stepi > 0.
  4918. ExprResult CmpRes =
  4919. CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
  4920. ActOnIntegerConstant(D.AssignmentLoc, 0).get());
  4921. if (!CmpRes.isUsable()) {
  4922. IsCorrect = false;
  4923. continue;
  4924. }
  4925. Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
  4926. Res.get(), Res1.get());
  4927. if (!Res.isUsable()) {
  4928. IsCorrect = false;
  4929. continue;
  4930. }
  4931. }
  4932. Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
  4933. if (!Res.isUsable()) {
  4934. IsCorrect = false;
  4935. continue;
  4936. }
  4937. // Build counter update.
  4938. // Build counter.
  4939. auto *CounterVD =
  4940. VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
  4941. D.IteratorDecl->getBeginLoc(), nullptr,
  4942. Res.get()->getType(), nullptr, SC_None);
  4943. CounterVD->setImplicit();
  4944. ExprResult RefRes =
  4945. BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
  4946. D.IteratorDecl->getBeginLoc());
  4947. // Build counter update.
  4948. // I = Begini + counter * Stepi;
  4949. ExprResult UpdateRes;
  4950. if (D.Range.Step) {
  4951. UpdateRes = CreateBuiltinBinOp(
  4952. D.AssignmentLoc, BO_Mul,
  4953. DefaultLvalueConversion(RefRes.get()).get(), St.get());
  4954. } else {
  4955. UpdateRes = DefaultLvalueConversion(RefRes.get());
  4956. }
  4957. if (!UpdateRes.isUsable()) {
  4958. IsCorrect = false;
  4959. continue;
  4960. }
  4961. UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
  4962. UpdateRes.get());
  4963. if (!UpdateRes.isUsable()) {
  4964. IsCorrect = false;
  4965. continue;
  4966. }
  4967. ExprResult VDRes =
  4968. BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
  4969. cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
  4970. D.IteratorDecl->getBeginLoc());
  4971. UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
  4972. UpdateRes.get());
  4973. if (!UpdateRes.isUsable()) {
  4974. IsCorrect = false;
  4975. continue;
  4976. }
  4977. UpdateRes =
  4978. ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
  4979. if (!UpdateRes.isUsable()) {
  4980. IsCorrect = false;
  4981. continue;
  4982. }
  4983. ExprResult CounterUpdateRes =
  4984. CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
  4985. if (!CounterUpdateRes.isUsable()) {
  4986. IsCorrect = false;
  4987. continue;
  4988. }
  4989. CounterUpdateRes =
  4990. ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
  4991. if (!CounterUpdateRes.isUsable()) {
  4992. IsCorrect = false;
  4993. continue;
  4994. }
  4995. OMPIteratorHelperData &HD = Helpers.emplace_back();
  4996. HD.CounterVD = CounterVD;
  4997. HD.Upper = Res.get();
  4998. HD.Update = UpdateRes.get();
  4999. HD.CounterUpdate = CounterUpdateRes.get();
  5000. }
  5001. } else {
  5002. Helpers.assign(ID.size(), {});
  5003. }
  5004. if (!IsCorrect) {
  5005. // Invalidate all created iterator declarations if error is found.
  5006. for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
  5007. if (Decl *ID = D.IteratorDecl)
  5008. ID->setInvalidDecl();
  5009. }
  5010. return ExprError();
  5011. }
  5012. return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
  5013. LLoc, RLoc, ID, Helpers);
  5014. }
  5015. ExprResult
  5016. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  5017. Expr *Idx, SourceLocation RLoc) {
  5018. Expr *LHSExp = Base;
  5019. Expr *RHSExp = Idx;
  5020. ExprValueKind VK = VK_LValue;
  5021. ExprObjectKind OK = OK_Ordinary;
  5022. // Per C++ core issue 1213, the result is an xvalue if either operand is
  5023. // a non-lvalue array, and an lvalue otherwise.
  5024. if (getLangOpts().CPlusPlus11) {
  5025. for (auto *Op : {LHSExp, RHSExp}) {
  5026. Op = Op->IgnoreImplicit();
  5027. if (Op->getType()->isArrayType() && !Op->isLValue())
  5028. VK = VK_XValue;
  5029. }
  5030. }
  5031. // Perform default conversions.
  5032. if (!LHSExp->getType()->getAs<VectorType>()) {
  5033. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  5034. if (Result.isInvalid())
  5035. return ExprError();
  5036. LHSExp = Result.get();
  5037. }
  5038. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  5039. if (Result.isInvalid())
  5040. return ExprError();
  5041. RHSExp = Result.get();
  5042. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  5043. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  5044. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  5045. // in the subscript position. As a result, we need to derive the array base
  5046. // and index from the expression types.
  5047. Expr *BaseExpr, *IndexExpr;
  5048. QualType ResultType;
  5049. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  5050. BaseExpr = LHSExp;
  5051. IndexExpr = RHSExp;
  5052. ResultType =
  5053. getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
  5054. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  5055. BaseExpr = LHSExp;
  5056. IndexExpr = RHSExp;
  5057. ResultType = PTy->getPointeeType();
  5058. } else if (const ObjCObjectPointerType *PTy =
  5059. LHSTy->getAs<ObjCObjectPointerType>()) {
  5060. BaseExpr = LHSExp;
  5061. IndexExpr = RHSExp;
  5062. // Use custom logic if this should be the pseudo-object subscript
  5063. // expression.
  5064. if (!LangOpts.isSubscriptPointerArithmetic())
  5065. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  5066. nullptr);
  5067. ResultType = PTy->getPointeeType();
  5068. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  5069. // Handle the uncommon case of "123[Ptr]".
  5070. BaseExpr = RHSExp;
  5071. IndexExpr = LHSExp;
  5072. ResultType = PTy->getPointeeType();
  5073. } else if (const ObjCObjectPointerType *PTy =
  5074. RHSTy->getAs<ObjCObjectPointerType>()) {
  5075. // Handle the uncommon case of "123[Ptr]".
  5076. BaseExpr = RHSExp;
  5077. IndexExpr = LHSExp;
  5078. ResultType = PTy->getPointeeType();
  5079. if (!LangOpts.isSubscriptPointerArithmetic()) {
  5080. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  5081. << ResultType << BaseExpr->getSourceRange();
  5082. return ExprError();
  5083. }
  5084. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  5085. BaseExpr = LHSExp; // vectors: V[123]
  5086. IndexExpr = RHSExp;
  5087. // We apply C++ DR1213 to vector subscripting too.
  5088. if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
  5089. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  5090. if (Materialized.isInvalid())
  5091. return ExprError();
  5092. LHSExp = Materialized.get();
  5093. }
  5094. VK = LHSExp->getValueKind();
  5095. if (VK != VK_PRValue)
  5096. OK = OK_VectorComponent;
  5097. ResultType = VTy->getElementType();
  5098. QualType BaseType = BaseExpr->getType();
  5099. Qualifiers BaseQuals = BaseType.getQualifiers();
  5100. Qualifiers MemberQuals = ResultType.getQualifiers();
  5101. Qualifiers Combined = BaseQuals + MemberQuals;
  5102. if (Combined != MemberQuals)
  5103. ResultType = Context.getQualifiedType(ResultType, Combined);
  5104. } else if (LHSTy->isBuiltinType() &&
  5105. LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
  5106. const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
  5107. if (BTy->isSVEBool())
  5108. return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
  5109. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  5110. BaseExpr = LHSExp;
  5111. IndexExpr = RHSExp;
  5112. if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
  5113. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  5114. if (Materialized.isInvalid())
  5115. return ExprError();
  5116. LHSExp = Materialized.get();
  5117. }
  5118. VK = LHSExp->getValueKind();
  5119. if (VK != VK_PRValue)
  5120. OK = OK_VectorComponent;
  5121. ResultType = BTy->getSveEltType(Context);
  5122. QualType BaseType = BaseExpr->getType();
  5123. Qualifiers BaseQuals = BaseType.getQualifiers();
  5124. Qualifiers MemberQuals = ResultType.getQualifiers();
  5125. Qualifiers Combined = BaseQuals + MemberQuals;
  5126. if (Combined != MemberQuals)
  5127. ResultType = Context.getQualifiedType(ResultType, Combined);
  5128. } else if (LHSTy->isArrayType()) {
  5129. // If we see an array that wasn't promoted by
  5130. // DefaultFunctionArrayLvalueConversion, it must be an array that
  5131. // wasn't promoted because of the C90 rule that doesn't
  5132. // allow promoting non-lvalue arrays. Warn, then
  5133. // force the promotion here.
  5134. Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  5135. << LHSExp->getSourceRange();
  5136. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  5137. CK_ArrayToPointerDecay).get();
  5138. LHSTy = LHSExp->getType();
  5139. BaseExpr = LHSExp;
  5140. IndexExpr = RHSExp;
  5141. ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
  5142. } else if (RHSTy->isArrayType()) {
  5143. // Same as previous, except for 123[f().a] case
  5144. Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  5145. << RHSExp->getSourceRange();
  5146. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  5147. CK_ArrayToPointerDecay).get();
  5148. RHSTy = RHSExp->getType();
  5149. BaseExpr = RHSExp;
  5150. IndexExpr = LHSExp;
  5151. ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
  5152. } else {
  5153. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  5154. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  5155. }
  5156. // C99 6.5.2.1p1
  5157. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  5158. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  5159. << IndexExpr->getSourceRange());
  5160. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  5161. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  5162. && !IndexExpr->isTypeDependent())
  5163. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  5164. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  5165. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  5166. // type. Note that Functions are not objects, and that (in C99 parlance)
  5167. // incomplete types are not object types.
  5168. if (ResultType->isFunctionType()) {
  5169. Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
  5170. << ResultType << BaseExpr->getSourceRange();
  5171. return ExprError();
  5172. }
  5173. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  5174. // GNU extension: subscripting on pointer to void
  5175. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  5176. << BaseExpr->getSourceRange();
  5177. // C forbids expressions of unqualified void type from being l-values.
  5178. // See IsCForbiddenLValueType.
  5179. if (!ResultType.hasQualifiers())
  5180. VK = VK_PRValue;
  5181. } else if (!ResultType->isDependentType() &&
  5182. RequireCompleteSizedType(
  5183. LLoc, ResultType,
  5184. diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
  5185. return ExprError();
  5186. assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
  5187. !ResultType.isCForbiddenLValueType());
  5188. if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
  5189. FunctionScopes.size() > 1) {
  5190. if (auto *TT =
  5191. LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
  5192. for (auto I = FunctionScopes.rbegin(),
  5193. E = std::prev(FunctionScopes.rend());
  5194. I != E; ++I) {
  5195. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  5196. if (CSI == nullptr)
  5197. break;
  5198. DeclContext *DC = nullptr;
  5199. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  5200. DC = LSI->CallOperator;
  5201. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  5202. DC = CRSI->TheCapturedDecl;
  5203. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  5204. DC = BSI->TheDecl;
  5205. if (DC) {
  5206. if (DC->containsDecl(TT->getDecl()))
  5207. break;
  5208. captureVariablyModifiedType(
  5209. Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
  5210. }
  5211. }
  5212. }
  5213. }
  5214. return new (Context)
  5215. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  5216. }
  5217. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  5218. ParmVarDecl *Param, Expr *RewrittenInit,
  5219. bool SkipImmediateInvocations) {
  5220. if (Param->hasUnparsedDefaultArg()) {
  5221. assert(!RewrittenInit && "Should not have a rewritten init expression yet");
  5222. // If we've already cleared out the location for the default argument,
  5223. // that means we're parsing it right now.
  5224. if (!UnparsedDefaultArgLocs.count(Param)) {
  5225. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  5226. Diag(CallLoc, diag::note_recursive_default_argument_used_here);
  5227. Param->setInvalidDecl();
  5228. return true;
  5229. }
  5230. Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
  5231. << FD << cast<CXXRecordDecl>(FD->getDeclContext());
  5232. Diag(UnparsedDefaultArgLocs[Param],
  5233. diag::note_default_argument_declared_here);
  5234. return true;
  5235. }
  5236. if (Param->hasUninstantiatedDefaultArg()) {
  5237. assert(!RewrittenInit && "Should not have a rewitten init expression yet");
  5238. if (InstantiateDefaultArgument(CallLoc, FD, Param))
  5239. return true;
  5240. }
  5241. Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
  5242. assert(Init && "default argument but no initializer?");
  5243. // If the default expression creates temporaries, we need to
  5244. // push them to the current stack of expression temporaries so they'll
  5245. // be properly destroyed.
  5246. // FIXME: We should really be rebuilding the default argument with new
  5247. // bound temporaries; see the comment in PR5810.
  5248. // We don't need to do that with block decls, though, because
  5249. // blocks in default argument expression can never capture anything.
  5250. if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
  5251. // Set the "needs cleanups" bit regardless of whether there are
  5252. // any explicit objects.
  5253. Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
  5254. // Append all the objects to the cleanup list. Right now, this
  5255. // should always be a no-op, because blocks in default argument
  5256. // expressions should never be able to capture anything.
  5257. assert(!InitWithCleanup->getNumObjects() &&
  5258. "default argument expression has capturing blocks?");
  5259. }
  5260. EnterExpressionEvaluationContext EvalContext(
  5261. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  5262. ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
  5263. SkipImmediateInvocations;
  5264. MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables*/ true);
  5265. return false;
  5266. }
  5267. struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
  5268. bool HasImmediateCalls = false;
  5269. bool shouldVisitImplicitCode() const { return true; }
  5270. bool VisitCallExpr(CallExpr *E) {
  5271. if (const FunctionDecl *FD = E->getDirectCallee())
  5272. HasImmediateCalls |= FD->isConsteval();
  5273. return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
  5274. }
  5275. // SourceLocExpr are not immediate invocations
  5276. // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
  5277. // need to be rebuilt so that they refer to the correct SourceLocation and
  5278. // DeclContext.
  5279. bool VisitSourceLocExpr(SourceLocExpr *E) {
  5280. HasImmediateCalls = true;
  5281. return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
  5282. }
  5283. // A nested lambda might have parameters with immediate invocations
  5284. // in their default arguments.
  5285. // The compound statement is not visited (as it does not constitute a
  5286. // subexpression).
  5287. // FIXME: We should consider visiting and transforming captures
  5288. // with init expressions.
  5289. bool VisitLambdaExpr(LambdaExpr *E) {
  5290. return VisitCXXMethodDecl(E->getCallOperator());
  5291. }
  5292. // Blocks don't support default parameters, and, as for lambdas,
  5293. // we don't consider their body a subexpression.
  5294. bool VisitBlockDecl(BlockDecl *B) { return false; }
  5295. bool VisitCompoundStmt(CompoundStmt *B) { return false; }
  5296. bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  5297. return TraverseStmt(E->getExpr());
  5298. }
  5299. bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
  5300. return TraverseStmt(E->getExpr());
  5301. }
  5302. };
  5303. struct EnsureImmediateInvocationInDefaultArgs
  5304. : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
  5305. EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
  5306. : TreeTransform(SemaRef) {}
  5307. // Lambda can only have immediate invocations in the default
  5308. // args of their parameters, which is transformed upon calling the closure.
  5309. // The body is not a subexpression, so we have nothing to do.
  5310. // FIXME: Immediate calls in capture initializers should be transformed.
  5311. ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
  5312. ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
  5313. // Make sure we don't rebuild the this pointer as it would
  5314. // cause it to incorrectly point it to the outermost class
  5315. // in the case of nested struct initialization.
  5316. ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
  5317. };
  5318. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  5319. FunctionDecl *FD, ParmVarDecl *Param,
  5320. Expr *Init) {
  5321. assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
  5322. bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
  5323. std::optional<ExpressionEvaluationContextRecord::InitializationContext>
  5324. InitializationContext =
  5325. OutermostDeclarationWithDelayedImmediateInvocations();
  5326. if (!InitializationContext.has_value())
  5327. InitializationContext.emplace(CallLoc, Param, CurContext);
  5328. if (!Init && !Param->hasUnparsedDefaultArg()) {
  5329. // Mark that we are replacing a default argument first.
  5330. // If we are instantiating a template we won't have to
  5331. // retransform immediate calls.
  5332. EnterExpressionEvaluationContext EvalContext(
  5333. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  5334. if (Param->hasUninstantiatedDefaultArg()) {
  5335. if (InstantiateDefaultArgument(CallLoc, FD, Param))
  5336. return ExprError();
  5337. }
  5338. // CWG2631
  5339. // An immediate invocation that is not evaluated where it appears is
  5340. // evaluated and checked for whether it is a constant expression at the
  5341. // point where the enclosing initializer is used in a function call.
  5342. ImmediateCallVisitor V;
  5343. if (!NestedDefaultChecking)
  5344. V.TraverseDecl(Param);
  5345. if (V.HasImmediateCalls) {
  5346. ExprEvalContexts.back().DelayedDefaultInitializationContext = {
  5347. CallLoc, Param, CurContext};
  5348. EnsureImmediateInvocationInDefaultArgs Immediate(*this);
  5349. ExprResult Res = Immediate.TransformInitializer(Param->getInit(),
  5350. /*NotCopy=*/false);
  5351. if (Res.isInvalid())
  5352. return ExprError();
  5353. Res = ConvertParamDefaultArgument(Param, Res.get(),
  5354. Res.get()->getBeginLoc());
  5355. if (Res.isInvalid())
  5356. return ExprError();
  5357. Init = Res.get();
  5358. }
  5359. }
  5360. if (CheckCXXDefaultArgExpr(
  5361. CallLoc, FD, Param, Init,
  5362. /*SkipImmediateInvocations=*/NestedDefaultChecking))
  5363. return ExprError();
  5364. return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
  5365. Init, InitializationContext->Context);
  5366. }
  5367. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  5368. assert(Field->hasInClassInitializer());
  5369. // If we might have already tried and failed to instantiate, don't try again.
  5370. if (Field->isInvalidDecl())
  5371. return ExprError();
  5372. auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  5373. std::optional<ExpressionEvaluationContextRecord::InitializationContext>
  5374. InitializationContext =
  5375. OutermostDeclarationWithDelayedImmediateInvocations();
  5376. if (!InitializationContext.has_value())
  5377. InitializationContext.emplace(Loc, Field, CurContext);
  5378. Expr *Init = nullptr;
  5379. bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
  5380. EnterExpressionEvaluationContext EvalContext(
  5381. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
  5382. if (!Field->getInClassInitializer()) {
  5383. // Maybe we haven't instantiated the in-class initializer. Go check the
  5384. // pattern FieldDecl to see if it has one.
  5385. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  5386. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  5387. DeclContext::lookup_result Lookup =
  5388. ClassPattern->lookup(Field->getDeclName());
  5389. FieldDecl *Pattern = nullptr;
  5390. for (auto *L : Lookup) {
  5391. if ((Pattern = dyn_cast<FieldDecl>(L)))
  5392. break;
  5393. }
  5394. assert(Pattern && "We must have set the Pattern!");
  5395. if (!Pattern->hasInClassInitializer() ||
  5396. InstantiateInClassInitializer(Loc, Field, Pattern,
  5397. getTemplateInstantiationArgs(Field))) {
  5398. Field->setInvalidDecl();
  5399. return ExprError();
  5400. }
  5401. }
  5402. }
  5403. // CWG2631
  5404. // An immediate invocation that is not evaluated where it appears is
  5405. // evaluated and checked for whether it is a constant expression at the
  5406. // point where the enclosing initializer is used in a [...] a constructor
  5407. // definition, or an aggregate initialization.
  5408. ImmediateCallVisitor V;
  5409. if (!NestedDefaultChecking)
  5410. V.TraverseDecl(Field);
  5411. if (V.HasImmediateCalls) {
  5412. ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
  5413. CurContext};
  5414. ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
  5415. NestedDefaultChecking;
  5416. EnsureImmediateInvocationInDefaultArgs Immediate(*this);
  5417. ExprResult Res =
  5418. Immediate.TransformInitializer(Field->getInClassInitializer(),
  5419. /*CXXDirectInit=*/false);
  5420. if (!Res.isInvalid())
  5421. Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
  5422. if (Res.isInvalid()) {
  5423. Field->setInvalidDecl();
  5424. return ExprError();
  5425. }
  5426. Init = Res.get();
  5427. }
  5428. if (Field->getInClassInitializer()) {
  5429. Expr *E = Init ? Init : Field->getInClassInitializer();
  5430. if (!NestedDefaultChecking)
  5431. MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
  5432. // C++11 [class.base.init]p7:
  5433. // The initialization of each base and member constitutes a
  5434. // full-expression.
  5435. ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
  5436. if (Res.isInvalid()) {
  5437. Field->setInvalidDecl();
  5438. return ExprError();
  5439. }
  5440. Init = Res.get();
  5441. return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
  5442. Field, InitializationContext->Context,
  5443. Init);
  5444. }
  5445. // DR1351:
  5446. // If the brace-or-equal-initializer of a non-static data member
  5447. // invokes a defaulted default constructor of its class or of an
  5448. // enclosing class in a potentially evaluated subexpression, the
  5449. // program is ill-formed.
  5450. //
  5451. // This resolution is unworkable: the exception specification of the
  5452. // default constructor can be needed in an unevaluated context, in
  5453. // particular, in the operand of a noexcept-expression, and we can be
  5454. // unable to compute an exception specification for an enclosed class.
  5455. //
  5456. // Any attempt to resolve the exception specification of a defaulted default
  5457. // constructor before the initializer is lexically complete will ultimately
  5458. // come here at which point we can diagnose it.
  5459. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  5460. Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
  5461. << OutermostClass << Field;
  5462. Diag(Field->getEndLoc(),
  5463. diag::note_default_member_initializer_not_yet_parsed);
  5464. // Recover by marking the field invalid, unless we're in a SFINAE context.
  5465. if (!isSFINAEContext())
  5466. Field->setInvalidDecl();
  5467. return ExprError();
  5468. }
  5469. Sema::VariadicCallType
  5470. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  5471. Expr *Fn) {
  5472. if (Proto && Proto->isVariadic()) {
  5473. if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
  5474. return VariadicConstructor;
  5475. else if (Fn && Fn->getType()->isBlockPointerType())
  5476. return VariadicBlock;
  5477. else if (FDecl) {
  5478. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  5479. if (Method->isInstance())
  5480. return VariadicMethod;
  5481. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  5482. return VariadicMethod;
  5483. return VariadicFunction;
  5484. }
  5485. return VariadicDoesNotApply;
  5486. }
  5487. namespace {
  5488. class FunctionCallCCC final : public FunctionCallFilterCCC {
  5489. public:
  5490. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  5491. unsigned NumArgs, MemberExpr *ME)
  5492. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  5493. FunctionName(FuncName) {}
  5494. bool ValidateCandidate(const TypoCorrection &candidate) override {
  5495. if (!candidate.getCorrectionSpecifier() ||
  5496. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  5497. return false;
  5498. }
  5499. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  5500. }
  5501. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  5502. return std::make_unique<FunctionCallCCC>(*this);
  5503. }
  5504. private:
  5505. const IdentifierInfo *const FunctionName;
  5506. };
  5507. }
  5508. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  5509. FunctionDecl *FDecl,
  5510. ArrayRef<Expr *> Args) {
  5511. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  5512. DeclarationName FuncName = FDecl->getDeclName();
  5513. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
  5514. FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
  5515. if (TypoCorrection Corrected = S.CorrectTypo(
  5516. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  5517. S.getScopeForContext(S.CurContext), nullptr, CCC,
  5518. Sema::CTK_ErrorRecovery)) {
  5519. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  5520. if (Corrected.isOverloaded()) {
  5521. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  5522. OverloadCandidateSet::iterator Best;
  5523. for (NamedDecl *CD : Corrected) {
  5524. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  5525. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  5526. OCS);
  5527. }
  5528. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  5529. case OR_Success:
  5530. ND = Best->FoundDecl;
  5531. Corrected.setCorrectionDecl(ND);
  5532. break;
  5533. default:
  5534. break;
  5535. }
  5536. }
  5537. ND = ND->getUnderlyingDecl();
  5538. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  5539. return Corrected;
  5540. }
  5541. }
  5542. return TypoCorrection();
  5543. }
  5544. /// ConvertArgumentsForCall - Converts the arguments specified in
  5545. /// Args/NumArgs to the parameter types of the function FDecl with
  5546. /// function prototype Proto. Call is the call expression itself, and
  5547. /// Fn is the function expression. For a C++ member function, this
  5548. /// routine does not attempt to convert the object argument. Returns
  5549. /// true if the call is ill-formed.
  5550. bool
  5551. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  5552. FunctionDecl *FDecl,
  5553. const FunctionProtoType *Proto,
  5554. ArrayRef<Expr *> Args,
  5555. SourceLocation RParenLoc,
  5556. bool IsExecConfig) {
  5557. // Bail out early if calling a builtin with custom typechecking.
  5558. if (FDecl)
  5559. if (unsigned ID = FDecl->getBuiltinID())
  5560. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  5561. return false;
  5562. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  5563. // assignment, to the types of the corresponding parameter, ...
  5564. unsigned NumParams = Proto->getNumParams();
  5565. bool Invalid = false;
  5566. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  5567. unsigned FnKind = Fn->getType()->isBlockPointerType()
  5568. ? 1 /* block */
  5569. : (IsExecConfig ? 3 /* kernel function (exec config) */
  5570. : 0 /* function */);
  5571. // If too few arguments are available (and we don't have default
  5572. // arguments for the remaining parameters), don't make the call.
  5573. if (Args.size() < NumParams) {
  5574. if (Args.size() < MinArgs) {
  5575. TypoCorrection TC;
  5576. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  5577. unsigned diag_id =
  5578. MinArgs == NumParams && !Proto->isVariadic()
  5579. ? diag::err_typecheck_call_too_few_args_suggest
  5580. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  5581. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  5582. << static_cast<unsigned>(Args.size())
  5583. << TC.getCorrectionRange());
  5584. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  5585. Diag(RParenLoc,
  5586. MinArgs == NumParams && !Proto->isVariadic()
  5587. ? diag::err_typecheck_call_too_few_args_one
  5588. : diag::err_typecheck_call_too_few_args_at_least_one)
  5589. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  5590. else
  5591. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  5592. ? diag::err_typecheck_call_too_few_args
  5593. : diag::err_typecheck_call_too_few_args_at_least)
  5594. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  5595. << Fn->getSourceRange();
  5596. // Emit the location of the prototype.
  5597. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  5598. Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
  5599. return true;
  5600. }
  5601. // We reserve space for the default arguments when we create
  5602. // the call expression, before calling ConvertArgumentsForCall.
  5603. assert((Call->getNumArgs() == NumParams) &&
  5604. "We should have reserved space for the default arguments before!");
  5605. }
  5606. // If too many are passed and not variadic, error on the extras and drop
  5607. // them.
  5608. if (Args.size() > NumParams) {
  5609. if (!Proto->isVariadic()) {
  5610. TypoCorrection TC;
  5611. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  5612. unsigned diag_id =
  5613. MinArgs == NumParams && !Proto->isVariadic()
  5614. ? diag::err_typecheck_call_too_many_args_suggest
  5615. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  5616. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  5617. << static_cast<unsigned>(Args.size())
  5618. << TC.getCorrectionRange());
  5619. } else if (NumParams == 1 && FDecl &&
  5620. FDecl->getParamDecl(0)->getDeclName())
  5621. Diag(Args[NumParams]->getBeginLoc(),
  5622. MinArgs == NumParams
  5623. ? diag::err_typecheck_call_too_many_args_one
  5624. : diag::err_typecheck_call_too_many_args_at_most_one)
  5625. << FnKind << FDecl->getParamDecl(0)
  5626. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  5627. << SourceRange(Args[NumParams]->getBeginLoc(),
  5628. Args.back()->getEndLoc());
  5629. else
  5630. Diag(Args[NumParams]->getBeginLoc(),
  5631. MinArgs == NumParams
  5632. ? diag::err_typecheck_call_too_many_args
  5633. : diag::err_typecheck_call_too_many_args_at_most)
  5634. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  5635. << Fn->getSourceRange()
  5636. << SourceRange(Args[NumParams]->getBeginLoc(),
  5637. Args.back()->getEndLoc());
  5638. // Emit the location of the prototype.
  5639. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  5640. Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
  5641. // This deletes the extra arguments.
  5642. Call->shrinkNumArgs(NumParams);
  5643. return true;
  5644. }
  5645. }
  5646. SmallVector<Expr *, 8> AllArgs;
  5647. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  5648. Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
  5649. AllArgs, CallType);
  5650. if (Invalid)
  5651. return true;
  5652. unsigned TotalNumArgs = AllArgs.size();
  5653. for (unsigned i = 0; i < TotalNumArgs; ++i)
  5654. Call->setArg(i, AllArgs[i]);
  5655. Call->computeDependence();
  5656. return false;
  5657. }
  5658. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  5659. const FunctionProtoType *Proto,
  5660. unsigned FirstParam, ArrayRef<Expr *> Args,
  5661. SmallVectorImpl<Expr *> &AllArgs,
  5662. VariadicCallType CallType, bool AllowExplicit,
  5663. bool IsListInitialization) {
  5664. unsigned NumParams = Proto->getNumParams();
  5665. bool Invalid = false;
  5666. size_t ArgIx = 0;
  5667. // Continue to check argument types (even if we have too few/many args).
  5668. for (unsigned i = FirstParam; i < NumParams; i++) {
  5669. QualType ProtoArgType = Proto->getParamType(i);
  5670. Expr *Arg;
  5671. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  5672. if (ArgIx < Args.size()) {
  5673. Arg = Args[ArgIx++];
  5674. if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
  5675. diag::err_call_incomplete_argument, Arg))
  5676. return true;
  5677. // Strip the unbridged-cast placeholder expression off, if applicable.
  5678. bool CFAudited = false;
  5679. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  5680. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  5681. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  5682. Arg = stripARCUnbridgedCast(Arg);
  5683. else if (getLangOpts().ObjCAutoRefCount &&
  5684. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  5685. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  5686. CFAudited = true;
  5687. if (Proto->getExtParameterInfo(i).isNoEscape() &&
  5688. ProtoArgType->isBlockPointerType())
  5689. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  5690. BE->getBlockDecl()->setDoesNotEscape();
  5691. InitializedEntity Entity =
  5692. Param ? InitializedEntity::InitializeParameter(Context, Param,
  5693. ProtoArgType)
  5694. : InitializedEntity::InitializeParameter(
  5695. Context, ProtoArgType, Proto->isParamConsumed(i));
  5696. // Remember that parameter belongs to a CF audited API.
  5697. if (CFAudited)
  5698. Entity.setParameterCFAudited();
  5699. ExprResult ArgE = PerformCopyInitialization(
  5700. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  5701. if (ArgE.isInvalid())
  5702. return true;
  5703. Arg = ArgE.getAs<Expr>();
  5704. } else {
  5705. assert(Param && "can't use default arguments without a known callee");
  5706. ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  5707. if (ArgExpr.isInvalid())
  5708. return true;
  5709. Arg = ArgExpr.getAs<Expr>();
  5710. }
  5711. // Check for array bounds violations for each argument to the call. This
  5712. // check only triggers warnings when the argument isn't a more complex Expr
  5713. // with its own checking, such as a BinaryOperator.
  5714. CheckArrayAccess(Arg);
  5715. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  5716. CheckStaticArrayArgument(CallLoc, Param, Arg);
  5717. AllArgs.push_back(Arg);
  5718. }
  5719. // If this is a variadic call, handle args passed through "...".
  5720. if (CallType != VariadicDoesNotApply) {
  5721. // Assume that extern "C" functions with variadic arguments that
  5722. // return __unknown_anytype aren't *really* variadic.
  5723. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  5724. FDecl->isExternC()) {
  5725. for (Expr *A : Args.slice(ArgIx)) {
  5726. QualType paramType; // ignored
  5727. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  5728. Invalid |= arg.isInvalid();
  5729. AllArgs.push_back(arg.get());
  5730. }
  5731. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  5732. } else {
  5733. for (Expr *A : Args.slice(ArgIx)) {
  5734. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  5735. Invalid |= Arg.isInvalid();
  5736. AllArgs.push_back(Arg.get());
  5737. }
  5738. }
  5739. // Check for array bounds violations.
  5740. for (Expr *A : Args.slice(ArgIx))
  5741. CheckArrayAccess(A);
  5742. }
  5743. return Invalid;
  5744. }
  5745. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  5746. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  5747. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  5748. TL = DTL.getOriginalLoc();
  5749. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  5750. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  5751. << ATL.getLocalSourceRange();
  5752. }
  5753. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  5754. /// array parameter, check that it is non-null, and that if it is formed by
  5755. /// array-to-pointer decay, the underlying array is sufficiently large.
  5756. ///
  5757. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  5758. /// array type derivation, then for each call to the function, the value of the
  5759. /// corresponding actual argument shall provide access to the first element of
  5760. /// an array with at least as many elements as specified by the size expression.
  5761. void
  5762. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  5763. ParmVarDecl *Param,
  5764. const Expr *ArgExpr) {
  5765. // Static array parameters are not supported in C++.
  5766. if (!Param || getLangOpts().CPlusPlus)
  5767. return;
  5768. QualType OrigTy = Param->getOriginalType();
  5769. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  5770. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  5771. return;
  5772. if (ArgExpr->isNullPointerConstant(Context,
  5773. Expr::NPC_NeverValueDependent)) {
  5774. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  5775. DiagnoseCalleeStaticArrayParam(*this, Param);
  5776. return;
  5777. }
  5778. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  5779. if (!CAT)
  5780. return;
  5781. const ConstantArrayType *ArgCAT =
  5782. Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
  5783. if (!ArgCAT)
  5784. return;
  5785. if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
  5786. ArgCAT->getElementType())) {
  5787. if (ArgCAT->getSize().ult(CAT->getSize())) {
  5788. Diag(CallLoc, diag::warn_static_array_too_small)
  5789. << ArgExpr->getSourceRange()
  5790. << (unsigned)ArgCAT->getSize().getZExtValue()
  5791. << (unsigned)CAT->getSize().getZExtValue() << 0;
  5792. DiagnoseCalleeStaticArrayParam(*this, Param);
  5793. }
  5794. return;
  5795. }
  5796. std::optional<CharUnits> ArgSize =
  5797. getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
  5798. std::optional<CharUnits> ParmSize =
  5799. getASTContext().getTypeSizeInCharsIfKnown(CAT);
  5800. if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
  5801. Diag(CallLoc, diag::warn_static_array_too_small)
  5802. << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
  5803. << (unsigned)ParmSize->getQuantity() << 1;
  5804. DiagnoseCalleeStaticArrayParam(*this, Param);
  5805. }
  5806. }
  5807. /// Given a function expression of unknown-any type, try to rebuild it
  5808. /// to have a function type.
  5809. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  5810. /// Is the given type a placeholder that we need to lower out
  5811. /// immediately during argument processing?
  5812. static bool isPlaceholderToRemoveAsArg(QualType type) {
  5813. // Placeholders are never sugared.
  5814. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  5815. if (!placeholder) return false;
  5816. switch (placeholder->getKind()) {
  5817. // Ignore all the non-placeholder types.
  5818. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  5819. case BuiltinType::Id:
  5820. #include "clang/Basic/OpenCLImageTypes.def"
  5821. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  5822. case BuiltinType::Id:
  5823. #include "clang/Basic/OpenCLExtensionTypes.def"
  5824. // In practice we'll never use this, since all SVE types are sugared
  5825. // via TypedefTypes rather than exposed directly as BuiltinTypes.
  5826. #define SVE_TYPE(Name, Id, SingletonId) \
  5827. case BuiltinType::Id:
  5828. #include "clang/Basic/AArch64SVEACLETypes.def"
  5829. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  5830. case BuiltinType::Id:
  5831. #include "clang/Basic/PPCTypes.def"
  5832. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  5833. #include "clang/Basic/RISCVVTypes.def"
  5834. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  5835. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  5836. #include "clang/AST/BuiltinTypes.def"
  5837. return false;
  5838. // We cannot lower out overload sets; they might validly be resolved
  5839. // by the call machinery.
  5840. case BuiltinType::Overload:
  5841. return false;
  5842. // Unbridged casts in ARC can be handled in some call positions and
  5843. // should be left in place.
  5844. case BuiltinType::ARCUnbridgedCast:
  5845. return false;
  5846. // Pseudo-objects should be converted as soon as possible.
  5847. case BuiltinType::PseudoObject:
  5848. return true;
  5849. // The debugger mode could theoretically but currently does not try
  5850. // to resolve unknown-typed arguments based on known parameter types.
  5851. case BuiltinType::UnknownAny:
  5852. return true;
  5853. // These are always invalid as call arguments and should be reported.
  5854. case BuiltinType::BoundMember:
  5855. case BuiltinType::BuiltinFn:
  5856. case BuiltinType::IncompleteMatrixIdx:
  5857. case BuiltinType::OMPArraySection:
  5858. case BuiltinType::OMPArrayShaping:
  5859. case BuiltinType::OMPIterator:
  5860. return true;
  5861. }
  5862. llvm_unreachable("bad builtin type kind");
  5863. }
  5864. /// Check an argument list for placeholders that we won't try to
  5865. /// handle later.
  5866. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  5867. // Apply this processing to all the arguments at once instead of
  5868. // dying at the first failure.
  5869. bool hasInvalid = false;
  5870. for (size_t i = 0, e = args.size(); i != e; i++) {
  5871. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  5872. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  5873. if (result.isInvalid()) hasInvalid = true;
  5874. else args[i] = result.get();
  5875. }
  5876. }
  5877. return hasInvalid;
  5878. }
  5879. /// If a builtin function has a pointer argument with no explicit address
  5880. /// space, then it should be able to accept a pointer to any address
  5881. /// space as input. In order to do this, we need to replace the
  5882. /// standard builtin declaration with one that uses the same address space
  5883. /// as the call.
  5884. ///
  5885. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  5886. /// it does not contain any pointer arguments without
  5887. /// an address space qualifer. Otherwise the rewritten
  5888. /// FunctionDecl is returned.
  5889. /// TODO: Handle pointer return types.
  5890. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  5891. FunctionDecl *FDecl,
  5892. MultiExprArg ArgExprs) {
  5893. QualType DeclType = FDecl->getType();
  5894. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  5895. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
  5896. ArgExprs.size() < FT->getNumParams())
  5897. return nullptr;
  5898. bool NeedsNewDecl = false;
  5899. unsigned i = 0;
  5900. SmallVector<QualType, 8> OverloadParams;
  5901. for (QualType ParamType : FT->param_types()) {
  5902. // Convert array arguments to pointer to simplify type lookup.
  5903. ExprResult ArgRes =
  5904. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  5905. if (ArgRes.isInvalid())
  5906. return nullptr;
  5907. Expr *Arg = ArgRes.get();
  5908. QualType ArgType = Arg->getType();
  5909. if (!ParamType->isPointerType() ||
  5910. ParamType.hasAddressSpace() ||
  5911. !ArgType->isPointerType() ||
  5912. !ArgType->getPointeeType().hasAddressSpace()) {
  5913. OverloadParams.push_back(ParamType);
  5914. continue;
  5915. }
  5916. QualType PointeeType = ParamType->getPointeeType();
  5917. if (PointeeType.hasAddressSpace())
  5918. continue;
  5919. NeedsNewDecl = true;
  5920. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  5921. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  5922. OverloadParams.push_back(Context.getPointerType(PointeeType));
  5923. }
  5924. if (!NeedsNewDecl)
  5925. return nullptr;
  5926. FunctionProtoType::ExtProtoInfo EPI;
  5927. EPI.Variadic = FT->isVariadic();
  5928. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  5929. OverloadParams, EPI);
  5930. DeclContext *Parent = FDecl->getParent();
  5931. FunctionDecl *OverloadDecl = FunctionDecl::Create(
  5932. Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
  5933. FDecl->getIdentifier(), OverloadTy,
  5934. /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
  5935. false,
  5936. /*hasPrototype=*/true);
  5937. SmallVector<ParmVarDecl*, 16> Params;
  5938. FT = cast<FunctionProtoType>(OverloadTy);
  5939. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  5940. QualType ParamType = FT->getParamType(i);
  5941. ParmVarDecl *Parm =
  5942. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  5943. SourceLocation(), nullptr, ParamType,
  5944. /*TInfo=*/nullptr, SC_None, nullptr);
  5945. Parm->setScopeInfo(0, i);
  5946. Params.push_back(Parm);
  5947. }
  5948. OverloadDecl->setParams(Params);
  5949. Sema->mergeDeclAttributes(OverloadDecl, FDecl);
  5950. return OverloadDecl;
  5951. }
  5952. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  5953. FunctionDecl *Callee,
  5954. MultiExprArg ArgExprs) {
  5955. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  5956. // similar attributes) really don't like it when functions are called with an
  5957. // invalid number of args.
  5958. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  5959. /*PartialOverloading=*/false) &&
  5960. !Callee->isVariadic())
  5961. return;
  5962. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  5963. return;
  5964. if (const EnableIfAttr *Attr =
  5965. S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
  5966. S.Diag(Fn->getBeginLoc(),
  5967. isa<CXXMethodDecl>(Callee)
  5968. ? diag::err_ovl_no_viable_member_function_in_call
  5969. : diag::err_ovl_no_viable_function_in_call)
  5970. << Callee << Callee->getSourceRange();
  5971. S.Diag(Callee->getLocation(),
  5972. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  5973. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  5974. return;
  5975. }
  5976. }
  5977. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  5978. const UnresolvedMemberExpr *const UME, Sema &S) {
  5979. const auto GetFunctionLevelDCIfCXXClass =
  5980. [](Sema &S) -> const CXXRecordDecl * {
  5981. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  5982. if (!DC || !DC->getParent())
  5983. return nullptr;
  5984. // If the call to some member function was made from within a member
  5985. // function body 'M' return return 'M's parent.
  5986. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  5987. return MD->getParent()->getCanonicalDecl();
  5988. // else the call was made from within a default member initializer of a
  5989. // class, so return the class.
  5990. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  5991. return RD->getCanonicalDecl();
  5992. return nullptr;
  5993. };
  5994. // If our DeclContext is neither a member function nor a class (in the
  5995. // case of a lambda in a default member initializer), we can't have an
  5996. // enclosing 'this'.
  5997. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  5998. if (!CurParentClass)
  5999. return false;
  6000. // The naming class for implicit member functions call is the class in which
  6001. // name lookup starts.
  6002. const CXXRecordDecl *const NamingClass =
  6003. UME->getNamingClass()->getCanonicalDecl();
  6004. assert(NamingClass && "Must have naming class even for implicit access");
  6005. // If the unresolved member functions were found in a 'naming class' that is
  6006. // related (either the same or derived from) to the class that contains the
  6007. // member function that itself contained the implicit member access.
  6008. return CurParentClass == NamingClass ||
  6009. CurParentClass->isDerivedFrom(NamingClass);
  6010. }
  6011. static void
  6012. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  6013. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  6014. if (!UME)
  6015. return;
  6016. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  6017. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  6018. // already been captured, or if this is an implicit member function call (if
  6019. // it isn't, an attempt to capture 'this' should already have been made).
  6020. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  6021. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  6022. return;
  6023. // Check if the naming class in which the unresolved members were found is
  6024. // related (same as or is a base of) to the enclosing class.
  6025. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  6026. return;
  6027. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  6028. // If the enclosing function is not dependent, then this lambda is
  6029. // capture ready, so if we can capture this, do so.
  6030. if (!EnclosingFunctionCtx->isDependentContext()) {
  6031. // If the current lambda and all enclosing lambdas can capture 'this' -
  6032. // then go ahead and capture 'this' (since our unresolved overload set
  6033. // contains at least one non-static member function).
  6034. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  6035. S.CheckCXXThisCapture(CallLoc);
  6036. } else if (S.CurContext->isDependentContext()) {
  6037. // ... since this is an implicit member reference, that might potentially
  6038. // involve a 'this' capture, mark 'this' for potential capture in
  6039. // enclosing lambdas.
  6040. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  6041. CurLSI->addPotentialThisCapture(CallLoc);
  6042. }
  6043. }
  6044. // Once a call is fully resolved, warn for unqualified calls to specific
  6045. // C++ standard functions, like move and forward.
  6046. static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
  6047. // We are only checking unary move and forward so exit early here.
  6048. if (Call->getNumArgs() != 1)
  6049. return;
  6050. Expr *E = Call->getCallee()->IgnoreParenImpCasts();
  6051. if (!E || isa<UnresolvedLookupExpr>(E))
  6052. return;
  6053. DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
  6054. if (!DRE || !DRE->getLocation().isValid())
  6055. return;
  6056. if (DRE->getQualifier())
  6057. return;
  6058. const FunctionDecl *FD = Call->getDirectCallee();
  6059. if (!FD)
  6060. return;
  6061. // Only warn for some functions deemed more frequent or problematic.
  6062. unsigned BuiltinID = FD->getBuiltinID();
  6063. if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
  6064. return;
  6065. S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
  6066. << FD->getQualifiedNameAsString()
  6067. << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
  6068. }
  6069. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  6070. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  6071. Expr *ExecConfig) {
  6072. ExprResult Call =
  6073. BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  6074. /*IsExecConfig=*/false, /*AllowRecovery=*/true);
  6075. if (Call.isInvalid())
  6076. return Call;
  6077. // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
  6078. // language modes.
  6079. if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
  6080. if (ULE->hasExplicitTemplateArgs() &&
  6081. ULE->decls_begin() == ULE->decls_end()) {
  6082. Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
  6083. ? diag::warn_cxx17_compat_adl_only_template_id
  6084. : diag::ext_adl_only_template_id)
  6085. << ULE->getName();
  6086. }
  6087. }
  6088. if (LangOpts.OpenMP)
  6089. Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
  6090. ExecConfig);
  6091. if (LangOpts.CPlusPlus) {
  6092. CallExpr *CE = dyn_cast<CallExpr>(Call.get());
  6093. if (CE)
  6094. DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
  6095. }
  6096. return Call;
  6097. }
  6098. /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
  6099. /// This provides the location of the left/right parens and a list of comma
  6100. /// locations.
  6101. ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  6102. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  6103. Expr *ExecConfig, bool IsExecConfig,
  6104. bool AllowRecovery) {
  6105. // Since this might be a postfix expression, get rid of ParenListExprs.
  6106. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  6107. if (Result.isInvalid()) return ExprError();
  6108. Fn = Result.get();
  6109. if (checkArgsForPlaceholders(*this, ArgExprs))
  6110. return ExprError();
  6111. if (getLangOpts().CPlusPlus) {
  6112. // If this is a pseudo-destructor expression, build the call immediately.
  6113. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  6114. if (!ArgExprs.empty()) {
  6115. // Pseudo-destructor calls should not have any arguments.
  6116. Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
  6117. << FixItHint::CreateRemoval(
  6118. SourceRange(ArgExprs.front()->getBeginLoc(),
  6119. ArgExprs.back()->getEndLoc()));
  6120. }
  6121. return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
  6122. VK_PRValue, RParenLoc, CurFPFeatureOverrides());
  6123. }
  6124. if (Fn->getType() == Context.PseudoObjectTy) {
  6125. ExprResult result = CheckPlaceholderExpr(Fn);
  6126. if (result.isInvalid()) return ExprError();
  6127. Fn = result.get();
  6128. }
  6129. // Determine whether this is a dependent call inside a C++ template,
  6130. // in which case we won't do any semantic analysis now.
  6131. if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
  6132. if (ExecConfig) {
  6133. return CUDAKernelCallExpr::Create(Context, Fn,
  6134. cast<CallExpr>(ExecConfig), ArgExprs,
  6135. Context.DependentTy, VK_PRValue,
  6136. RParenLoc, CurFPFeatureOverrides());
  6137. } else {
  6138. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  6139. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  6140. Fn->getBeginLoc());
  6141. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  6142. VK_PRValue, RParenLoc, CurFPFeatureOverrides());
  6143. }
  6144. }
  6145. // Determine whether this is a call to an object (C++ [over.call.object]).
  6146. if (Fn->getType()->isRecordType())
  6147. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  6148. RParenLoc);
  6149. if (Fn->getType() == Context.UnknownAnyTy) {
  6150. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  6151. if (result.isInvalid()) return ExprError();
  6152. Fn = result.get();
  6153. }
  6154. if (Fn->getType() == Context.BoundMemberTy) {
  6155. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  6156. RParenLoc, ExecConfig, IsExecConfig,
  6157. AllowRecovery);
  6158. }
  6159. }
  6160. // Check for overloaded calls. This can happen even in C due to extensions.
  6161. if (Fn->getType() == Context.OverloadTy) {
  6162. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  6163. // We aren't supposed to apply this logic if there's an '&' involved.
  6164. if (!find.HasFormOfMemberPointer) {
  6165. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  6166. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  6167. VK_PRValue, RParenLoc, CurFPFeatureOverrides());
  6168. OverloadExpr *ovl = find.Expression;
  6169. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  6170. return BuildOverloadedCallExpr(
  6171. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  6172. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  6173. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  6174. RParenLoc, ExecConfig, IsExecConfig,
  6175. AllowRecovery);
  6176. }
  6177. }
  6178. // If we're directly calling a function, get the appropriate declaration.
  6179. if (Fn->getType() == Context.UnknownAnyTy) {
  6180. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  6181. if (result.isInvalid()) return ExprError();
  6182. Fn = result.get();
  6183. }
  6184. Expr *NakedFn = Fn->IgnoreParens();
  6185. bool CallingNDeclIndirectly = false;
  6186. NamedDecl *NDecl = nullptr;
  6187. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  6188. if (UnOp->getOpcode() == UO_AddrOf) {
  6189. CallingNDeclIndirectly = true;
  6190. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  6191. }
  6192. }
  6193. if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
  6194. NDecl = DRE->getDecl();
  6195. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  6196. if (FDecl && FDecl->getBuiltinID()) {
  6197. // Rewrite the function decl for this builtin by replacing parameters
  6198. // with no explicit address space with the address space of the arguments
  6199. // in ArgExprs.
  6200. if ((FDecl =
  6201. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  6202. NDecl = FDecl;
  6203. Fn = DeclRefExpr::Create(
  6204. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  6205. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
  6206. nullptr, DRE->isNonOdrUse());
  6207. }
  6208. }
  6209. } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
  6210. NDecl = ME->getMemberDecl();
  6211. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  6212. if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
  6213. FD, /*Complain=*/true, Fn->getBeginLoc()))
  6214. return ExprError();
  6215. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  6216. // If this expression is a call to a builtin function in HIP device
  6217. // compilation, allow a pointer-type argument to default address space to be
  6218. // passed as a pointer-type parameter to a non-default address space.
  6219. // If Arg is declared in the default address space and Param is declared
  6220. // in a non-default address space, perform an implicit address space cast to
  6221. // the parameter type.
  6222. if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
  6223. FD->getBuiltinID()) {
  6224. for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
  6225. ParmVarDecl *Param = FD->getParamDecl(Idx);
  6226. if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
  6227. !ArgExprs[Idx]->getType()->isPointerType())
  6228. continue;
  6229. auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
  6230. auto ArgTy = ArgExprs[Idx]->getType();
  6231. auto ArgPtTy = ArgTy->getPointeeType();
  6232. auto ArgAS = ArgPtTy.getAddressSpace();
  6233. // Add address space cast if target address spaces are different
  6234. bool NeedImplicitASC =
  6235. ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
  6236. ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
  6237. // or from specific AS which has target AS matching that of Param.
  6238. getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
  6239. if (!NeedImplicitASC)
  6240. continue;
  6241. // First, ensure that the Arg is an RValue.
  6242. if (ArgExprs[Idx]->isGLValue()) {
  6243. ArgExprs[Idx] = ImplicitCastExpr::Create(
  6244. Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
  6245. nullptr, VK_PRValue, FPOptionsOverride());
  6246. }
  6247. // Construct a new arg type with address space of Param
  6248. Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
  6249. ArgPtQuals.setAddressSpace(ParamAS);
  6250. auto NewArgPtTy =
  6251. Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
  6252. auto NewArgTy =
  6253. Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
  6254. ArgTy.getQualifiers());
  6255. // Finally perform an implicit address space cast
  6256. ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
  6257. CK_AddressSpaceConversion)
  6258. .get();
  6259. }
  6260. }
  6261. }
  6262. if (Context.isDependenceAllowed() &&
  6263. (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
  6264. assert(!getLangOpts().CPlusPlus);
  6265. assert((Fn->containsErrors() ||
  6266. llvm::any_of(ArgExprs,
  6267. [](clang::Expr *E) { return E->containsErrors(); })) &&
  6268. "should only occur in error-recovery path.");
  6269. QualType ReturnType =
  6270. llvm::isa_and_nonnull<FunctionDecl>(NDecl)
  6271. ? cast<FunctionDecl>(NDecl)->getCallResultType()
  6272. : Context.DependentTy;
  6273. return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
  6274. Expr::getValueKindForType(ReturnType), RParenLoc,
  6275. CurFPFeatureOverrides());
  6276. }
  6277. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  6278. ExecConfig, IsExecConfig);
  6279. }
  6280. /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
  6281. // with the specified CallArgs
  6282. Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
  6283. MultiExprArg CallArgs) {
  6284. StringRef Name = Context.BuiltinInfo.getName(Id);
  6285. LookupResult R(*this, &Context.Idents.get(Name), Loc,
  6286. Sema::LookupOrdinaryName);
  6287. LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
  6288. auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
  6289. assert(BuiltInDecl && "failed to find builtin declaration");
  6290. ExprResult DeclRef =
  6291. BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
  6292. assert(DeclRef.isUsable() && "Builtin reference cannot fail");
  6293. ExprResult Call =
  6294. BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
  6295. assert(!Call.isInvalid() && "Call to builtin cannot fail!");
  6296. return Call.get();
  6297. }
  6298. /// Parse a __builtin_astype expression.
  6299. ///
  6300. /// __builtin_astype( value, dst type )
  6301. ///
  6302. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  6303. SourceLocation BuiltinLoc,
  6304. SourceLocation RParenLoc) {
  6305. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  6306. return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
  6307. }
  6308. /// Create a new AsTypeExpr node (bitcast) from the arguments.
  6309. ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
  6310. SourceLocation BuiltinLoc,
  6311. SourceLocation RParenLoc) {
  6312. ExprValueKind VK = VK_PRValue;
  6313. ExprObjectKind OK = OK_Ordinary;
  6314. QualType SrcTy = E->getType();
  6315. if (!SrcTy->isDependentType() &&
  6316. Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
  6317. return ExprError(
  6318. Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
  6319. << DestTy << SrcTy << E->getSourceRange());
  6320. return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
  6321. }
  6322. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  6323. /// provided arguments.
  6324. ///
  6325. /// __builtin_convertvector( value, dst type )
  6326. ///
  6327. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  6328. SourceLocation BuiltinLoc,
  6329. SourceLocation RParenLoc) {
  6330. TypeSourceInfo *TInfo;
  6331. GetTypeFromParser(ParsedDestTy, &TInfo);
  6332. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  6333. }
  6334. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  6335. /// i.e. an expression not of \p OverloadTy. The expression should
  6336. /// unary-convert to an expression of function-pointer or
  6337. /// block-pointer type.
  6338. ///
  6339. /// \param NDecl the declaration being called, if available
  6340. ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  6341. SourceLocation LParenLoc,
  6342. ArrayRef<Expr *> Args,
  6343. SourceLocation RParenLoc, Expr *Config,
  6344. bool IsExecConfig, ADLCallKind UsesADL) {
  6345. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  6346. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  6347. // Functions with 'interrupt' attribute cannot be called directly.
  6348. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  6349. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  6350. return ExprError();
  6351. }
  6352. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  6353. // so there's some risk when calling out to non-interrupt handler functions
  6354. // that the callee might not preserve them. This is easy to diagnose here,
  6355. // but can be very challenging to debug.
  6356. // Likewise, X86 interrupt handlers may only call routines with attribute
  6357. // no_caller_saved_registers since there is no efficient way to
  6358. // save and restore the non-GPR state.
  6359. if (auto *Caller = getCurFunctionDecl()) {
  6360. if (Caller->hasAttr<ARMInterruptAttr>()) {
  6361. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  6362. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
  6363. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  6364. if (FDecl)
  6365. Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
  6366. }
  6367. }
  6368. if (Caller->hasAttr<AnyX86InterruptAttr>() &&
  6369. ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
  6370. Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
  6371. if (FDecl)
  6372. Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
  6373. }
  6374. }
  6375. // Promote the function operand.
  6376. // We special-case function promotion here because we only allow promoting
  6377. // builtin functions to function pointers in the callee of a call.
  6378. ExprResult Result;
  6379. QualType ResultTy;
  6380. if (BuiltinID &&
  6381. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  6382. // Extract the return type from the (builtin) function pointer type.
  6383. // FIXME Several builtins still have setType in
  6384. // Sema::CheckBuiltinFunctionCall. One should review their definitions in
  6385. // Builtins.def to ensure they are correct before removing setType calls.
  6386. QualType FnPtrTy = Context.getPointerType(FDecl->getType());
  6387. Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
  6388. ResultTy = FDecl->getCallResultType();
  6389. } else {
  6390. Result = CallExprUnaryConversions(Fn);
  6391. ResultTy = Context.BoolTy;
  6392. }
  6393. if (Result.isInvalid())
  6394. return ExprError();
  6395. Fn = Result.get();
  6396. // Check for a valid function type, but only if it is not a builtin which
  6397. // requires custom type checking. These will be handled by
  6398. // CheckBuiltinFunctionCall below just after creation of the call expression.
  6399. const FunctionType *FuncT = nullptr;
  6400. if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
  6401. retry:
  6402. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  6403. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  6404. // have type pointer to function".
  6405. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  6406. if (!FuncT)
  6407. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  6408. << Fn->getType() << Fn->getSourceRange());
  6409. } else if (const BlockPointerType *BPT =
  6410. Fn->getType()->getAs<BlockPointerType>()) {
  6411. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  6412. } else {
  6413. // Handle calls to expressions of unknown-any type.
  6414. if (Fn->getType() == Context.UnknownAnyTy) {
  6415. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  6416. if (rewrite.isInvalid())
  6417. return ExprError();
  6418. Fn = rewrite.get();
  6419. goto retry;
  6420. }
  6421. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  6422. << Fn->getType() << Fn->getSourceRange());
  6423. }
  6424. }
  6425. // Get the number of parameters in the function prototype, if any.
  6426. // We will allocate space for max(Args.size(), NumParams) arguments
  6427. // in the call expression.
  6428. const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
  6429. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  6430. CallExpr *TheCall;
  6431. if (Config) {
  6432. assert(UsesADL == ADLCallKind::NotADL &&
  6433. "CUDAKernelCallExpr should not use ADL");
  6434. TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
  6435. Args, ResultTy, VK_PRValue, RParenLoc,
  6436. CurFPFeatureOverrides(), NumParams);
  6437. } else {
  6438. TheCall =
  6439. CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
  6440. CurFPFeatureOverrides(), NumParams, UsesADL);
  6441. }
  6442. if (!Context.isDependenceAllowed()) {
  6443. // Forget about the nulled arguments since typo correction
  6444. // do not handle them well.
  6445. TheCall->shrinkNumArgs(Args.size());
  6446. // C cannot always handle TypoExpr nodes in builtin calls and direct
  6447. // function calls as their argument checking don't necessarily handle
  6448. // dependent types properly, so make sure any TypoExprs have been
  6449. // dealt with.
  6450. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  6451. if (!Result.isUsable()) return ExprError();
  6452. CallExpr *TheOldCall = TheCall;
  6453. TheCall = dyn_cast<CallExpr>(Result.get());
  6454. bool CorrectedTypos = TheCall != TheOldCall;
  6455. if (!TheCall) return Result;
  6456. Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  6457. // A new call expression node was created if some typos were corrected.
  6458. // However it may not have been constructed with enough storage. In this
  6459. // case, rebuild the node with enough storage. The waste of space is
  6460. // immaterial since this only happens when some typos were corrected.
  6461. if (CorrectedTypos && Args.size() < NumParams) {
  6462. if (Config)
  6463. TheCall = CUDAKernelCallExpr::Create(
  6464. Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
  6465. RParenLoc, CurFPFeatureOverrides(), NumParams);
  6466. else
  6467. TheCall =
  6468. CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
  6469. CurFPFeatureOverrides(), NumParams, UsesADL);
  6470. }
  6471. // We can now handle the nulled arguments for the default arguments.
  6472. TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
  6473. }
  6474. // Bail out early if calling a builtin with custom type checking.
  6475. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  6476. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  6477. if (getLangOpts().CUDA) {
  6478. if (Config) {
  6479. // CUDA: Kernel calls must be to global functions
  6480. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  6481. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  6482. << FDecl << Fn->getSourceRange());
  6483. // CUDA: Kernel function must have 'void' return type
  6484. if (!FuncT->getReturnType()->isVoidType() &&
  6485. !FuncT->getReturnType()->getAs<AutoType>() &&
  6486. !FuncT->getReturnType()->isInstantiationDependentType())
  6487. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  6488. << Fn->getType() << Fn->getSourceRange());
  6489. } else {
  6490. // CUDA: Calls to global functions must be configured
  6491. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  6492. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  6493. << FDecl << Fn->getSourceRange());
  6494. }
  6495. }
  6496. // Check for a valid return type
  6497. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
  6498. FDecl))
  6499. return ExprError();
  6500. // We know the result type of the call, set it.
  6501. TheCall->setType(FuncT->getCallResultType(Context));
  6502. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  6503. if (Proto) {
  6504. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  6505. IsExecConfig))
  6506. return ExprError();
  6507. } else {
  6508. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  6509. if (FDecl) {
  6510. // Check if we have too few/too many template arguments, based
  6511. // on our knowledge of the function definition.
  6512. const FunctionDecl *Def = nullptr;
  6513. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  6514. Proto = Def->getType()->getAs<FunctionProtoType>();
  6515. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  6516. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  6517. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  6518. }
  6519. // If the function we're calling isn't a function prototype, but we have
  6520. // a function prototype from a prior declaratiom, use that prototype.
  6521. if (!FDecl->hasPrototype())
  6522. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  6523. }
  6524. // If we still haven't found a prototype to use but there are arguments to
  6525. // the call, diagnose this as calling a function without a prototype.
  6526. // However, if we found a function declaration, check to see if
  6527. // -Wdeprecated-non-prototype was disabled where the function was declared.
  6528. // If so, we will silence the diagnostic here on the assumption that this
  6529. // interface is intentional and the user knows what they're doing. We will
  6530. // also silence the diagnostic if there is a function declaration but it
  6531. // was implicitly defined (the user already gets diagnostics about the
  6532. // creation of the implicit function declaration, so the additional warning
  6533. // is not helpful).
  6534. if (!Proto && !Args.empty() &&
  6535. (!FDecl || (!FDecl->isImplicit() &&
  6536. !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
  6537. FDecl->getLocation()))))
  6538. Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
  6539. << (FDecl != nullptr) << FDecl;
  6540. // Promote the arguments (C99 6.5.2.2p6).
  6541. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  6542. Expr *Arg = Args[i];
  6543. if (Proto && i < Proto->getNumParams()) {
  6544. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  6545. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  6546. ExprResult ArgE =
  6547. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  6548. if (ArgE.isInvalid())
  6549. return true;
  6550. Arg = ArgE.getAs<Expr>();
  6551. } else {
  6552. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  6553. if (ArgE.isInvalid())
  6554. return true;
  6555. Arg = ArgE.getAs<Expr>();
  6556. }
  6557. if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
  6558. diag::err_call_incomplete_argument, Arg))
  6559. return ExprError();
  6560. TheCall->setArg(i, Arg);
  6561. }
  6562. TheCall->computeDependence();
  6563. }
  6564. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  6565. if (!Method->isStatic())
  6566. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  6567. << Fn->getSourceRange());
  6568. // Check for sentinels
  6569. if (NDecl)
  6570. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  6571. // Warn for unions passing across security boundary (CMSE).
  6572. if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
  6573. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  6574. if (const auto *RT =
  6575. dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
  6576. if (RT->getDecl()->isOrContainsUnion())
  6577. Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
  6578. << 0 << i;
  6579. }
  6580. }
  6581. }
  6582. // Do special checking on direct calls to functions.
  6583. if (FDecl) {
  6584. if (CheckFunctionCall(FDecl, TheCall, Proto))
  6585. return ExprError();
  6586. checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
  6587. if (BuiltinID)
  6588. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  6589. } else if (NDecl) {
  6590. if (CheckPointerCall(NDecl, TheCall, Proto))
  6591. return ExprError();
  6592. } else {
  6593. if (CheckOtherCall(TheCall, Proto))
  6594. return ExprError();
  6595. }
  6596. return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
  6597. }
  6598. ExprResult
  6599. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  6600. SourceLocation RParenLoc, Expr *InitExpr) {
  6601. assert(Ty && "ActOnCompoundLiteral(): missing type");
  6602. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  6603. TypeSourceInfo *TInfo;
  6604. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  6605. if (!TInfo)
  6606. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  6607. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  6608. }
  6609. ExprResult
  6610. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  6611. SourceLocation RParenLoc, Expr *LiteralExpr) {
  6612. QualType literalType = TInfo->getType();
  6613. if (literalType->isArrayType()) {
  6614. if (RequireCompleteSizedType(
  6615. LParenLoc, Context.getBaseElementType(literalType),
  6616. diag::err_array_incomplete_or_sizeless_type,
  6617. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  6618. return ExprError();
  6619. if (literalType->isVariableArrayType()) {
  6620. if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
  6621. diag::err_variable_object_no_init)) {
  6622. return ExprError();
  6623. }
  6624. }
  6625. } else if (!literalType->isDependentType() &&
  6626. RequireCompleteType(LParenLoc, literalType,
  6627. diag::err_typecheck_decl_incomplete_type,
  6628. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  6629. return ExprError();
  6630. InitializedEntity Entity
  6631. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  6632. InitializationKind Kind
  6633. = InitializationKind::CreateCStyleCast(LParenLoc,
  6634. SourceRange(LParenLoc, RParenLoc),
  6635. /*InitList=*/true);
  6636. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  6637. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  6638. &literalType);
  6639. if (Result.isInvalid())
  6640. return ExprError();
  6641. LiteralExpr = Result.get();
  6642. bool isFileScope = !CurContext->isFunctionOrMethod();
  6643. // In C, compound literals are l-values for some reason.
  6644. // For GCC compatibility, in C++, file-scope array compound literals with
  6645. // constant initializers are also l-values, and compound literals are
  6646. // otherwise prvalues.
  6647. //
  6648. // (GCC also treats C++ list-initialized file-scope array prvalues with
  6649. // constant initializers as l-values, but that's non-conforming, so we don't
  6650. // follow it there.)
  6651. //
  6652. // FIXME: It would be better to handle the lvalue cases as materializing and
  6653. // lifetime-extending a temporary object, but our materialized temporaries
  6654. // representation only supports lifetime extension from a variable, not "out
  6655. // of thin air".
  6656. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  6657. // is bound to the result of applying array-to-pointer decay to the compound
  6658. // literal.
  6659. // FIXME: GCC supports compound literals of reference type, which should
  6660. // obviously have a value kind derived from the kind of reference involved.
  6661. ExprValueKind VK =
  6662. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  6663. ? VK_PRValue
  6664. : VK_LValue;
  6665. if (isFileScope)
  6666. if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
  6667. for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
  6668. Expr *Init = ILE->getInit(i);
  6669. ILE->setInit(i, ConstantExpr::Create(Context, Init));
  6670. }
  6671. auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  6672. VK, LiteralExpr, isFileScope);
  6673. if (isFileScope) {
  6674. if (!LiteralExpr->isTypeDependent() &&
  6675. !LiteralExpr->isValueDependent() &&
  6676. !literalType->isDependentType()) // C99 6.5.2.5p3
  6677. if (CheckForConstantInitializer(LiteralExpr, literalType))
  6678. return ExprError();
  6679. } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  6680. literalType.getAddressSpace() != LangAS::Default) {
  6681. // Embedded-C extensions to C99 6.5.2.5:
  6682. // "If the compound literal occurs inside the body of a function, the
  6683. // type name shall not be qualified by an address-space qualifier."
  6684. Diag(LParenLoc, diag::err_compound_literal_with_address_space)
  6685. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
  6686. return ExprError();
  6687. }
  6688. if (!isFileScope && !getLangOpts().CPlusPlus) {
  6689. // Compound literals that have automatic storage duration are destroyed at
  6690. // the end of the scope in C; in C++, they're just temporaries.
  6691. // Emit diagnostics if it is or contains a C union type that is non-trivial
  6692. // to destruct.
  6693. if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
  6694. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  6695. NTCUC_CompoundLiteral, NTCUK_Destruct);
  6696. // Diagnose jumps that enter or exit the lifetime of the compound literal.
  6697. if (literalType.isDestructedType()) {
  6698. Cleanup.setExprNeedsCleanups(true);
  6699. ExprCleanupObjects.push_back(E);
  6700. getCurFunction()->setHasBranchProtectedScope();
  6701. }
  6702. }
  6703. if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  6704. E->getType().hasNonTrivialToPrimitiveCopyCUnion())
  6705. checkNonTrivialCUnionInInitializer(E->getInitializer(),
  6706. E->getInitializer()->getExprLoc());
  6707. return MaybeBindToTemporary(E);
  6708. }
  6709. ExprResult
  6710. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  6711. SourceLocation RBraceLoc) {
  6712. // Only produce each kind of designated initialization diagnostic once.
  6713. SourceLocation FirstDesignator;
  6714. bool DiagnosedArrayDesignator = false;
  6715. bool DiagnosedNestedDesignator = false;
  6716. bool DiagnosedMixedDesignator = false;
  6717. // Check that any designated initializers are syntactically valid in the
  6718. // current language mode.
  6719. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  6720. if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
  6721. if (FirstDesignator.isInvalid())
  6722. FirstDesignator = DIE->getBeginLoc();
  6723. if (!getLangOpts().CPlusPlus)
  6724. break;
  6725. if (!DiagnosedNestedDesignator && DIE->size() > 1) {
  6726. DiagnosedNestedDesignator = true;
  6727. Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
  6728. << DIE->getDesignatorsSourceRange();
  6729. }
  6730. for (auto &Desig : DIE->designators()) {
  6731. if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
  6732. DiagnosedArrayDesignator = true;
  6733. Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
  6734. << Desig.getSourceRange();
  6735. }
  6736. }
  6737. if (!DiagnosedMixedDesignator &&
  6738. !isa<DesignatedInitExpr>(InitArgList[0])) {
  6739. DiagnosedMixedDesignator = true;
  6740. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  6741. << DIE->getSourceRange();
  6742. Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
  6743. << InitArgList[0]->getSourceRange();
  6744. }
  6745. } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
  6746. isa<DesignatedInitExpr>(InitArgList[0])) {
  6747. DiagnosedMixedDesignator = true;
  6748. auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
  6749. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  6750. << DIE->getSourceRange();
  6751. Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
  6752. << InitArgList[I]->getSourceRange();
  6753. }
  6754. }
  6755. if (FirstDesignator.isValid()) {
  6756. // Only diagnose designated initiaization as a C++20 extension if we didn't
  6757. // already diagnose use of (non-C++20) C99 designator syntax.
  6758. if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
  6759. !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
  6760. Diag(FirstDesignator, getLangOpts().CPlusPlus20
  6761. ? diag::warn_cxx17_compat_designated_init
  6762. : diag::ext_cxx_designated_init);
  6763. } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
  6764. Diag(FirstDesignator, diag::ext_designated_init);
  6765. }
  6766. }
  6767. return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
  6768. }
  6769. ExprResult
  6770. Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  6771. SourceLocation RBraceLoc) {
  6772. // Semantic analysis for initializers is done by ActOnDeclarator() and
  6773. // CheckInitializer() - it requires knowledge of the object being initialized.
  6774. // Immediately handle non-overload placeholders. Overloads can be
  6775. // resolved contextually, but everything else here can't.
  6776. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  6777. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  6778. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  6779. // Ignore failures; dropping the entire initializer list because
  6780. // of one failure would be terrible for indexing/etc.
  6781. if (result.isInvalid()) continue;
  6782. InitArgList[I] = result.get();
  6783. }
  6784. }
  6785. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  6786. RBraceLoc);
  6787. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  6788. return E;
  6789. }
  6790. /// Do an explicit extend of the given block pointer if we're in ARC.
  6791. void Sema::maybeExtendBlockObject(ExprResult &E) {
  6792. assert(E.get()->getType()->isBlockPointerType());
  6793. assert(E.get()->isPRValue());
  6794. // Only do this in an r-value context.
  6795. if (!getLangOpts().ObjCAutoRefCount) return;
  6796. E = ImplicitCastExpr::Create(
  6797. Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
  6798. /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
  6799. Cleanup.setExprNeedsCleanups(true);
  6800. }
  6801. /// Prepare a conversion of the given expression to an ObjC object
  6802. /// pointer type.
  6803. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  6804. QualType type = E.get()->getType();
  6805. if (type->isObjCObjectPointerType()) {
  6806. return CK_BitCast;
  6807. } else if (type->isBlockPointerType()) {
  6808. maybeExtendBlockObject(E);
  6809. return CK_BlockPointerToObjCPointerCast;
  6810. } else {
  6811. assert(type->isPointerType());
  6812. return CK_CPointerToObjCPointerCast;
  6813. }
  6814. }
  6815. /// Prepares for a scalar cast, performing all the necessary stages
  6816. /// except the final cast and returning the kind required.
  6817. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  6818. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  6819. // Also, callers should have filtered out the invalid cases with
  6820. // pointers. Everything else should be possible.
  6821. QualType SrcTy = Src.get()->getType();
  6822. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  6823. return CK_NoOp;
  6824. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  6825. case Type::STK_MemberPointer:
  6826. llvm_unreachable("member pointer type in C");
  6827. case Type::STK_CPointer:
  6828. case Type::STK_BlockPointer:
  6829. case Type::STK_ObjCObjectPointer:
  6830. switch (DestTy->getScalarTypeKind()) {
  6831. case Type::STK_CPointer: {
  6832. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  6833. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  6834. if (SrcAS != DestAS)
  6835. return CK_AddressSpaceConversion;
  6836. if (Context.hasCvrSimilarType(SrcTy, DestTy))
  6837. return CK_NoOp;
  6838. return CK_BitCast;
  6839. }
  6840. case Type::STK_BlockPointer:
  6841. return (SrcKind == Type::STK_BlockPointer
  6842. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  6843. case Type::STK_ObjCObjectPointer:
  6844. if (SrcKind == Type::STK_ObjCObjectPointer)
  6845. return CK_BitCast;
  6846. if (SrcKind == Type::STK_CPointer)
  6847. return CK_CPointerToObjCPointerCast;
  6848. maybeExtendBlockObject(Src);
  6849. return CK_BlockPointerToObjCPointerCast;
  6850. case Type::STK_Bool:
  6851. return CK_PointerToBoolean;
  6852. case Type::STK_Integral:
  6853. return CK_PointerToIntegral;
  6854. case Type::STK_Floating:
  6855. case Type::STK_FloatingComplex:
  6856. case Type::STK_IntegralComplex:
  6857. case Type::STK_MemberPointer:
  6858. case Type::STK_FixedPoint:
  6859. llvm_unreachable("illegal cast from pointer");
  6860. }
  6861. llvm_unreachable("Should have returned before this");
  6862. case Type::STK_FixedPoint:
  6863. switch (DestTy->getScalarTypeKind()) {
  6864. case Type::STK_FixedPoint:
  6865. return CK_FixedPointCast;
  6866. case Type::STK_Bool:
  6867. return CK_FixedPointToBoolean;
  6868. case Type::STK_Integral:
  6869. return CK_FixedPointToIntegral;
  6870. case Type::STK_Floating:
  6871. return CK_FixedPointToFloating;
  6872. case Type::STK_IntegralComplex:
  6873. case Type::STK_FloatingComplex:
  6874. Diag(Src.get()->getExprLoc(),
  6875. diag::err_unimplemented_conversion_with_fixed_point_type)
  6876. << DestTy;
  6877. return CK_IntegralCast;
  6878. case Type::STK_CPointer:
  6879. case Type::STK_ObjCObjectPointer:
  6880. case Type::STK_BlockPointer:
  6881. case Type::STK_MemberPointer:
  6882. llvm_unreachable("illegal cast to pointer type");
  6883. }
  6884. llvm_unreachable("Should have returned before this");
  6885. case Type::STK_Bool: // casting from bool is like casting from an integer
  6886. case Type::STK_Integral:
  6887. switch (DestTy->getScalarTypeKind()) {
  6888. case Type::STK_CPointer:
  6889. case Type::STK_ObjCObjectPointer:
  6890. case Type::STK_BlockPointer:
  6891. if (Src.get()->isNullPointerConstant(Context,
  6892. Expr::NPC_ValueDependentIsNull))
  6893. return CK_NullToPointer;
  6894. return CK_IntegralToPointer;
  6895. case Type::STK_Bool:
  6896. return CK_IntegralToBoolean;
  6897. case Type::STK_Integral:
  6898. return CK_IntegralCast;
  6899. case Type::STK_Floating:
  6900. return CK_IntegralToFloating;
  6901. case Type::STK_IntegralComplex:
  6902. Src = ImpCastExprToType(Src.get(),
  6903. DestTy->castAs<ComplexType>()->getElementType(),
  6904. CK_IntegralCast);
  6905. return CK_IntegralRealToComplex;
  6906. case Type::STK_FloatingComplex:
  6907. Src = ImpCastExprToType(Src.get(),
  6908. DestTy->castAs<ComplexType>()->getElementType(),
  6909. CK_IntegralToFloating);
  6910. return CK_FloatingRealToComplex;
  6911. case Type::STK_MemberPointer:
  6912. llvm_unreachable("member pointer type in C");
  6913. case Type::STK_FixedPoint:
  6914. return CK_IntegralToFixedPoint;
  6915. }
  6916. llvm_unreachable("Should have returned before this");
  6917. case Type::STK_Floating:
  6918. switch (DestTy->getScalarTypeKind()) {
  6919. case Type::STK_Floating:
  6920. return CK_FloatingCast;
  6921. case Type::STK_Bool:
  6922. return CK_FloatingToBoolean;
  6923. case Type::STK_Integral:
  6924. return CK_FloatingToIntegral;
  6925. case Type::STK_FloatingComplex:
  6926. Src = ImpCastExprToType(Src.get(),
  6927. DestTy->castAs<ComplexType>()->getElementType(),
  6928. CK_FloatingCast);
  6929. return CK_FloatingRealToComplex;
  6930. case Type::STK_IntegralComplex:
  6931. Src = ImpCastExprToType(Src.get(),
  6932. DestTy->castAs<ComplexType>()->getElementType(),
  6933. CK_FloatingToIntegral);
  6934. return CK_IntegralRealToComplex;
  6935. case Type::STK_CPointer:
  6936. case Type::STK_ObjCObjectPointer:
  6937. case Type::STK_BlockPointer:
  6938. llvm_unreachable("valid float->pointer cast?");
  6939. case Type::STK_MemberPointer:
  6940. llvm_unreachable("member pointer type in C");
  6941. case Type::STK_FixedPoint:
  6942. return CK_FloatingToFixedPoint;
  6943. }
  6944. llvm_unreachable("Should have returned before this");
  6945. case Type::STK_FloatingComplex:
  6946. switch (DestTy->getScalarTypeKind()) {
  6947. case Type::STK_FloatingComplex:
  6948. return CK_FloatingComplexCast;
  6949. case Type::STK_IntegralComplex:
  6950. return CK_FloatingComplexToIntegralComplex;
  6951. case Type::STK_Floating: {
  6952. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  6953. if (Context.hasSameType(ET, DestTy))
  6954. return CK_FloatingComplexToReal;
  6955. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  6956. return CK_FloatingCast;
  6957. }
  6958. case Type::STK_Bool:
  6959. return CK_FloatingComplexToBoolean;
  6960. case Type::STK_Integral:
  6961. Src = ImpCastExprToType(Src.get(),
  6962. SrcTy->castAs<ComplexType>()->getElementType(),
  6963. CK_FloatingComplexToReal);
  6964. return CK_FloatingToIntegral;
  6965. case Type::STK_CPointer:
  6966. case Type::STK_ObjCObjectPointer:
  6967. case Type::STK_BlockPointer:
  6968. llvm_unreachable("valid complex float->pointer cast?");
  6969. case Type::STK_MemberPointer:
  6970. llvm_unreachable("member pointer type in C");
  6971. case Type::STK_FixedPoint:
  6972. Diag(Src.get()->getExprLoc(),
  6973. diag::err_unimplemented_conversion_with_fixed_point_type)
  6974. << SrcTy;
  6975. return CK_IntegralCast;
  6976. }
  6977. llvm_unreachable("Should have returned before this");
  6978. case Type::STK_IntegralComplex:
  6979. switch (DestTy->getScalarTypeKind()) {
  6980. case Type::STK_FloatingComplex:
  6981. return CK_IntegralComplexToFloatingComplex;
  6982. case Type::STK_IntegralComplex:
  6983. return CK_IntegralComplexCast;
  6984. case Type::STK_Integral: {
  6985. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  6986. if (Context.hasSameType(ET, DestTy))
  6987. return CK_IntegralComplexToReal;
  6988. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  6989. return CK_IntegralCast;
  6990. }
  6991. case Type::STK_Bool:
  6992. return CK_IntegralComplexToBoolean;
  6993. case Type::STK_Floating:
  6994. Src = ImpCastExprToType(Src.get(),
  6995. SrcTy->castAs<ComplexType>()->getElementType(),
  6996. CK_IntegralComplexToReal);
  6997. return CK_IntegralToFloating;
  6998. case Type::STK_CPointer:
  6999. case Type::STK_ObjCObjectPointer:
  7000. case Type::STK_BlockPointer:
  7001. llvm_unreachable("valid complex int->pointer cast?");
  7002. case Type::STK_MemberPointer:
  7003. llvm_unreachable("member pointer type in C");
  7004. case Type::STK_FixedPoint:
  7005. Diag(Src.get()->getExprLoc(),
  7006. diag::err_unimplemented_conversion_with_fixed_point_type)
  7007. << SrcTy;
  7008. return CK_IntegralCast;
  7009. }
  7010. llvm_unreachable("Should have returned before this");
  7011. }
  7012. llvm_unreachable("Unhandled scalar cast");
  7013. }
  7014. static bool breakDownVectorType(QualType type, uint64_t &len,
  7015. QualType &eltType) {
  7016. // Vectors are simple.
  7017. if (const VectorType *vecType = type->getAs<VectorType>()) {
  7018. len = vecType->getNumElements();
  7019. eltType = vecType->getElementType();
  7020. assert(eltType->isScalarType());
  7021. return true;
  7022. }
  7023. // We allow lax conversion to and from non-vector types, but only if
  7024. // they're real types (i.e. non-complex, non-pointer scalar types).
  7025. if (!type->isRealType()) return false;
  7026. len = 1;
  7027. eltType = type;
  7028. return true;
  7029. }
  7030. /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
  7031. /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
  7032. /// allowed?
  7033. ///
  7034. /// This will also return false if the two given types do not make sense from
  7035. /// the perspective of SVE bitcasts.
  7036. bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
  7037. assert(srcTy->isVectorType() || destTy->isVectorType());
  7038. auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
  7039. if (!FirstType->isSizelessBuiltinType())
  7040. return false;
  7041. const auto *VecTy = SecondType->getAs<VectorType>();
  7042. return VecTy &&
  7043. VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
  7044. };
  7045. return ValidScalableConversion(srcTy, destTy) ||
  7046. ValidScalableConversion(destTy, srcTy);
  7047. }
  7048. /// Are the two types matrix types and do they have the same dimensions i.e.
  7049. /// do they have the same number of rows and the same number of columns?
  7050. bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
  7051. if (!destTy->isMatrixType() || !srcTy->isMatrixType())
  7052. return false;
  7053. const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
  7054. const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
  7055. return matSrcType->getNumRows() == matDestType->getNumRows() &&
  7056. matSrcType->getNumColumns() == matDestType->getNumColumns();
  7057. }
  7058. bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
  7059. assert(DestTy->isVectorType() || SrcTy->isVectorType());
  7060. uint64_t SrcLen, DestLen;
  7061. QualType SrcEltTy, DestEltTy;
  7062. if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
  7063. return false;
  7064. if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
  7065. return false;
  7066. // ASTContext::getTypeSize will return the size rounded up to a
  7067. // power of 2, so instead of using that, we need to use the raw
  7068. // element size multiplied by the element count.
  7069. uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
  7070. uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
  7071. return (SrcLen * SrcEltSize == DestLen * DestEltSize);
  7072. }
  7073. // This returns true if at least one of the types is an altivec vector.
  7074. bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
  7075. assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
  7076. "expected at least one type to be a vector here");
  7077. bool IsSrcTyAltivec =
  7078. SrcTy->isVectorType() && (SrcTy->castAs<VectorType>()->getVectorKind() ==
  7079. VectorType::AltiVecVector);
  7080. bool IsDestTyAltivec = DestTy->isVectorType() &&
  7081. (DestTy->castAs<VectorType>()->getVectorKind() ==
  7082. VectorType::AltiVecVector);
  7083. return (IsSrcTyAltivec || IsDestTyAltivec);
  7084. }
  7085. // This returns true if both vectors have the same element type.
  7086. bool Sema::areSameVectorElemTypes(QualType SrcTy, QualType DestTy) {
  7087. assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
  7088. "expected at least one type to be a vector here");
  7089. uint64_t SrcLen, DestLen;
  7090. QualType SrcEltTy, DestEltTy;
  7091. if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
  7092. return false;
  7093. if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
  7094. return false;
  7095. return (SrcEltTy == DestEltTy);
  7096. }
  7097. /// Are the two types lax-compatible vector types? That is, given
  7098. /// that one of them is a vector, do they have equal storage sizes,
  7099. /// where the storage size is the number of elements times the element
  7100. /// size?
  7101. ///
  7102. /// This will also return false if either of the types is neither a
  7103. /// vector nor a real type.
  7104. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  7105. assert(destTy->isVectorType() || srcTy->isVectorType());
  7106. // Disallow lax conversions between scalars and ExtVectors (these
  7107. // conversions are allowed for other vector types because common headers
  7108. // depend on them). Most scalar OP ExtVector cases are handled by the
  7109. // splat path anyway, which does what we want (convert, not bitcast).
  7110. // What this rules out for ExtVectors is crazy things like char4*float.
  7111. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  7112. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  7113. return areVectorTypesSameSize(srcTy, destTy);
  7114. }
  7115. /// Is this a legal conversion between two types, one of which is
  7116. /// known to be a vector type?
  7117. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  7118. assert(destTy->isVectorType() || srcTy->isVectorType());
  7119. switch (Context.getLangOpts().getLaxVectorConversions()) {
  7120. case LangOptions::LaxVectorConversionKind::None:
  7121. return false;
  7122. case LangOptions::LaxVectorConversionKind::Integer:
  7123. if (!srcTy->isIntegralOrEnumerationType()) {
  7124. auto *Vec = srcTy->getAs<VectorType>();
  7125. if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
  7126. return false;
  7127. }
  7128. if (!destTy->isIntegralOrEnumerationType()) {
  7129. auto *Vec = destTy->getAs<VectorType>();
  7130. if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
  7131. return false;
  7132. }
  7133. // OK, integer (vector) -> integer (vector) bitcast.
  7134. break;
  7135. case LangOptions::LaxVectorConversionKind::All:
  7136. break;
  7137. }
  7138. return areLaxCompatibleVectorTypes(srcTy, destTy);
  7139. }
  7140. bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
  7141. CastKind &Kind) {
  7142. if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
  7143. if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
  7144. return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
  7145. << DestTy << SrcTy << R;
  7146. }
  7147. } else if (SrcTy->isMatrixType()) {
  7148. return Diag(R.getBegin(),
  7149. diag::err_invalid_conversion_between_matrix_and_type)
  7150. << SrcTy << DestTy << R;
  7151. } else if (DestTy->isMatrixType()) {
  7152. return Diag(R.getBegin(),
  7153. diag::err_invalid_conversion_between_matrix_and_type)
  7154. << DestTy << SrcTy << R;
  7155. }
  7156. Kind = CK_MatrixCast;
  7157. return false;
  7158. }
  7159. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  7160. CastKind &Kind) {
  7161. assert(VectorTy->isVectorType() && "Not a vector type!");
  7162. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  7163. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  7164. return Diag(R.getBegin(),
  7165. Ty->isVectorType() ?
  7166. diag::err_invalid_conversion_between_vectors :
  7167. diag::err_invalid_conversion_between_vector_and_integer)
  7168. << VectorTy << Ty << R;
  7169. } else
  7170. return Diag(R.getBegin(),
  7171. diag::err_invalid_conversion_between_vector_and_scalar)
  7172. << VectorTy << Ty << R;
  7173. Kind = CK_BitCast;
  7174. return false;
  7175. }
  7176. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  7177. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  7178. if (DestElemTy == SplattedExpr->getType())
  7179. return SplattedExpr;
  7180. assert(DestElemTy->isFloatingType() ||
  7181. DestElemTy->isIntegralOrEnumerationType());
  7182. CastKind CK;
  7183. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  7184. // OpenCL requires that we convert `true` boolean expressions to -1, but
  7185. // only when splatting vectors.
  7186. if (DestElemTy->isFloatingType()) {
  7187. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  7188. // in two steps: boolean to signed integral, then to floating.
  7189. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  7190. CK_BooleanToSignedIntegral);
  7191. SplattedExpr = CastExprRes.get();
  7192. CK = CK_IntegralToFloating;
  7193. } else {
  7194. CK = CK_BooleanToSignedIntegral;
  7195. }
  7196. } else {
  7197. ExprResult CastExprRes = SplattedExpr;
  7198. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  7199. if (CastExprRes.isInvalid())
  7200. return ExprError();
  7201. SplattedExpr = CastExprRes.get();
  7202. }
  7203. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  7204. }
  7205. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  7206. Expr *CastExpr, CastKind &Kind) {
  7207. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  7208. QualType SrcTy = CastExpr->getType();
  7209. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  7210. // an ExtVectorType.
  7211. // In OpenCL, casts between vectors of different types are not allowed.
  7212. // (See OpenCL 6.2).
  7213. if (SrcTy->isVectorType()) {
  7214. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  7215. (getLangOpts().OpenCL &&
  7216. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  7217. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  7218. << DestTy << SrcTy << R;
  7219. return ExprError();
  7220. }
  7221. Kind = CK_BitCast;
  7222. return CastExpr;
  7223. }
  7224. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  7225. // conversion will take place first from scalar to elt type, and then
  7226. // splat from elt type to vector.
  7227. if (SrcTy->isPointerType())
  7228. return Diag(R.getBegin(),
  7229. diag::err_invalid_conversion_between_vector_and_scalar)
  7230. << DestTy << SrcTy << R;
  7231. Kind = CK_VectorSplat;
  7232. return prepareVectorSplat(DestTy, CastExpr);
  7233. }
  7234. ExprResult
  7235. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  7236. Declarator &D, ParsedType &Ty,
  7237. SourceLocation RParenLoc, Expr *CastExpr) {
  7238. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  7239. "ActOnCastExpr(): missing type or expr");
  7240. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  7241. if (D.isInvalidType())
  7242. return ExprError();
  7243. if (getLangOpts().CPlusPlus) {
  7244. // Check that there are no default arguments (C++ only).
  7245. CheckExtraCXXDefaultArguments(D);
  7246. } else {
  7247. // Make sure any TypoExprs have been dealt with.
  7248. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  7249. if (!Res.isUsable())
  7250. return ExprError();
  7251. CastExpr = Res.get();
  7252. }
  7253. checkUnusedDeclAttributes(D);
  7254. QualType castType = castTInfo->getType();
  7255. Ty = CreateParsedType(castType, castTInfo);
  7256. bool isVectorLiteral = false;
  7257. // Check for an altivec or OpenCL literal,
  7258. // i.e. all the elements are integer constants.
  7259. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  7260. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  7261. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  7262. && castType->isVectorType() && (PE || PLE)) {
  7263. if (PLE && PLE->getNumExprs() == 0) {
  7264. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  7265. return ExprError();
  7266. }
  7267. if (PE || PLE->getNumExprs() == 1) {
  7268. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  7269. if (!E->isTypeDependent() && !E->getType()->isVectorType())
  7270. isVectorLiteral = true;
  7271. }
  7272. else
  7273. isVectorLiteral = true;
  7274. }
  7275. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  7276. // then handle it as such.
  7277. if (isVectorLiteral)
  7278. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  7279. // If the Expr being casted is a ParenListExpr, handle it specially.
  7280. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  7281. // sequence of BinOp comma operators.
  7282. if (isa<ParenListExpr>(CastExpr)) {
  7283. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  7284. if (Result.isInvalid()) return ExprError();
  7285. CastExpr = Result.get();
  7286. }
  7287. if (getLangOpts().CPlusPlus && !castType->isVoidType())
  7288. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  7289. CheckTollFreeBridgeCast(castType, CastExpr);
  7290. CheckObjCBridgeRelatedCast(castType, CastExpr);
  7291. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  7292. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  7293. }
  7294. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  7295. SourceLocation RParenLoc, Expr *E,
  7296. TypeSourceInfo *TInfo) {
  7297. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  7298. "Expected paren or paren list expression");
  7299. Expr **exprs;
  7300. unsigned numExprs;
  7301. Expr *subExpr;
  7302. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  7303. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  7304. LiteralLParenLoc = PE->getLParenLoc();
  7305. LiteralRParenLoc = PE->getRParenLoc();
  7306. exprs = PE->getExprs();
  7307. numExprs = PE->getNumExprs();
  7308. } else { // isa<ParenExpr> by assertion at function entrance
  7309. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  7310. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  7311. subExpr = cast<ParenExpr>(E)->getSubExpr();
  7312. exprs = &subExpr;
  7313. numExprs = 1;
  7314. }
  7315. QualType Ty = TInfo->getType();
  7316. assert(Ty->isVectorType() && "Expected vector type");
  7317. SmallVector<Expr *, 8> initExprs;
  7318. const VectorType *VTy = Ty->castAs<VectorType>();
  7319. unsigned numElems = VTy->getNumElements();
  7320. // '(...)' form of vector initialization in AltiVec: the number of
  7321. // initializers must be one or must match the size of the vector.
  7322. // If a single value is specified in the initializer then it will be
  7323. // replicated to all the components of the vector
  7324. if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
  7325. VTy->getElementType()))
  7326. return ExprError();
  7327. if (ShouldSplatAltivecScalarInCast(VTy)) {
  7328. // The number of initializers must be one or must match the size of the
  7329. // vector. If a single value is specified in the initializer then it will
  7330. // be replicated to all the components of the vector
  7331. if (numExprs == 1) {
  7332. QualType ElemTy = VTy->getElementType();
  7333. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  7334. if (Literal.isInvalid())
  7335. return ExprError();
  7336. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  7337. PrepareScalarCast(Literal, ElemTy));
  7338. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  7339. }
  7340. else if (numExprs < numElems) {
  7341. Diag(E->getExprLoc(),
  7342. diag::err_incorrect_number_of_vector_initializers);
  7343. return ExprError();
  7344. }
  7345. else
  7346. initExprs.append(exprs, exprs + numExprs);
  7347. }
  7348. else {
  7349. // For OpenCL, when the number of initializers is a single value,
  7350. // it will be replicated to all components of the vector.
  7351. if (getLangOpts().OpenCL &&
  7352. VTy->getVectorKind() == VectorType::GenericVector &&
  7353. numExprs == 1) {
  7354. QualType ElemTy = VTy->getElementType();
  7355. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  7356. if (Literal.isInvalid())
  7357. return ExprError();
  7358. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  7359. PrepareScalarCast(Literal, ElemTy));
  7360. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  7361. }
  7362. initExprs.append(exprs, exprs + numExprs);
  7363. }
  7364. // FIXME: This means that pretty-printing the final AST will produce curly
  7365. // braces instead of the original commas.
  7366. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  7367. initExprs, LiteralRParenLoc);
  7368. initE->setType(Ty);
  7369. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  7370. }
  7371. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  7372. /// the ParenListExpr into a sequence of comma binary operators.
  7373. ExprResult
  7374. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  7375. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  7376. if (!E)
  7377. return OrigExpr;
  7378. ExprResult Result(E->getExpr(0));
  7379. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  7380. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  7381. E->getExpr(i));
  7382. if (Result.isInvalid()) return ExprError();
  7383. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  7384. }
  7385. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  7386. SourceLocation R,
  7387. MultiExprArg Val) {
  7388. return ParenListExpr::Create(Context, L, Val, R);
  7389. }
  7390. /// Emit a specialized diagnostic when one expression is a null pointer
  7391. /// constant and the other is not a pointer. Returns true if a diagnostic is
  7392. /// emitted.
  7393. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  7394. SourceLocation QuestionLoc) {
  7395. Expr *NullExpr = LHSExpr;
  7396. Expr *NonPointerExpr = RHSExpr;
  7397. Expr::NullPointerConstantKind NullKind =
  7398. NullExpr->isNullPointerConstant(Context,
  7399. Expr::NPC_ValueDependentIsNotNull);
  7400. if (NullKind == Expr::NPCK_NotNull) {
  7401. NullExpr = RHSExpr;
  7402. NonPointerExpr = LHSExpr;
  7403. NullKind =
  7404. NullExpr->isNullPointerConstant(Context,
  7405. Expr::NPC_ValueDependentIsNotNull);
  7406. }
  7407. if (NullKind == Expr::NPCK_NotNull)
  7408. return false;
  7409. if (NullKind == Expr::NPCK_ZeroExpression)
  7410. return false;
  7411. if (NullKind == Expr::NPCK_ZeroLiteral) {
  7412. // In this case, check to make sure that we got here from a "NULL"
  7413. // string in the source code.
  7414. NullExpr = NullExpr->IgnoreParenImpCasts();
  7415. SourceLocation loc = NullExpr->getExprLoc();
  7416. if (!findMacroSpelling(loc, "NULL"))
  7417. return false;
  7418. }
  7419. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  7420. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  7421. << NonPointerExpr->getType() << DiagType
  7422. << NonPointerExpr->getSourceRange();
  7423. return true;
  7424. }
  7425. /// Return false if the condition expression is valid, true otherwise.
  7426. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  7427. QualType CondTy = Cond->getType();
  7428. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  7429. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  7430. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  7431. << CondTy << Cond->getSourceRange();
  7432. return true;
  7433. }
  7434. // C99 6.5.15p2
  7435. if (CondTy->isScalarType()) return false;
  7436. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  7437. << CondTy << Cond->getSourceRange();
  7438. return true;
  7439. }
  7440. /// Return false if the NullExpr can be promoted to PointerTy,
  7441. /// true otherwise.
  7442. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  7443. QualType PointerTy) {
  7444. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  7445. !NullExpr.get()->isNullPointerConstant(S.Context,
  7446. Expr::NPC_ValueDependentIsNull))
  7447. return true;
  7448. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  7449. return false;
  7450. }
  7451. /// Checks compatibility between two pointers and return the resulting
  7452. /// type.
  7453. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  7454. ExprResult &RHS,
  7455. SourceLocation Loc) {
  7456. QualType LHSTy = LHS.get()->getType();
  7457. QualType RHSTy = RHS.get()->getType();
  7458. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  7459. // Two identical pointers types are always compatible.
  7460. return S.Context.getCommonSugaredType(LHSTy, RHSTy);
  7461. }
  7462. QualType lhptee, rhptee;
  7463. // Get the pointee types.
  7464. bool IsBlockPointer = false;
  7465. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  7466. lhptee = LHSBTy->getPointeeType();
  7467. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  7468. IsBlockPointer = true;
  7469. } else {
  7470. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  7471. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  7472. }
  7473. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  7474. // differently qualified versions of compatible types, the result type is
  7475. // a pointer to an appropriately qualified version of the composite
  7476. // type.
  7477. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  7478. // clause doesn't make sense for our extensions. E.g. address space 2 should
  7479. // be incompatible with address space 3: they may live on different devices or
  7480. // anything.
  7481. Qualifiers lhQual = lhptee.getQualifiers();
  7482. Qualifiers rhQual = rhptee.getQualifiers();
  7483. LangAS ResultAddrSpace = LangAS::Default;
  7484. LangAS LAddrSpace = lhQual.getAddressSpace();
  7485. LangAS RAddrSpace = rhQual.getAddressSpace();
  7486. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  7487. // spaces is disallowed.
  7488. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  7489. ResultAddrSpace = LAddrSpace;
  7490. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  7491. ResultAddrSpace = RAddrSpace;
  7492. else {
  7493. S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7494. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  7495. << RHS.get()->getSourceRange();
  7496. return QualType();
  7497. }
  7498. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  7499. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  7500. lhQual.removeCVRQualifiers();
  7501. rhQual.removeCVRQualifiers();
  7502. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  7503. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  7504. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  7505. // qual types are compatible iff
  7506. // * corresponded types are compatible
  7507. // * CVR qualifiers are equal
  7508. // * address spaces are equal
  7509. // Thus for conditional operator we merge CVR and address space unqualified
  7510. // pointees and if there is a composite type we return a pointer to it with
  7511. // merged qualifiers.
  7512. LHSCastKind =
  7513. LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  7514. RHSCastKind =
  7515. RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  7516. lhQual.removeAddressSpace();
  7517. rhQual.removeAddressSpace();
  7518. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  7519. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  7520. QualType CompositeTy = S.Context.mergeTypes(
  7521. lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
  7522. /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
  7523. if (CompositeTy.isNull()) {
  7524. // In this situation, we assume void* type. No especially good
  7525. // reason, but this is what gcc does, and we do have to pick
  7526. // to get a consistent AST.
  7527. QualType incompatTy;
  7528. incompatTy = S.Context.getPointerType(
  7529. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  7530. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  7531. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  7532. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  7533. // for casts between types with incompatible address space qualifiers.
  7534. // For the following code the compiler produces casts between global and
  7535. // local address spaces of the corresponded innermost pointees:
  7536. // local int *global *a;
  7537. // global int *global *b;
  7538. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  7539. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  7540. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  7541. << RHS.get()->getSourceRange();
  7542. return incompatTy;
  7543. }
  7544. // The pointer types are compatible.
  7545. // In case of OpenCL ResultTy should have the address space qualifier
  7546. // which is a superset of address spaces of both the 2nd and the 3rd
  7547. // operands of the conditional operator.
  7548. QualType ResultTy = [&, ResultAddrSpace]() {
  7549. if (S.getLangOpts().OpenCL) {
  7550. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  7551. CompositeQuals.setAddressSpace(ResultAddrSpace);
  7552. return S.Context
  7553. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  7554. .withCVRQualifiers(MergedCVRQual);
  7555. }
  7556. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  7557. }();
  7558. if (IsBlockPointer)
  7559. ResultTy = S.Context.getBlockPointerType(ResultTy);
  7560. else
  7561. ResultTy = S.Context.getPointerType(ResultTy);
  7562. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  7563. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  7564. return ResultTy;
  7565. }
  7566. /// Return the resulting type when the operands are both block pointers.
  7567. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  7568. ExprResult &LHS,
  7569. ExprResult &RHS,
  7570. SourceLocation Loc) {
  7571. QualType LHSTy = LHS.get()->getType();
  7572. QualType RHSTy = RHS.get()->getType();
  7573. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  7574. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  7575. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  7576. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  7577. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  7578. return destType;
  7579. }
  7580. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  7581. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  7582. << RHS.get()->getSourceRange();
  7583. return QualType();
  7584. }
  7585. // We have 2 block pointer types.
  7586. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  7587. }
  7588. /// Return the resulting type when the operands are both pointers.
  7589. static QualType
  7590. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  7591. ExprResult &RHS,
  7592. SourceLocation Loc) {
  7593. // get the pointer types
  7594. QualType LHSTy = LHS.get()->getType();
  7595. QualType RHSTy = RHS.get()->getType();
  7596. // get the "pointed to" types
  7597. QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  7598. QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  7599. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  7600. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  7601. // Figure out necessary qualifiers (C99 6.5.15p6)
  7602. QualType destPointee
  7603. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  7604. QualType destType = S.Context.getPointerType(destPointee);
  7605. // Add qualifiers if necessary.
  7606. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  7607. // Promote to void*.
  7608. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  7609. return destType;
  7610. }
  7611. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  7612. QualType destPointee
  7613. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  7614. QualType destType = S.Context.getPointerType(destPointee);
  7615. // Add qualifiers if necessary.
  7616. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  7617. // Promote to void*.
  7618. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  7619. return destType;
  7620. }
  7621. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  7622. }
  7623. /// Return false if the first expression is not an integer and the second
  7624. /// expression is not a pointer, true otherwise.
  7625. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  7626. Expr* PointerExpr, SourceLocation Loc,
  7627. bool IsIntFirstExpr) {
  7628. if (!PointerExpr->getType()->isPointerType() ||
  7629. !Int.get()->getType()->isIntegerType())
  7630. return false;
  7631. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  7632. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  7633. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  7634. << Expr1->getType() << Expr2->getType()
  7635. << Expr1->getSourceRange() << Expr2->getSourceRange();
  7636. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  7637. CK_IntegralToPointer);
  7638. return true;
  7639. }
  7640. /// Simple conversion between integer and floating point types.
  7641. ///
  7642. /// Used when handling the OpenCL conditional operator where the
  7643. /// condition is a vector while the other operands are scalar.
  7644. ///
  7645. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  7646. /// types are either integer or floating type. Between the two
  7647. /// operands, the type with the higher rank is defined as the "result
  7648. /// type". The other operand needs to be promoted to the same type. No
  7649. /// other type promotion is allowed. We cannot use
  7650. /// UsualArithmeticConversions() for this purpose, since it always
  7651. /// promotes promotable types.
  7652. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  7653. ExprResult &RHS,
  7654. SourceLocation QuestionLoc) {
  7655. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  7656. if (LHS.isInvalid())
  7657. return QualType();
  7658. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  7659. if (RHS.isInvalid())
  7660. return QualType();
  7661. // For conversion purposes, we ignore any qualifiers.
  7662. // For example, "const float" and "float" are equivalent.
  7663. QualType LHSType =
  7664. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  7665. QualType RHSType =
  7666. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  7667. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  7668. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  7669. << LHSType << LHS.get()->getSourceRange();
  7670. return QualType();
  7671. }
  7672. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  7673. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  7674. << RHSType << RHS.get()->getSourceRange();
  7675. return QualType();
  7676. }
  7677. // If both types are identical, no conversion is needed.
  7678. if (LHSType == RHSType)
  7679. return LHSType;
  7680. // Now handle "real" floating types (i.e. float, double, long double).
  7681. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  7682. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  7683. /*IsCompAssign = */ false);
  7684. // Finally, we have two differing integer types.
  7685. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  7686. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  7687. }
  7688. /// Convert scalar operands to a vector that matches the
  7689. /// condition in length.
  7690. ///
  7691. /// Used when handling the OpenCL conditional operator where the
  7692. /// condition is a vector while the other operands are scalar.
  7693. ///
  7694. /// We first compute the "result type" for the scalar operands
  7695. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  7696. /// into a vector of that type where the length matches the condition
  7697. /// vector type. s6.11.6 requires that the element types of the result
  7698. /// and the condition must have the same number of bits.
  7699. static QualType
  7700. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7701. QualType CondTy, SourceLocation QuestionLoc) {
  7702. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  7703. if (ResTy.isNull()) return QualType();
  7704. const VectorType *CV = CondTy->getAs<VectorType>();
  7705. assert(CV);
  7706. // Determine the vector result type
  7707. unsigned NumElements = CV->getNumElements();
  7708. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  7709. // Ensure that all types have the same number of bits
  7710. if (S.Context.getTypeSize(CV->getElementType())
  7711. != S.Context.getTypeSize(ResTy)) {
  7712. // Since VectorTy is created internally, it does not pretty print
  7713. // with an OpenCL name. Instead, we just print a description.
  7714. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  7715. SmallString<64> Str;
  7716. llvm::raw_svector_ostream OS(Str);
  7717. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  7718. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  7719. << CondTy << OS.str();
  7720. return QualType();
  7721. }
  7722. // Convert operands to the vector result type
  7723. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  7724. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  7725. return VectorTy;
  7726. }
  7727. /// Return false if this is a valid OpenCL condition vector
  7728. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  7729. SourceLocation QuestionLoc) {
  7730. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  7731. // integral type.
  7732. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  7733. assert(CondTy);
  7734. QualType EleTy = CondTy->getElementType();
  7735. if (EleTy->isIntegerType()) return false;
  7736. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  7737. << Cond->getType() << Cond->getSourceRange();
  7738. return true;
  7739. }
  7740. /// Return false if the vector condition type and the vector
  7741. /// result type are compatible.
  7742. ///
  7743. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  7744. /// number of elements, and their element types have the same number
  7745. /// of bits.
  7746. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  7747. SourceLocation QuestionLoc) {
  7748. const VectorType *CV = CondTy->getAs<VectorType>();
  7749. const VectorType *RV = VecResTy->getAs<VectorType>();
  7750. assert(CV && RV);
  7751. if (CV->getNumElements() != RV->getNumElements()) {
  7752. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  7753. << CondTy << VecResTy;
  7754. return true;
  7755. }
  7756. QualType CVE = CV->getElementType();
  7757. QualType RVE = RV->getElementType();
  7758. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  7759. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  7760. << CondTy << VecResTy;
  7761. return true;
  7762. }
  7763. return false;
  7764. }
  7765. /// Return the resulting type for the conditional operator in
  7766. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  7767. /// s6.3.i) when the condition is a vector type.
  7768. static QualType
  7769. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  7770. ExprResult &LHS, ExprResult &RHS,
  7771. SourceLocation QuestionLoc) {
  7772. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  7773. if (Cond.isInvalid())
  7774. return QualType();
  7775. QualType CondTy = Cond.get()->getType();
  7776. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  7777. return QualType();
  7778. // If either operand is a vector then find the vector type of the
  7779. // result as specified in OpenCL v1.1 s6.3.i.
  7780. if (LHS.get()->getType()->isVectorType() ||
  7781. RHS.get()->getType()->isVectorType()) {
  7782. bool IsBoolVecLang =
  7783. !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
  7784. QualType VecResTy =
  7785. S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  7786. /*isCompAssign*/ false,
  7787. /*AllowBothBool*/ true,
  7788. /*AllowBoolConversions*/ false,
  7789. /*AllowBooleanOperation*/ IsBoolVecLang,
  7790. /*ReportInvalid*/ true);
  7791. if (VecResTy.isNull())
  7792. return QualType();
  7793. // The result type must match the condition type as specified in
  7794. // OpenCL v1.1 s6.11.6.
  7795. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  7796. return QualType();
  7797. return VecResTy;
  7798. }
  7799. // Both operands are scalar.
  7800. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  7801. }
  7802. /// Return true if the Expr is block type
  7803. static bool checkBlockType(Sema &S, const Expr *E) {
  7804. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  7805. QualType Ty = CE->getCallee()->getType();
  7806. if (Ty->isBlockPointerType()) {
  7807. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  7808. return true;
  7809. }
  7810. }
  7811. return false;
  7812. }
  7813. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  7814. /// In that case, LHS = cond.
  7815. /// C99 6.5.15
  7816. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  7817. ExprResult &RHS, ExprValueKind &VK,
  7818. ExprObjectKind &OK,
  7819. SourceLocation QuestionLoc) {
  7820. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  7821. if (!LHSResult.isUsable()) return QualType();
  7822. LHS = LHSResult;
  7823. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  7824. if (!RHSResult.isUsable()) return QualType();
  7825. RHS = RHSResult;
  7826. // C++ is sufficiently different to merit its own checker.
  7827. if (getLangOpts().CPlusPlus)
  7828. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  7829. VK = VK_PRValue;
  7830. OK = OK_Ordinary;
  7831. if (Context.isDependenceAllowed() &&
  7832. (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
  7833. RHS.get()->isTypeDependent())) {
  7834. assert(!getLangOpts().CPlusPlus);
  7835. assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
  7836. RHS.get()->containsErrors()) &&
  7837. "should only occur in error-recovery path.");
  7838. return Context.DependentTy;
  7839. }
  7840. // The OpenCL operator with a vector condition is sufficiently
  7841. // different to merit its own checker.
  7842. if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
  7843. Cond.get()->getType()->isExtVectorType())
  7844. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  7845. // First, check the condition.
  7846. Cond = UsualUnaryConversions(Cond.get());
  7847. if (Cond.isInvalid())
  7848. return QualType();
  7849. if (checkCondition(*this, Cond.get(), QuestionLoc))
  7850. return QualType();
  7851. // Now check the two expressions.
  7852. if (LHS.get()->getType()->isVectorType() ||
  7853. RHS.get()->getType()->isVectorType())
  7854. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
  7855. /*AllowBothBool*/ true,
  7856. /*AllowBoolConversions*/ false,
  7857. /*AllowBooleanOperation*/ false,
  7858. /*ReportInvalid*/ true);
  7859. QualType ResTy =
  7860. UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
  7861. if (LHS.isInvalid() || RHS.isInvalid())
  7862. return QualType();
  7863. QualType LHSTy = LHS.get()->getType();
  7864. QualType RHSTy = RHS.get()->getType();
  7865. // Diagnose attempts to convert between __ibm128, __float128 and long double
  7866. // where such conversions currently can't be handled.
  7867. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  7868. Diag(QuestionLoc,
  7869. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  7870. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7871. return QualType();
  7872. }
  7873. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  7874. // selection operator (?:).
  7875. if (getLangOpts().OpenCL &&
  7876. ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
  7877. return QualType();
  7878. }
  7879. // If both operands have arithmetic type, do the usual arithmetic conversions
  7880. // to find a common type: C99 6.5.15p3,5.
  7881. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  7882. // Disallow invalid arithmetic conversions, such as those between bit-
  7883. // precise integers types of different sizes, or between a bit-precise
  7884. // integer and another type.
  7885. if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
  7886. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  7887. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  7888. << RHS.get()->getSourceRange();
  7889. return QualType();
  7890. }
  7891. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  7892. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  7893. return ResTy;
  7894. }
  7895. // And if they're both bfloat (which isn't arithmetic), that's fine too.
  7896. if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
  7897. return Context.getCommonSugaredType(LHSTy, RHSTy);
  7898. }
  7899. // If both operands are the same structure or union type, the result is that
  7900. // type.
  7901. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  7902. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  7903. if (LHSRT->getDecl() == RHSRT->getDecl())
  7904. // "If both the operands have structure or union type, the result has
  7905. // that type." This implies that CV qualifiers are dropped.
  7906. return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
  7907. RHSTy.getUnqualifiedType());
  7908. // FIXME: Type of conditional expression must be complete in C mode.
  7909. }
  7910. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  7911. // The following || allows only one side to be void (a GCC-ism).
  7912. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  7913. QualType ResTy;
  7914. if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
  7915. ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
  7916. } else if (RHSTy->isVoidType()) {
  7917. ResTy = RHSTy;
  7918. Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  7919. << RHS.get()->getSourceRange();
  7920. } else {
  7921. ResTy = LHSTy;
  7922. Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  7923. << LHS.get()->getSourceRange();
  7924. }
  7925. LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
  7926. RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
  7927. return ResTy;
  7928. }
  7929. // C2x 6.5.15p7:
  7930. // ... if both the second and third operands have nullptr_t type, the
  7931. // result also has that type.
  7932. if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
  7933. return ResTy;
  7934. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  7935. // the type of the other operand."
  7936. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  7937. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  7938. // All objective-c pointer type analysis is done here.
  7939. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  7940. QuestionLoc);
  7941. if (LHS.isInvalid() || RHS.isInvalid())
  7942. return QualType();
  7943. if (!compositeType.isNull())
  7944. return compositeType;
  7945. // Handle block pointer types.
  7946. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  7947. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  7948. QuestionLoc);
  7949. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  7950. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  7951. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  7952. QuestionLoc);
  7953. // GCC compatibility: soften pointer/integer mismatch. Note that
  7954. // null pointers have been filtered out by this point.
  7955. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  7956. /*IsIntFirstExpr=*/true))
  7957. return RHSTy;
  7958. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  7959. /*IsIntFirstExpr=*/false))
  7960. return LHSTy;
  7961. // Allow ?: operations in which both operands have the same
  7962. // built-in sizeless type.
  7963. if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
  7964. return Context.getCommonSugaredType(LHSTy, RHSTy);
  7965. // Emit a better diagnostic if one of the expressions is a null pointer
  7966. // constant and the other is not a pointer type. In this case, the user most
  7967. // likely forgot to take the address of the other expression.
  7968. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  7969. return QualType();
  7970. // Otherwise, the operands are not compatible.
  7971. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  7972. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  7973. << RHS.get()->getSourceRange();
  7974. return QualType();
  7975. }
  7976. /// FindCompositeObjCPointerType - Helper method to find composite type of
  7977. /// two objective-c pointer types of the two input expressions.
  7978. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  7979. SourceLocation QuestionLoc) {
  7980. QualType LHSTy = LHS.get()->getType();
  7981. QualType RHSTy = RHS.get()->getType();
  7982. // Handle things like Class and struct objc_class*. Here we case the result
  7983. // to the pseudo-builtin, because that will be implicitly cast back to the
  7984. // redefinition type if an attempt is made to access its fields.
  7985. if (LHSTy->isObjCClassType() &&
  7986. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  7987. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  7988. return LHSTy;
  7989. }
  7990. if (RHSTy->isObjCClassType() &&
  7991. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  7992. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  7993. return RHSTy;
  7994. }
  7995. // And the same for struct objc_object* / id
  7996. if (LHSTy->isObjCIdType() &&
  7997. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  7998. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  7999. return LHSTy;
  8000. }
  8001. if (RHSTy->isObjCIdType() &&
  8002. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  8003. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  8004. return RHSTy;
  8005. }
  8006. // And the same for struct objc_selector* / SEL
  8007. if (Context.isObjCSelType(LHSTy) &&
  8008. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  8009. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  8010. return LHSTy;
  8011. }
  8012. if (Context.isObjCSelType(RHSTy) &&
  8013. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  8014. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  8015. return RHSTy;
  8016. }
  8017. // Check constraints for Objective-C object pointers types.
  8018. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  8019. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  8020. // Two identical object pointer types are always compatible.
  8021. return LHSTy;
  8022. }
  8023. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  8024. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  8025. QualType compositeType = LHSTy;
  8026. // If both operands are interfaces and either operand can be
  8027. // assigned to the other, use that type as the composite
  8028. // type. This allows
  8029. // xxx ? (A*) a : (B*) b
  8030. // where B is a subclass of A.
  8031. //
  8032. // Additionally, as for assignment, if either type is 'id'
  8033. // allow silent coercion. Finally, if the types are
  8034. // incompatible then make sure to use 'id' as the composite
  8035. // type so the result is acceptable for sending messages to.
  8036. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  8037. // It could return the composite type.
  8038. if (!(compositeType =
  8039. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  8040. // Nothing more to do.
  8041. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  8042. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  8043. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  8044. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  8045. } else if ((LHSOPT->isObjCQualifiedIdType() ||
  8046. RHSOPT->isObjCQualifiedIdType()) &&
  8047. Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
  8048. true)) {
  8049. // Need to handle "id<xx>" explicitly.
  8050. // GCC allows qualified id and any Objective-C type to devolve to
  8051. // id. Currently localizing to here until clear this should be
  8052. // part of ObjCQualifiedIdTypesAreCompatible.
  8053. compositeType = Context.getObjCIdType();
  8054. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  8055. compositeType = Context.getObjCIdType();
  8056. } else {
  8057. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  8058. << LHSTy << RHSTy
  8059. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8060. QualType incompatTy = Context.getObjCIdType();
  8061. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  8062. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  8063. return incompatTy;
  8064. }
  8065. // The object pointer types are compatible.
  8066. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  8067. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  8068. return compositeType;
  8069. }
  8070. // Check Objective-C object pointer types and 'void *'
  8071. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  8072. if (getLangOpts().ObjCAutoRefCount) {
  8073. // ARC forbids the implicit conversion of object pointers to 'void *',
  8074. // so these types are not compatible.
  8075. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  8076. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8077. LHS = RHS = true;
  8078. return QualType();
  8079. }
  8080. QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  8081. QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
  8082. QualType destPointee
  8083. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  8084. QualType destType = Context.getPointerType(destPointee);
  8085. // Add qualifiers if necessary.
  8086. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  8087. // Promote to void*.
  8088. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  8089. return destType;
  8090. }
  8091. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  8092. if (getLangOpts().ObjCAutoRefCount) {
  8093. // ARC forbids the implicit conversion of object pointers to 'void *',
  8094. // so these types are not compatible.
  8095. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  8096. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8097. LHS = RHS = true;
  8098. return QualType();
  8099. }
  8100. QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
  8101. QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  8102. QualType destPointee
  8103. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  8104. QualType destType = Context.getPointerType(destPointee);
  8105. // Add qualifiers if necessary.
  8106. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  8107. // Promote to void*.
  8108. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  8109. return destType;
  8110. }
  8111. return QualType();
  8112. }
  8113. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  8114. /// ParenRange in parentheses.
  8115. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  8116. const PartialDiagnostic &Note,
  8117. SourceRange ParenRange) {
  8118. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  8119. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  8120. EndLoc.isValid()) {
  8121. Self.Diag(Loc, Note)
  8122. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  8123. << FixItHint::CreateInsertion(EndLoc, ")");
  8124. } else {
  8125. // We can't display the parentheses, so just show the bare note.
  8126. Self.Diag(Loc, Note) << ParenRange;
  8127. }
  8128. }
  8129. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  8130. return BinaryOperator::isAdditiveOp(Opc) ||
  8131. BinaryOperator::isMultiplicativeOp(Opc) ||
  8132. BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
  8133. // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
  8134. // not any of the logical operators. Bitwise-xor is commonly used as a
  8135. // logical-xor because there is no logical-xor operator. The logical
  8136. // operators, including uses of xor, have a high false positive rate for
  8137. // precedence warnings.
  8138. }
  8139. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  8140. /// expression, either using a built-in or overloaded operator,
  8141. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  8142. /// expression.
  8143. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  8144. Expr **RHSExprs) {
  8145. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  8146. E = E->IgnoreImpCasts();
  8147. E = E->IgnoreConversionOperatorSingleStep();
  8148. E = E->IgnoreImpCasts();
  8149. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  8150. E = MTE->getSubExpr();
  8151. E = E->IgnoreImpCasts();
  8152. }
  8153. // Built-in binary operator.
  8154. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  8155. if (IsArithmeticOp(OP->getOpcode())) {
  8156. *Opcode = OP->getOpcode();
  8157. *RHSExprs = OP->getRHS();
  8158. return true;
  8159. }
  8160. }
  8161. // Overloaded operator.
  8162. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  8163. if (Call->getNumArgs() != 2)
  8164. return false;
  8165. // Make sure this is really a binary operator that is safe to pass into
  8166. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  8167. OverloadedOperatorKind OO = Call->getOperator();
  8168. if (OO < OO_Plus || OO > OO_Arrow ||
  8169. OO == OO_PlusPlus || OO == OO_MinusMinus)
  8170. return false;
  8171. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  8172. if (IsArithmeticOp(OpKind)) {
  8173. *Opcode = OpKind;
  8174. *RHSExprs = Call->getArg(1);
  8175. return true;
  8176. }
  8177. }
  8178. return false;
  8179. }
  8180. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  8181. /// or is a logical expression such as (x==y) which has int type, but is
  8182. /// commonly interpreted as boolean.
  8183. static bool ExprLooksBoolean(Expr *E) {
  8184. E = E->IgnoreParenImpCasts();
  8185. if (E->getType()->isBooleanType())
  8186. return true;
  8187. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  8188. return OP->isComparisonOp() || OP->isLogicalOp();
  8189. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  8190. return OP->getOpcode() == UO_LNot;
  8191. if (E->getType()->isPointerType())
  8192. return true;
  8193. // FIXME: What about overloaded operator calls returning "unspecified boolean
  8194. // type"s (commonly pointer-to-members)?
  8195. return false;
  8196. }
  8197. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  8198. /// and binary operator are mixed in a way that suggests the programmer assumed
  8199. /// the conditional operator has higher precedence, for example:
  8200. /// "int x = a + someBinaryCondition ? 1 : 2".
  8201. static void DiagnoseConditionalPrecedence(Sema &Self,
  8202. SourceLocation OpLoc,
  8203. Expr *Condition,
  8204. Expr *LHSExpr,
  8205. Expr *RHSExpr) {
  8206. BinaryOperatorKind CondOpcode;
  8207. Expr *CondRHS;
  8208. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  8209. return;
  8210. if (!ExprLooksBoolean(CondRHS))
  8211. return;
  8212. // The condition is an arithmetic binary expression, with a right-
  8213. // hand side that looks boolean, so warn.
  8214. unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
  8215. ? diag::warn_precedence_bitwise_conditional
  8216. : diag::warn_precedence_conditional;
  8217. Self.Diag(OpLoc, DiagID)
  8218. << Condition->getSourceRange()
  8219. << BinaryOperator::getOpcodeStr(CondOpcode);
  8220. SuggestParentheses(
  8221. Self, OpLoc,
  8222. Self.PDiag(diag::note_precedence_silence)
  8223. << BinaryOperator::getOpcodeStr(CondOpcode),
  8224. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  8225. SuggestParentheses(Self, OpLoc,
  8226. Self.PDiag(diag::note_precedence_conditional_first),
  8227. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  8228. }
  8229. /// Compute the nullability of a conditional expression.
  8230. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  8231. QualType LHSTy, QualType RHSTy,
  8232. ASTContext &Ctx) {
  8233. if (!ResTy->isAnyPointerType())
  8234. return ResTy;
  8235. auto GetNullability = [](QualType Ty) {
  8236. std::optional<NullabilityKind> Kind = Ty->getNullability();
  8237. if (Kind) {
  8238. // For our purposes, treat _Nullable_result as _Nullable.
  8239. if (*Kind == NullabilityKind::NullableResult)
  8240. return NullabilityKind::Nullable;
  8241. return *Kind;
  8242. }
  8243. return NullabilityKind::Unspecified;
  8244. };
  8245. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  8246. NullabilityKind MergedKind;
  8247. // Compute nullability of a binary conditional expression.
  8248. if (IsBin) {
  8249. if (LHSKind == NullabilityKind::NonNull)
  8250. MergedKind = NullabilityKind::NonNull;
  8251. else
  8252. MergedKind = RHSKind;
  8253. // Compute nullability of a normal conditional expression.
  8254. } else {
  8255. if (LHSKind == NullabilityKind::Nullable ||
  8256. RHSKind == NullabilityKind::Nullable)
  8257. MergedKind = NullabilityKind::Nullable;
  8258. else if (LHSKind == NullabilityKind::NonNull)
  8259. MergedKind = RHSKind;
  8260. else if (RHSKind == NullabilityKind::NonNull)
  8261. MergedKind = LHSKind;
  8262. else
  8263. MergedKind = NullabilityKind::Unspecified;
  8264. }
  8265. // Return if ResTy already has the correct nullability.
  8266. if (GetNullability(ResTy) == MergedKind)
  8267. return ResTy;
  8268. // Strip all nullability from ResTy.
  8269. while (ResTy->getNullability())
  8270. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  8271. // Create a new AttributedType with the new nullability kind.
  8272. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  8273. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  8274. }
  8275. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  8276. /// in the case of a the GNU conditional expr extension.
  8277. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  8278. SourceLocation ColonLoc,
  8279. Expr *CondExpr, Expr *LHSExpr,
  8280. Expr *RHSExpr) {
  8281. if (!Context.isDependenceAllowed()) {
  8282. // C cannot handle TypoExpr nodes in the condition because it
  8283. // doesn't handle dependent types properly, so make sure any TypoExprs have
  8284. // been dealt with before checking the operands.
  8285. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  8286. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  8287. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  8288. if (!CondResult.isUsable())
  8289. return ExprError();
  8290. if (LHSExpr) {
  8291. if (!LHSResult.isUsable())
  8292. return ExprError();
  8293. }
  8294. if (!RHSResult.isUsable())
  8295. return ExprError();
  8296. CondExpr = CondResult.get();
  8297. LHSExpr = LHSResult.get();
  8298. RHSExpr = RHSResult.get();
  8299. }
  8300. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  8301. // was the condition.
  8302. OpaqueValueExpr *opaqueValue = nullptr;
  8303. Expr *commonExpr = nullptr;
  8304. if (!LHSExpr) {
  8305. commonExpr = CondExpr;
  8306. // Lower out placeholder types first. This is important so that we don't
  8307. // try to capture a placeholder. This happens in few cases in C++; such
  8308. // as Objective-C++'s dictionary subscripting syntax.
  8309. if (commonExpr->hasPlaceholderType()) {
  8310. ExprResult result = CheckPlaceholderExpr(commonExpr);
  8311. if (!result.isUsable()) return ExprError();
  8312. commonExpr = result.get();
  8313. }
  8314. // We usually want to apply unary conversions *before* saving, except
  8315. // in the special case of a C++ l-value conditional.
  8316. if (!(getLangOpts().CPlusPlus
  8317. && !commonExpr->isTypeDependent()
  8318. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  8319. && commonExpr->isGLValue()
  8320. && commonExpr->isOrdinaryOrBitFieldObject()
  8321. && RHSExpr->isOrdinaryOrBitFieldObject()
  8322. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  8323. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  8324. if (commonRes.isInvalid())
  8325. return ExprError();
  8326. commonExpr = commonRes.get();
  8327. }
  8328. // If the common expression is a class or array prvalue, materialize it
  8329. // so that we can safely refer to it multiple times.
  8330. if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
  8331. commonExpr->getType()->isArrayType())) {
  8332. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  8333. if (MatExpr.isInvalid())
  8334. return ExprError();
  8335. commonExpr = MatExpr.get();
  8336. }
  8337. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  8338. commonExpr->getType(),
  8339. commonExpr->getValueKind(),
  8340. commonExpr->getObjectKind(),
  8341. commonExpr);
  8342. LHSExpr = CondExpr = opaqueValue;
  8343. }
  8344. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  8345. ExprValueKind VK = VK_PRValue;
  8346. ExprObjectKind OK = OK_Ordinary;
  8347. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  8348. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  8349. VK, OK, QuestionLoc);
  8350. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  8351. RHS.isInvalid())
  8352. return ExprError();
  8353. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  8354. RHS.get());
  8355. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  8356. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  8357. Context);
  8358. if (!commonExpr)
  8359. return new (Context)
  8360. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  8361. RHS.get(), result, VK, OK);
  8362. return new (Context) BinaryConditionalOperator(
  8363. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  8364. ColonLoc, result, VK, OK);
  8365. }
  8366. // Check if we have a conversion between incompatible cmse function pointer
  8367. // types, that is, a conversion between a function pointer with the
  8368. // cmse_nonsecure_call attribute and one without.
  8369. static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
  8370. QualType ToType) {
  8371. if (const auto *ToFn =
  8372. dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
  8373. if (const auto *FromFn =
  8374. dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
  8375. FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
  8376. FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
  8377. return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
  8378. }
  8379. }
  8380. return false;
  8381. }
  8382. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  8383. // being closely modeled after the C99 spec:-). The odd characteristic of this
  8384. // routine is it effectively iqnores the qualifiers on the top level pointee.
  8385. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  8386. // FIXME: add a couple examples in this comment.
  8387. static Sema::AssignConvertType
  8388. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
  8389. SourceLocation Loc) {
  8390. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  8391. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  8392. // get the "pointed to" type (ignoring qualifiers at the top level)
  8393. const Type *lhptee, *rhptee;
  8394. Qualifiers lhq, rhq;
  8395. std::tie(lhptee, lhq) =
  8396. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  8397. std::tie(rhptee, rhq) =
  8398. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  8399. Sema::AssignConvertType ConvTy = Sema::Compatible;
  8400. // C99 6.5.16.1p1: This following citation is common to constraints
  8401. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  8402. // qualifiers of the type *pointed to* by the right;
  8403. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  8404. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  8405. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  8406. // Ignore lifetime for further calculation.
  8407. lhq.removeObjCLifetime();
  8408. rhq.removeObjCLifetime();
  8409. }
  8410. if (!lhq.compatiblyIncludes(rhq)) {
  8411. // Treat address-space mismatches as fatal.
  8412. if (!lhq.isAddressSpaceSupersetOf(rhq))
  8413. return Sema::IncompatiblePointerDiscardsQualifiers;
  8414. // It's okay to add or remove GC or lifetime qualifiers when converting to
  8415. // and from void*.
  8416. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  8417. .compatiblyIncludes(
  8418. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  8419. && (lhptee->isVoidType() || rhptee->isVoidType()))
  8420. ; // keep old
  8421. // Treat lifetime mismatches as fatal.
  8422. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  8423. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  8424. // For GCC/MS compatibility, other qualifier mismatches are treated
  8425. // as still compatible in C.
  8426. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  8427. }
  8428. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  8429. // incomplete type and the other is a pointer to a qualified or unqualified
  8430. // version of void...
  8431. if (lhptee->isVoidType()) {
  8432. if (rhptee->isIncompleteOrObjectType())
  8433. return ConvTy;
  8434. // As an extension, we allow cast to/from void* to function pointer.
  8435. assert(rhptee->isFunctionType());
  8436. return Sema::FunctionVoidPointer;
  8437. }
  8438. if (rhptee->isVoidType()) {
  8439. if (lhptee->isIncompleteOrObjectType())
  8440. return ConvTy;
  8441. // As an extension, we allow cast to/from void* to function pointer.
  8442. assert(lhptee->isFunctionType());
  8443. return Sema::FunctionVoidPointer;
  8444. }
  8445. if (!S.Diags.isIgnored(
  8446. diag::warn_typecheck_convert_incompatible_function_pointer_strict,
  8447. Loc) &&
  8448. RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
  8449. !S.IsFunctionConversion(RHSType, LHSType, RHSType))
  8450. return Sema::IncompatibleFunctionPointerStrict;
  8451. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  8452. // unqualified versions of compatible types, ...
  8453. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  8454. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  8455. // Check if the pointee types are compatible ignoring the sign.
  8456. // We explicitly check for char so that we catch "char" vs
  8457. // "unsigned char" on systems where "char" is unsigned.
  8458. if (lhptee->isCharType())
  8459. ltrans = S.Context.UnsignedCharTy;
  8460. else if (lhptee->hasSignedIntegerRepresentation())
  8461. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  8462. if (rhptee->isCharType())
  8463. rtrans = S.Context.UnsignedCharTy;
  8464. else if (rhptee->hasSignedIntegerRepresentation())
  8465. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  8466. if (ltrans == rtrans) {
  8467. // Types are compatible ignoring the sign. Qualifier incompatibility
  8468. // takes priority over sign incompatibility because the sign
  8469. // warning can be disabled.
  8470. if (ConvTy != Sema::Compatible)
  8471. return ConvTy;
  8472. return Sema::IncompatiblePointerSign;
  8473. }
  8474. // If we are a multi-level pointer, it's possible that our issue is simply
  8475. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  8476. // the eventual target type is the same and the pointers have the same
  8477. // level of indirection, this must be the issue.
  8478. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  8479. do {
  8480. std::tie(lhptee, lhq) =
  8481. cast<PointerType>(lhptee)->getPointeeType().split().asPair();
  8482. std::tie(rhptee, rhq) =
  8483. cast<PointerType>(rhptee)->getPointeeType().split().asPair();
  8484. // Inconsistent address spaces at this point is invalid, even if the
  8485. // address spaces would be compatible.
  8486. // FIXME: This doesn't catch address space mismatches for pointers of
  8487. // different nesting levels, like:
  8488. // __local int *** a;
  8489. // int ** b = a;
  8490. // It's not clear how to actually determine when such pointers are
  8491. // invalidly incompatible.
  8492. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  8493. return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
  8494. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  8495. if (lhptee == rhptee)
  8496. return Sema::IncompatibleNestedPointerQualifiers;
  8497. }
  8498. // General pointer incompatibility takes priority over qualifiers.
  8499. if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
  8500. return Sema::IncompatibleFunctionPointer;
  8501. return Sema::IncompatiblePointer;
  8502. }
  8503. if (!S.getLangOpts().CPlusPlus &&
  8504. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  8505. return Sema::IncompatibleFunctionPointer;
  8506. if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
  8507. return Sema::IncompatibleFunctionPointer;
  8508. return ConvTy;
  8509. }
  8510. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  8511. /// block pointer types are compatible or whether a block and normal pointer
  8512. /// are compatible. It is more restrict than comparing two function pointer
  8513. // types.
  8514. static Sema::AssignConvertType
  8515. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  8516. QualType RHSType) {
  8517. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  8518. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  8519. QualType lhptee, rhptee;
  8520. // get the "pointed to" type (ignoring qualifiers at the top level)
  8521. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  8522. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  8523. // In C++, the types have to match exactly.
  8524. if (S.getLangOpts().CPlusPlus)
  8525. return Sema::IncompatibleBlockPointer;
  8526. Sema::AssignConvertType ConvTy = Sema::Compatible;
  8527. // For blocks we enforce that qualifiers are identical.
  8528. Qualifiers LQuals = lhptee.getLocalQualifiers();
  8529. Qualifiers RQuals = rhptee.getLocalQualifiers();
  8530. if (S.getLangOpts().OpenCL) {
  8531. LQuals.removeAddressSpace();
  8532. RQuals.removeAddressSpace();
  8533. }
  8534. if (LQuals != RQuals)
  8535. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  8536. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  8537. // assignment.
  8538. // The current behavior is similar to C++ lambdas. A block might be
  8539. // assigned to a variable iff its return type and parameters are compatible
  8540. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  8541. // an assignment. Presumably it should behave in way that a function pointer
  8542. // assignment does in C, so for each parameter and return type:
  8543. // * CVR and address space of LHS should be a superset of CVR and address
  8544. // space of RHS.
  8545. // * unqualified types should be compatible.
  8546. if (S.getLangOpts().OpenCL) {
  8547. if (!S.Context.typesAreBlockPointerCompatible(
  8548. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  8549. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  8550. return Sema::IncompatibleBlockPointer;
  8551. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  8552. return Sema::IncompatibleBlockPointer;
  8553. return ConvTy;
  8554. }
  8555. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  8556. /// for assignment compatibility.
  8557. static Sema::AssignConvertType
  8558. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  8559. QualType RHSType) {
  8560. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  8561. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  8562. if (LHSType->isObjCBuiltinType()) {
  8563. // Class is not compatible with ObjC object pointers.
  8564. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  8565. !RHSType->isObjCQualifiedClassType())
  8566. return Sema::IncompatiblePointer;
  8567. return Sema::Compatible;
  8568. }
  8569. if (RHSType->isObjCBuiltinType()) {
  8570. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  8571. !LHSType->isObjCQualifiedClassType())
  8572. return Sema::IncompatiblePointer;
  8573. return Sema::Compatible;
  8574. }
  8575. QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
  8576. QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
  8577. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  8578. // make an exception for id<P>
  8579. !LHSType->isObjCQualifiedIdType())
  8580. return Sema::CompatiblePointerDiscardsQualifiers;
  8581. if (S.Context.typesAreCompatible(LHSType, RHSType))
  8582. return Sema::Compatible;
  8583. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  8584. return Sema::IncompatibleObjCQualifiedId;
  8585. return Sema::IncompatiblePointer;
  8586. }
  8587. Sema::AssignConvertType
  8588. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  8589. QualType LHSType, QualType RHSType) {
  8590. // Fake up an opaque expression. We don't actually care about what
  8591. // cast operations are required, so if CheckAssignmentConstraints
  8592. // adds casts to this they'll be wasted, but fortunately that doesn't
  8593. // usually happen on valid code.
  8594. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
  8595. ExprResult RHSPtr = &RHSExpr;
  8596. CastKind K;
  8597. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  8598. }
  8599. /// This helper function returns true if QT is a vector type that has element
  8600. /// type ElementType.
  8601. static bool isVector(QualType QT, QualType ElementType) {
  8602. if (const VectorType *VT = QT->getAs<VectorType>())
  8603. return VT->getElementType().getCanonicalType() == ElementType;
  8604. return false;
  8605. }
  8606. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  8607. /// has code to accommodate several GCC extensions when type checking
  8608. /// pointers. Here are some objectionable examples that GCC considers warnings:
  8609. ///
  8610. /// int a, *pint;
  8611. /// short *pshort;
  8612. /// struct foo *pfoo;
  8613. ///
  8614. /// pint = pshort; // warning: assignment from incompatible pointer type
  8615. /// a = pint; // warning: assignment makes integer from pointer without a cast
  8616. /// pint = a; // warning: assignment makes pointer from integer without a cast
  8617. /// pint = pfoo; // warning: assignment from incompatible pointer type
  8618. ///
  8619. /// As a result, the code for dealing with pointers is more complex than the
  8620. /// C99 spec dictates.
  8621. ///
  8622. /// Sets 'Kind' for any result kind except Incompatible.
  8623. Sema::AssignConvertType
  8624. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  8625. CastKind &Kind, bool ConvertRHS) {
  8626. QualType RHSType = RHS.get()->getType();
  8627. QualType OrigLHSType = LHSType;
  8628. // Get canonical types. We're not formatting these types, just comparing
  8629. // them.
  8630. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  8631. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  8632. // Common case: no conversion required.
  8633. if (LHSType == RHSType) {
  8634. Kind = CK_NoOp;
  8635. return Compatible;
  8636. }
  8637. // If the LHS has an __auto_type, there are no additional type constraints
  8638. // to be worried about.
  8639. if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
  8640. if (AT->isGNUAutoType()) {
  8641. Kind = CK_NoOp;
  8642. return Compatible;
  8643. }
  8644. }
  8645. // If we have an atomic type, try a non-atomic assignment, then just add an
  8646. // atomic qualification step.
  8647. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  8648. Sema::AssignConvertType result =
  8649. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  8650. if (result != Compatible)
  8651. return result;
  8652. if (Kind != CK_NoOp && ConvertRHS)
  8653. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  8654. Kind = CK_NonAtomicToAtomic;
  8655. return Compatible;
  8656. }
  8657. // If the left-hand side is a reference type, then we are in a
  8658. // (rare!) case where we've allowed the use of references in C,
  8659. // e.g., as a parameter type in a built-in function. In this case,
  8660. // just make sure that the type referenced is compatible with the
  8661. // right-hand side type. The caller is responsible for adjusting
  8662. // LHSType so that the resulting expression does not have reference
  8663. // type.
  8664. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  8665. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  8666. Kind = CK_LValueBitCast;
  8667. return Compatible;
  8668. }
  8669. return Incompatible;
  8670. }
  8671. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  8672. // to the same ExtVector type.
  8673. if (LHSType->isExtVectorType()) {
  8674. if (RHSType->isExtVectorType())
  8675. return Incompatible;
  8676. if (RHSType->isArithmeticType()) {
  8677. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  8678. if (ConvertRHS)
  8679. RHS = prepareVectorSplat(LHSType, RHS.get());
  8680. Kind = CK_VectorSplat;
  8681. return Compatible;
  8682. }
  8683. }
  8684. // Conversions to or from vector type.
  8685. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  8686. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  8687. // Allow assignments of an AltiVec vector type to an equivalent GCC
  8688. // vector type and vice versa
  8689. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  8690. Kind = CK_BitCast;
  8691. return Compatible;
  8692. }
  8693. // If we are allowing lax vector conversions, and LHS and RHS are both
  8694. // vectors, the total size only needs to be the same. This is a bitcast;
  8695. // no bits are changed but the result type is different.
  8696. if (isLaxVectorConversion(RHSType, LHSType)) {
  8697. // The default for lax vector conversions with Altivec vectors will
  8698. // change, so if we are converting between vector types where
  8699. // at least one is an Altivec vector, emit a warning.
  8700. if (anyAltivecTypes(RHSType, LHSType) &&
  8701. !areSameVectorElemTypes(RHSType, LHSType))
  8702. Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
  8703. << RHSType << LHSType;
  8704. Kind = CK_BitCast;
  8705. return IncompatibleVectors;
  8706. }
  8707. }
  8708. // When the RHS comes from another lax conversion (e.g. binops between
  8709. // scalars and vectors) the result is canonicalized as a vector. When the
  8710. // LHS is also a vector, the lax is allowed by the condition above. Handle
  8711. // the case where LHS is a scalar.
  8712. if (LHSType->isScalarType()) {
  8713. const VectorType *VecType = RHSType->getAs<VectorType>();
  8714. if (VecType && VecType->getNumElements() == 1 &&
  8715. isLaxVectorConversion(RHSType, LHSType)) {
  8716. if (VecType->getVectorKind() == VectorType::AltiVecVector)
  8717. Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
  8718. << RHSType << LHSType;
  8719. ExprResult *VecExpr = &RHS;
  8720. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  8721. Kind = CK_BitCast;
  8722. return Compatible;
  8723. }
  8724. }
  8725. // Allow assignments between fixed-length and sizeless SVE vectors.
  8726. if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
  8727. (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
  8728. if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
  8729. Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
  8730. Kind = CK_BitCast;
  8731. return Compatible;
  8732. }
  8733. return Incompatible;
  8734. }
  8735. // Diagnose attempts to convert between __ibm128, __float128 and long double
  8736. // where such conversions currently can't be handled.
  8737. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  8738. return Incompatible;
  8739. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  8740. // discards the imaginary part.
  8741. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  8742. !LHSType->getAs<ComplexType>())
  8743. return Incompatible;
  8744. // Arithmetic conversions.
  8745. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  8746. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  8747. if (ConvertRHS)
  8748. Kind = PrepareScalarCast(RHS, LHSType);
  8749. return Compatible;
  8750. }
  8751. // Conversions to normal pointers.
  8752. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  8753. // U* -> T*
  8754. if (isa<PointerType>(RHSType)) {
  8755. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  8756. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  8757. if (AddrSpaceL != AddrSpaceR)
  8758. Kind = CK_AddressSpaceConversion;
  8759. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  8760. Kind = CK_NoOp;
  8761. else
  8762. Kind = CK_BitCast;
  8763. return checkPointerTypesForAssignment(*this, LHSType, RHSType,
  8764. RHS.get()->getBeginLoc());
  8765. }
  8766. // int -> T*
  8767. if (RHSType->isIntegerType()) {
  8768. Kind = CK_IntegralToPointer; // FIXME: null?
  8769. return IntToPointer;
  8770. }
  8771. // C pointers are not compatible with ObjC object pointers,
  8772. // with two exceptions:
  8773. if (isa<ObjCObjectPointerType>(RHSType)) {
  8774. // - conversions to void*
  8775. if (LHSPointer->getPointeeType()->isVoidType()) {
  8776. Kind = CK_BitCast;
  8777. return Compatible;
  8778. }
  8779. // - conversions from 'Class' to the redefinition type
  8780. if (RHSType->isObjCClassType() &&
  8781. Context.hasSameType(LHSType,
  8782. Context.getObjCClassRedefinitionType())) {
  8783. Kind = CK_BitCast;
  8784. return Compatible;
  8785. }
  8786. Kind = CK_BitCast;
  8787. return IncompatiblePointer;
  8788. }
  8789. // U^ -> void*
  8790. if (RHSType->getAs<BlockPointerType>()) {
  8791. if (LHSPointer->getPointeeType()->isVoidType()) {
  8792. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  8793. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  8794. ->getPointeeType()
  8795. .getAddressSpace();
  8796. Kind =
  8797. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  8798. return Compatible;
  8799. }
  8800. }
  8801. return Incompatible;
  8802. }
  8803. // Conversions to block pointers.
  8804. if (isa<BlockPointerType>(LHSType)) {
  8805. // U^ -> T^
  8806. if (RHSType->isBlockPointerType()) {
  8807. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  8808. ->getPointeeType()
  8809. .getAddressSpace();
  8810. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  8811. ->getPointeeType()
  8812. .getAddressSpace();
  8813. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  8814. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  8815. }
  8816. // int or null -> T^
  8817. if (RHSType->isIntegerType()) {
  8818. Kind = CK_IntegralToPointer; // FIXME: null
  8819. return IntToBlockPointer;
  8820. }
  8821. // id -> T^
  8822. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  8823. Kind = CK_AnyPointerToBlockPointerCast;
  8824. return Compatible;
  8825. }
  8826. // void* -> T^
  8827. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  8828. if (RHSPT->getPointeeType()->isVoidType()) {
  8829. Kind = CK_AnyPointerToBlockPointerCast;
  8830. return Compatible;
  8831. }
  8832. return Incompatible;
  8833. }
  8834. // Conversions to Objective-C pointers.
  8835. if (isa<ObjCObjectPointerType>(LHSType)) {
  8836. // A* -> B*
  8837. if (RHSType->isObjCObjectPointerType()) {
  8838. Kind = CK_BitCast;
  8839. Sema::AssignConvertType result =
  8840. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  8841. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  8842. result == Compatible &&
  8843. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  8844. result = IncompatibleObjCWeakRef;
  8845. return result;
  8846. }
  8847. // int or null -> A*
  8848. if (RHSType->isIntegerType()) {
  8849. Kind = CK_IntegralToPointer; // FIXME: null
  8850. return IntToPointer;
  8851. }
  8852. // In general, C pointers are not compatible with ObjC object pointers,
  8853. // with two exceptions:
  8854. if (isa<PointerType>(RHSType)) {
  8855. Kind = CK_CPointerToObjCPointerCast;
  8856. // - conversions from 'void*'
  8857. if (RHSType->isVoidPointerType()) {
  8858. return Compatible;
  8859. }
  8860. // - conversions to 'Class' from its redefinition type
  8861. if (LHSType->isObjCClassType() &&
  8862. Context.hasSameType(RHSType,
  8863. Context.getObjCClassRedefinitionType())) {
  8864. return Compatible;
  8865. }
  8866. return IncompatiblePointer;
  8867. }
  8868. // Only under strict condition T^ is compatible with an Objective-C pointer.
  8869. if (RHSType->isBlockPointerType() &&
  8870. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  8871. if (ConvertRHS)
  8872. maybeExtendBlockObject(RHS);
  8873. Kind = CK_BlockPointerToObjCPointerCast;
  8874. return Compatible;
  8875. }
  8876. return Incompatible;
  8877. }
  8878. // Conversions from pointers that are not covered by the above.
  8879. if (isa<PointerType>(RHSType)) {
  8880. // T* -> _Bool
  8881. if (LHSType == Context.BoolTy) {
  8882. Kind = CK_PointerToBoolean;
  8883. return Compatible;
  8884. }
  8885. // T* -> int
  8886. if (LHSType->isIntegerType()) {
  8887. Kind = CK_PointerToIntegral;
  8888. return PointerToInt;
  8889. }
  8890. return Incompatible;
  8891. }
  8892. // Conversions from Objective-C pointers that are not covered by the above.
  8893. if (isa<ObjCObjectPointerType>(RHSType)) {
  8894. // T* -> _Bool
  8895. if (LHSType == Context.BoolTy) {
  8896. Kind = CK_PointerToBoolean;
  8897. return Compatible;
  8898. }
  8899. // T* -> int
  8900. if (LHSType->isIntegerType()) {
  8901. Kind = CK_PointerToIntegral;
  8902. return PointerToInt;
  8903. }
  8904. return Incompatible;
  8905. }
  8906. // struct A -> struct B
  8907. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  8908. if (Context.typesAreCompatible(LHSType, RHSType)) {
  8909. Kind = CK_NoOp;
  8910. return Compatible;
  8911. }
  8912. }
  8913. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  8914. Kind = CK_IntToOCLSampler;
  8915. return Compatible;
  8916. }
  8917. return Incompatible;
  8918. }
  8919. /// Constructs a transparent union from an expression that is
  8920. /// used to initialize the transparent union.
  8921. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  8922. ExprResult &EResult, QualType UnionType,
  8923. FieldDecl *Field) {
  8924. // Build an initializer list that designates the appropriate member
  8925. // of the transparent union.
  8926. Expr *E = EResult.get();
  8927. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  8928. E, SourceLocation());
  8929. Initializer->setType(UnionType);
  8930. Initializer->setInitializedFieldInUnion(Field);
  8931. // Build a compound literal constructing a value of the transparent
  8932. // union type from this initializer list.
  8933. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  8934. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  8935. VK_PRValue, Initializer, false);
  8936. }
  8937. Sema::AssignConvertType
  8938. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  8939. ExprResult &RHS) {
  8940. QualType RHSType = RHS.get()->getType();
  8941. // If the ArgType is a Union type, we want to handle a potential
  8942. // transparent_union GCC extension.
  8943. const RecordType *UT = ArgType->getAsUnionType();
  8944. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  8945. return Incompatible;
  8946. // The field to initialize within the transparent union.
  8947. RecordDecl *UD = UT->getDecl();
  8948. FieldDecl *InitField = nullptr;
  8949. // It's compatible if the expression matches any of the fields.
  8950. for (auto *it : UD->fields()) {
  8951. if (it->getType()->isPointerType()) {
  8952. // If the transparent union contains a pointer type, we allow:
  8953. // 1) void pointer
  8954. // 2) null pointer constant
  8955. if (RHSType->isPointerType())
  8956. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  8957. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  8958. InitField = it;
  8959. break;
  8960. }
  8961. if (RHS.get()->isNullPointerConstant(Context,
  8962. Expr::NPC_ValueDependentIsNull)) {
  8963. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  8964. CK_NullToPointer);
  8965. InitField = it;
  8966. break;
  8967. }
  8968. }
  8969. CastKind Kind;
  8970. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  8971. == Compatible) {
  8972. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  8973. InitField = it;
  8974. break;
  8975. }
  8976. }
  8977. if (!InitField)
  8978. return Incompatible;
  8979. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  8980. return Compatible;
  8981. }
  8982. Sema::AssignConvertType
  8983. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  8984. bool Diagnose,
  8985. bool DiagnoseCFAudited,
  8986. bool ConvertRHS) {
  8987. // We need to be able to tell the caller whether we diagnosed a problem, if
  8988. // they ask us to issue diagnostics.
  8989. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  8990. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  8991. // we can't avoid *all* modifications at the moment, so we need some somewhere
  8992. // to put the updated value.
  8993. ExprResult LocalRHS = CallerRHS;
  8994. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  8995. if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
  8996. if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
  8997. if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  8998. !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  8999. Diag(RHS.get()->getExprLoc(),
  9000. diag::warn_noderef_to_dereferenceable_pointer)
  9001. << RHS.get()->getSourceRange();
  9002. }
  9003. }
  9004. }
  9005. if (getLangOpts().CPlusPlus) {
  9006. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  9007. // C++ 5.17p3: If the left operand is not of class type, the
  9008. // expression is implicitly converted (C++ 4) to the
  9009. // cv-unqualified type of the left operand.
  9010. QualType RHSType = RHS.get()->getType();
  9011. if (Diagnose) {
  9012. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  9013. AA_Assigning);
  9014. } else {
  9015. ImplicitConversionSequence ICS =
  9016. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  9017. /*SuppressUserConversions=*/false,
  9018. AllowedExplicit::None,
  9019. /*InOverloadResolution=*/false,
  9020. /*CStyle=*/false,
  9021. /*AllowObjCWritebackConversion=*/false);
  9022. if (ICS.isFailure())
  9023. return Incompatible;
  9024. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  9025. ICS, AA_Assigning);
  9026. }
  9027. if (RHS.isInvalid())
  9028. return Incompatible;
  9029. Sema::AssignConvertType result = Compatible;
  9030. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  9031. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  9032. result = IncompatibleObjCWeakRef;
  9033. return result;
  9034. }
  9035. // FIXME: Currently, we fall through and treat C++ classes like C
  9036. // structures.
  9037. // FIXME: We also fall through for atomics; not sure what should
  9038. // happen there, though.
  9039. } else if (RHS.get()->getType() == Context.OverloadTy) {
  9040. // As a set of extensions to C, we support overloading on functions. These
  9041. // functions need to be resolved here.
  9042. DeclAccessPair DAP;
  9043. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  9044. RHS.get(), LHSType, /*Complain=*/false, DAP))
  9045. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  9046. else
  9047. return Incompatible;
  9048. }
  9049. // This check seems unnatural, however it is necessary to ensure the proper
  9050. // conversion of functions/arrays. If the conversion were done for all
  9051. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  9052. // expressions that suppress this implicit conversion (&, sizeof). This needs
  9053. // to happen before we check for null pointer conversions because C does not
  9054. // undergo the same implicit conversions as C++ does above (by the calls to
  9055. // TryImplicitConversion() and PerformImplicitConversion()) which insert the
  9056. // lvalue to rvalue cast before checking for null pointer constraints. This
  9057. // addresses code like: nullptr_t val; int *ptr; ptr = val;
  9058. //
  9059. // Suppress this for references: C++ 8.5.3p5.
  9060. if (!LHSType->isReferenceType()) {
  9061. // FIXME: We potentially allocate here even if ConvertRHS is false.
  9062. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  9063. if (RHS.isInvalid())
  9064. return Incompatible;
  9065. }
  9066. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  9067. // a null pointer constant.
  9068. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  9069. LHSType->isBlockPointerType()) &&
  9070. RHS.get()->isNullPointerConstant(Context,
  9071. Expr::NPC_ValueDependentIsNull)) {
  9072. if (Diagnose || ConvertRHS) {
  9073. CastKind Kind;
  9074. CXXCastPath Path;
  9075. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  9076. /*IgnoreBaseAccess=*/false, Diagnose);
  9077. if (ConvertRHS)
  9078. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
  9079. }
  9080. return Compatible;
  9081. }
  9082. // OpenCL queue_t type assignment.
  9083. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  9084. Context, Expr::NPC_ValueDependentIsNull)) {
  9085. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9086. return Compatible;
  9087. }
  9088. CastKind Kind;
  9089. Sema::AssignConvertType result =
  9090. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  9091. // C99 6.5.16.1p2: The value of the right operand is converted to the
  9092. // type of the assignment expression.
  9093. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  9094. // so that we can use references in built-in functions even in C.
  9095. // The getNonReferenceType() call makes sure that the resulting expression
  9096. // does not have reference type.
  9097. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  9098. QualType Ty = LHSType.getNonLValueExprType(Context);
  9099. Expr *E = RHS.get();
  9100. // Check for various Objective-C errors. If we are not reporting
  9101. // diagnostics and just checking for errors, e.g., during overload
  9102. // resolution, return Incompatible to indicate the failure.
  9103. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  9104. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  9105. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  9106. if (!Diagnose)
  9107. return Incompatible;
  9108. }
  9109. if (getLangOpts().ObjC &&
  9110. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  9111. E->getType(), E, Diagnose) ||
  9112. CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
  9113. if (!Diagnose)
  9114. return Incompatible;
  9115. // Replace the expression with a corrected version and continue so we
  9116. // can find further errors.
  9117. RHS = E;
  9118. return Compatible;
  9119. }
  9120. if (ConvertRHS)
  9121. RHS = ImpCastExprToType(E, Ty, Kind);
  9122. }
  9123. return result;
  9124. }
  9125. namespace {
  9126. /// The original operand to an operator, prior to the application of the usual
  9127. /// arithmetic conversions and converting the arguments of a builtin operator
  9128. /// candidate.
  9129. struct OriginalOperand {
  9130. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  9131. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  9132. Op = MTE->getSubExpr();
  9133. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  9134. Op = BTE->getSubExpr();
  9135. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  9136. Orig = ICE->getSubExprAsWritten();
  9137. Conversion = ICE->getConversionFunction();
  9138. }
  9139. }
  9140. QualType getType() const { return Orig->getType(); }
  9141. Expr *Orig;
  9142. NamedDecl *Conversion;
  9143. };
  9144. }
  9145. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  9146. ExprResult &RHS) {
  9147. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  9148. Diag(Loc, diag::err_typecheck_invalid_operands)
  9149. << OrigLHS.getType() << OrigRHS.getType()
  9150. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9151. // If a user-defined conversion was applied to either of the operands prior
  9152. // to applying the built-in operator rules, tell the user about it.
  9153. if (OrigLHS.Conversion) {
  9154. Diag(OrigLHS.Conversion->getLocation(),
  9155. diag::note_typecheck_invalid_operands_converted)
  9156. << 0 << LHS.get()->getType();
  9157. }
  9158. if (OrigRHS.Conversion) {
  9159. Diag(OrigRHS.Conversion->getLocation(),
  9160. diag::note_typecheck_invalid_operands_converted)
  9161. << 1 << RHS.get()->getType();
  9162. }
  9163. return QualType();
  9164. }
  9165. // Diagnose cases where a scalar was implicitly converted to a vector and
  9166. // diagnose the underlying types. Otherwise, diagnose the error
  9167. // as invalid vector logical operands for non-C++ cases.
  9168. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  9169. ExprResult &RHS) {
  9170. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  9171. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  9172. bool LHSNatVec = LHSType->isVectorType();
  9173. bool RHSNatVec = RHSType->isVectorType();
  9174. if (!(LHSNatVec && RHSNatVec)) {
  9175. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  9176. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  9177. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  9178. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  9179. << Vector->getSourceRange();
  9180. return QualType();
  9181. }
  9182. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  9183. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  9184. << RHS.get()->getSourceRange();
  9185. return QualType();
  9186. }
  9187. /// Try to convert a value of non-vector type to a vector type by converting
  9188. /// the type to the element type of the vector and then performing a splat.
  9189. /// If the language is OpenCL, we only use conversions that promote scalar
  9190. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  9191. /// for float->int.
  9192. ///
  9193. /// OpenCL V2.0 6.2.6.p2:
  9194. /// An error shall occur if any scalar operand type has greater rank
  9195. /// than the type of the vector element.
  9196. ///
  9197. /// \param scalar - if non-null, actually perform the conversions
  9198. /// \return true if the operation fails (but without diagnosing the failure)
  9199. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  9200. QualType scalarTy,
  9201. QualType vectorEltTy,
  9202. QualType vectorTy,
  9203. unsigned &DiagID) {
  9204. // The conversion to apply to the scalar before splatting it,
  9205. // if necessary.
  9206. CastKind scalarCast = CK_NoOp;
  9207. if (vectorEltTy->isIntegralType(S.Context)) {
  9208. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  9209. (scalarTy->isIntegerType() &&
  9210. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  9211. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  9212. return true;
  9213. }
  9214. if (!scalarTy->isIntegralType(S.Context))
  9215. return true;
  9216. scalarCast = CK_IntegralCast;
  9217. } else if (vectorEltTy->isRealFloatingType()) {
  9218. if (scalarTy->isRealFloatingType()) {
  9219. if (S.getLangOpts().OpenCL &&
  9220. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  9221. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  9222. return true;
  9223. }
  9224. scalarCast = CK_FloatingCast;
  9225. }
  9226. else if (scalarTy->isIntegralType(S.Context))
  9227. scalarCast = CK_IntegralToFloating;
  9228. else
  9229. return true;
  9230. } else {
  9231. return true;
  9232. }
  9233. // Adjust scalar if desired.
  9234. if (scalar) {
  9235. if (scalarCast != CK_NoOp)
  9236. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  9237. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  9238. }
  9239. return false;
  9240. }
  9241. /// Convert vector E to a vector with the same number of elements but different
  9242. /// element type.
  9243. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  9244. const auto *VecTy = E->getType()->getAs<VectorType>();
  9245. assert(VecTy && "Expression E must be a vector");
  9246. QualType NewVecTy =
  9247. VecTy->isExtVectorType()
  9248. ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
  9249. : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
  9250. VecTy->getVectorKind());
  9251. // Look through the implicit cast. Return the subexpression if its type is
  9252. // NewVecTy.
  9253. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  9254. if (ICE->getSubExpr()->getType() == NewVecTy)
  9255. return ICE->getSubExpr();
  9256. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  9257. return S.ImpCastExprToType(E, NewVecTy, Cast);
  9258. }
  9259. /// Test if a (constant) integer Int can be casted to another integer type
  9260. /// IntTy without losing precision.
  9261. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  9262. QualType OtherIntTy) {
  9263. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  9264. // Reject cases where the value of the Int is unknown as that would
  9265. // possibly cause truncation, but accept cases where the scalar can be
  9266. // demoted without loss of precision.
  9267. Expr::EvalResult EVResult;
  9268. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  9269. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  9270. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  9271. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  9272. if (CstInt) {
  9273. // If the scalar is constant and is of a higher order and has more active
  9274. // bits that the vector element type, reject it.
  9275. llvm::APSInt Result = EVResult.Val.getInt();
  9276. unsigned NumBits = IntSigned
  9277. ? (Result.isNegative() ? Result.getMinSignedBits()
  9278. : Result.getActiveBits())
  9279. : Result.getActiveBits();
  9280. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  9281. return true;
  9282. // If the signedness of the scalar type and the vector element type
  9283. // differs and the number of bits is greater than that of the vector
  9284. // element reject it.
  9285. return (IntSigned != OtherIntSigned &&
  9286. NumBits > S.Context.getIntWidth(OtherIntTy));
  9287. }
  9288. // Reject cases where the value of the scalar is not constant and it's
  9289. // order is greater than that of the vector element type.
  9290. return (Order < 0);
  9291. }
  9292. /// Test if a (constant) integer Int can be casted to floating point type
  9293. /// FloatTy without losing precision.
  9294. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  9295. QualType FloatTy) {
  9296. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  9297. // Determine if the integer constant can be expressed as a floating point
  9298. // number of the appropriate type.
  9299. Expr::EvalResult EVResult;
  9300. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  9301. uint64_t Bits = 0;
  9302. if (CstInt) {
  9303. // Reject constants that would be truncated if they were converted to
  9304. // the floating point type. Test by simple to/from conversion.
  9305. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  9306. // could be avoided if there was a convertFromAPInt method
  9307. // which could signal back if implicit truncation occurred.
  9308. llvm::APSInt Result = EVResult.Val.getInt();
  9309. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  9310. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  9311. llvm::APFloat::rmTowardZero);
  9312. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  9313. !IntTy->hasSignedIntegerRepresentation());
  9314. bool Ignored = false;
  9315. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  9316. &Ignored);
  9317. if (Result != ConvertBack)
  9318. return true;
  9319. } else {
  9320. // Reject types that cannot be fully encoded into the mantissa of
  9321. // the float.
  9322. Bits = S.Context.getTypeSize(IntTy);
  9323. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  9324. S.Context.getFloatTypeSemantics(FloatTy));
  9325. if (Bits > FloatPrec)
  9326. return true;
  9327. }
  9328. return false;
  9329. }
  9330. /// Attempt to convert and splat Scalar into a vector whose types matches
  9331. /// Vector following GCC conversion rules. The rule is that implicit
  9332. /// conversion can occur when Scalar can be casted to match Vector's element
  9333. /// type without causing truncation of Scalar.
  9334. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  9335. ExprResult *Vector) {
  9336. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  9337. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  9338. QualType VectorEltTy;
  9339. if (const auto *VT = VectorTy->getAs<VectorType>()) {
  9340. assert(!isa<ExtVectorType>(VT) &&
  9341. "ExtVectorTypes should not be handled here!");
  9342. VectorEltTy = VT->getElementType();
  9343. } else if (VectorTy->isVLSTBuiltinType()) {
  9344. VectorEltTy =
  9345. VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
  9346. } else {
  9347. llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
  9348. }
  9349. // Reject cases where the vector element type or the scalar element type are
  9350. // not integral or floating point types.
  9351. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  9352. return true;
  9353. // The conversion to apply to the scalar before splatting it,
  9354. // if necessary.
  9355. CastKind ScalarCast = CK_NoOp;
  9356. // Accept cases where the vector elements are integers and the scalar is
  9357. // an integer.
  9358. // FIXME: Notionally if the scalar was a floating point value with a precise
  9359. // integral representation, we could cast it to an appropriate integer
  9360. // type and then perform the rest of the checks here. GCC will perform
  9361. // this conversion in some cases as determined by the input language.
  9362. // We should accept it on a language independent basis.
  9363. if (VectorEltTy->isIntegralType(S.Context) &&
  9364. ScalarTy->isIntegralType(S.Context) &&
  9365. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  9366. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  9367. return true;
  9368. ScalarCast = CK_IntegralCast;
  9369. } else if (VectorEltTy->isIntegralType(S.Context) &&
  9370. ScalarTy->isRealFloatingType()) {
  9371. if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
  9372. ScalarCast = CK_FloatingToIntegral;
  9373. else
  9374. return true;
  9375. } else if (VectorEltTy->isRealFloatingType()) {
  9376. if (ScalarTy->isRealFloatingType()) {
  9377. // Reject cases where the scalar type is not a constant and has a higher
  9378. // Order than the vector element type.
  9379. llvm::APFloat Result(0.0);
  9380. // Determine whether this is a constant scalar. In the event that the
  9381. // value is dependent (and thus cannot be evaluated by the constant
  9382. // evaluator), skip the evaluation. This will then diagnose once the
  9383. // expression is instantiated.
  9384. bool CstScalar = Scalar->get()->isValueDependent() ||
  9385. Scalar->get()->EvaluateAsFloat(Result, S.Context);
  9386. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  9387. if (!CstScalar && Order < 0)
  9388. return true;
  9389. // If the scalar cannot be safely casted to the vector element type,
  9390. // reject it.
  9391. if (CstScalar) {
  9392. bool Truncated = false;
  9393. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  9394. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  9395. if (Truncated)
  9396. return true;
  9397. }
  9398. ScalarCast = CK_FloatingCast;
  9399. } else if (ScalarTy->isIntegralType(S.Context)) {
  9400. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  9401. return true;
  9402. ScalarCast = CK_IntegralToFloating;
  9403. } else
  9404. return true;
  9405. } else if (ScalarTy->isEnumeralType())
  9406. return true;
  9407. // Adjust scalar if desired.
  9408. if (Scalar) {
  9409. if (ScalarCast != CK_NoOp)
  9410. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  9411. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  9412. }
  9413. return false;
  9414. }
  9415. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  9416. SourceLocation Loc, bool IsCompAssign,
  9417. bool AllowBothBool,
  9418. bool AllowBoolConversions,
  9419. bool AllowBoolOperation,
  9420. bool ReportInvalid) {
  9421. if (!IsCompAssign) {
  9422. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  9423. if (LHS.isInvalid())
  9424. return QualType();
  9425. }
  9426. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  9427. if (RHS.isInvalid())
  9428. return QualType();
  9429. // For conversion purposes, we ignore any qualifiers.
  9430. // For example, "const float" and "float" are equivalent.
  9431. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  9432. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  9433. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  9434. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  9435. assert(LHSVecType || RHSVecType);
  9436. if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
  9437. (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
  9438. return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
  9439. // AltiVec-style "vector bool op vector bool" combinations are allowed
  9440. // for some operators but not others.
  9441. if (!AllowBothBool &&
  9442. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  9443. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  9444. return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
  9445. // This operation may not be performed on boolean vectors.
  9446. if (!AllowBoolOperation &&
  9447. (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
  9448. return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
  9449. // If the vector types are identical, return.
  9450. if (Context.hasSameType(LHSType, RHSType))
  9451. return Context.getCommonSugaredType(LHSType, RHSType);
  9452. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  9453. if (LHSVecType && RHSVecType &&
  9454. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  9455. if (isa<ExtVectorType>(LHSVecType)) {
  9456. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9457. return LHSType;
  9458. }
  9459. if (!IsCompAssign)
  9460. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9461. return RHSType;
  9462. }
  9463. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  9464. // can be mixed, with the result being the non-bool type. The non-bool
  9465. // operand must have integer element type.
  9466. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  9467. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  9468. (Context.getTypeSize(LHSVecType->getElementType()) ==
  9469. Context.getTypeSize(RHSVecType->getElementType()))) {
  9470. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  9471. LHSVecType->getElementType()->isIntegerType() &&
  9472. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  9473. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9474. return LHSType;
  9475. }
  9476. if (!IsCompAssign &&
  9477. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  9478. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  9479. RHSVecType->getElementType()->isIntegerType()) {
  9480. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9481. return RHSType;
  9482. }
  9483. }
  9484. // Expressions containing fixed-length and sizeless SVE vectors are invalid
  9485. // since the ambiguity can affect the ABI.
  9486. auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
  9487. const VectorType *VecType = SecondType->getAs<VectorType>();
  9488. return FirstType->isSizelessBuiltinType() && VecType &&
  9489. (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  9490. VecType->getVectorKind() ==
  9491. VectorType::SveFixedLengthPredicateVector);
  9492. };
  9493. if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
  9494. Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
  9495. return QualType();
  9496. }
  9497. // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
  9498. // since the ambiguity can affect the ABI.
  9499. auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
  9500. const VectorType *FirstVecType = FirstType->getAs<VectorType>();
  9501. const VectorType *SecondVecType = SecondType->getAs<VectorType>();
  9502. if (FirstVecType && SecondVecType)
  9503. return FirstVecType->getVectorKind() == VectorType::GenericVector &&
  9504. (SecondVecType->getVectorKind() ==
  9505. VectorType::SveFixedLengthDataVector ||
  9506. SecondVecType->getVectorKind() ==
  9507. VectorType::SveFixedLengthPredicateVector);
  9508. return FirstType->isSizelessBuiltinType() && SecondVecType &&
  9509. SecondVecType->getVectorKind() == VectorType::GenericVector;
  9510. };
  9511. if (IsSveGnuConversion(LHSType, RHSType) ||
  9512. IsSveGnuConversion(RHSType, LHSType)) {
  9513. Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
  9514. return QualType();
  9515. }
  9516. // If there's a vector type and a scalar, try to convert the scalar to
  9517. // the vector element type and splat.
  9518. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  9519. if (!RHSVecType) {
  9520. if (isa<ExtVectorType>(LHSVecType)) {
  9521. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  9522. LHSVecType->getElementType(), LHSType,
  9523. DiagID))
  9524. return LHSType;
  9525. } else {
  9526. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  9527. return LHSType;
  9528. }
  9529. }
  9530. if (!LHSVecType) {
  9531. if (isa<ExtVectorType>(RHSVecType)) {
  9532. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  9533. LHSType, RHSVecType->getElementType(),
  9534. RHSType, DiagID))
  9535. return RHSType;
  9536. } else {
  9537. if (LHS.get()->isLValue() ||
  9538. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  9539. return RHSType;
  9540. }
  9541. }
  9542. // FIXME: The code below also handles conversion between vectors and
  9543. // non-scalars, we should break this down into fine grained specific checks
  9544. // and emit proper diagnostics.
  9545. QualType VecType = LHSVecType ? LHSType : RHSType;
  9546. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  9547. QualType OtherType = LHSVecType ? RHSType : LHSType;
  9548. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  9549. if (isLaxVectorConversion(OtherType, VecType)) {
  9550. if (anyAltivecTypes(RHSType, LHSType) &&
  9551. !areSameVectorElemTypes(RHSType, LHSType))
  9552. Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
  9553. // If we're allowing lax vector conversions, only the total (data) size
  9554. // needs to be the same. For non compound assignment, if one of the types is
  9555. // scalar, the result is always the vector type.
  9556. if (!IsCompAssign) {
  9557. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  9558. return VecType;
  9559. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  9560. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  9561. // type. Note that this is already done by non-compound assignments in
  9562. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  9563. // <1 x T> -> T. The result is also a vector type.
  9564. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  9565. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  9566. ExprResult *RHSExpr = &RHS;
  9567. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  9568. return VecType;
  9569. }
  9570. }
  9571. // Okay, the expression is invalid.
  9572. // If there's a non-vector, non-real operand, diagnose that.
  9573. if ((!RHSVecType && !RHSType->isRealType()) ||
  9574. (!LHSVecType && !LHSType->isRealType())) {
  9575. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  9576. << LHSType << RHSType
  9577. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9578. return QualType();
  9579. }
  9580. // OpenCL V1.1 6.2.6.p1:
  9581. // If the operands are of more than one vector type, then an error shall
  9582. // occur. Implicit conversions between vector types are not permitted, per
  9583. // section 6.2.1.
  9584. if (getLangOpts().OpenCL &&
  9585. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  9586. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  9587. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  9588. << RHSType;
  9589. return QualType();
  9590. }
  9591. // If there is a vector type that is not a ExtVector and a scalar, we reach
  9592. // this point if scalar could not be converted to the vector's element type
  9593. // without truncation.
  9594. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  9595. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  9596. QualType Scalar = LHSVecType ? RHSType : LHSType;
  9597. QualType Vector = LHSVecType ? LHSType : RHSType;
  9598. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  9599. Diag(Loc,
  9600. diag::err_typecheck_vector_not_convertable_implict_truncation)
  9601. << ScalarOrVector << Scalar << Vector;
  9602. return QualType();
  9603. }
  9604. // Otherwise, use the generic diagnostic.
  9605. Diag(Loc, DiagID)
  9606. << LHSType << RHSType
  9607. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9608. return QualType();
  9609. }
  9610. QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
  9611. SourceLocation Loc,
  9612. bool IsCompAssign,
  9613. ArithConvKind OperationKind) {
  9614. if (!IsCompAssign) {
  9615. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  9616. if (LHS.isInvalid())
  9617. return QualType();
  9618. }
  9619. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  9620. if (RHS.isInvalid())
  9621. return QualType();
  9622. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  9623. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  9624. const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
  9625. const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
  9626. unsigned DiagID = diag::err_typecheck_invalid_operands;
  9627. if ((OperationKind == ACK_Arithmetic) &&
  9628. ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
  9629. (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
  9630. Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
  9631. << RHS.get()->getSourceRange();
  9632. return QualType();
  9633. }
  9634. if (Context.hasSameType(LHSType, RHSType))
  9635. return LHSType;
  9636. if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
  9637. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  9638. return LHSType;
  9639. }
  9640. if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
  9641. if (LHS.get()->isLValue() ||
  9642. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  9643. return RHSType;
  9644. }
  9645. if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
  9646. (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
  9647. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  9648. << LHSType << RHSType << LHS.get()->getSourceRange()
  9649. << RHS.get()->getSourceRange();
  9650. return QualType();
  9651. }
  9652. if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
  9653. Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
  9654. Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
  9655. Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  9656. << LHSType << RHSType << LHS.get()->getSourceRange()
  9657. << RHS.get()->getSourceRange();
  9658. return QualType();
  9659. }
  9660. if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
  9661. QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
  9662. QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
  9663. bool ScalarOrVector =
  9664. LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
  9665. Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
  9666. << ScalarOrVector << Scalar << Vector;
  9667. return QualType();
  9668. }
  9669. Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
  9670. << RHS.get()->getSourceRange();
  9671. return QualType();
  9672. }
  9673. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  9674. // expression. These are mainly cases where the null pointer is used as an
  9675. // integer instead of a pointer.
  9676. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  9677. SourceLocation Loc, bool IsCompare) {
  9678. // The canonical way to check for a GNU null is with isNullPointerConstant,
  9679. // but we use a bit of a hack here for speed; this is a relatively
  9680. // hot path, and isNullPointerConstant is slow.
  9681. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  9682. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  9683. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  9684. // Avoid analyzing cases where the result will either be invalid (and
  9685. // diagnosed as such) or entirely valid and not something to warn about.
  9686. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  9687. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  9688. return;
  9689. // Comparison operations would not make sense with a null pointer no matter
  9690. // what the other expression is.
  9691. if (!IsCompare) {
  9692. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  9693. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  9694. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  9695. return;
  9696. }
  9697. // The rest of the operations only make sense with a null pointer
  9698. // if the other expression is a pointer.
  9699. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  9700. NonNullType->canDecayToPointerType())
  9701. return;
  9702. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  9703. << LHSNull /* LHS is NULL */ << NonNullType
  9704. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9705. }
  9706. static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
  9707. SourceLocation Loc) {
  9708. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  9709. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  9710. if (!LUE || !RUE)
  9711. return;
  9712. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  9713. RUE->getKind() != UETT_SizeOf)
  9714. return;
  9715. const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
  9716. QualType LHSTy = LHSArg->getType();
  9717. QualType RHSTy;
  9718. if (RUE->isArgumentType())
  9719. RHSTy = RUE->getArgumentType().getNonReferenceType();
  9720. else
  9721. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  9722. if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
  9723. if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
  9724. return;
  9725. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  9726. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  9727. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  9728. S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
  9729. << LHSArgDecl;
  9730. }
  9731. } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
  9732. QualType ArrayElemTy = ArrayTy->getElementType();
  9733. if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
  9734. ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
  9735. RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
  9736. S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
  9737. return;
  9738. S.Diag(Loc, diag::warn_division_sizeof_array)
  9739. << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
  9740. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  9741. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  9742. S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
  9743. << LHSArgDecl;
  9744. }
  9745. S.Diag(Loc, diag::note_precedence_silence) << RHS;
  9746. }
  9747. }
  9748. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  9749. ExprResult &RHS,
  9750. SourceLocation Loc, bool IsDiv) {
  9751. // Check for division/remainder by zero.
  9752. Expr::EvalResult RHSValue;
  9753. if (!RHS.get()->isValueDependent() &&
  9754. RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
  9755. RHSValue.Val.getInt() == 0)
  9756. S.DiagRuntimeBehavior(Loc, RHS.get(),
  9757. S.PDiag(diag::warn_remainder_division_by_zero)
  9758. << IsDiv << RHS.get()->getSourceRange());
  9759. }
  9760. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  9761. SourceLocation Loc,
  9762. bool IsCompAssign, bool IsDiv) {
  9763. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9764. QualType LHSTy = LHS.get()->getType();
  9765. QualType RHSTy = RHS.get()->getType();
  9766. if (LHSTy->isVectorType() || RHSTy->isVectorType())
  9767. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9768. /*AllowBothBool*/ getLangOpts().AltiVec,
  9769. /*AllowBoolConversions*/ false,
  9770. /*AllowBooleanOperation*/ false,
  9771. /*ReportInvalid*/ true);
  9772. if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
  9773. return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9774. ACK_Arithmetic);
  9775. if (!IsDiv &&
  9776. (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
  9777. return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
  9778. // For division, only matrix-by-scalar is supported. Other combinations with
  9779. // matrix types are invalid.
  9780. if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
  9781. return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
  9782. QualType compType = UsualArithmeticConversions(
  9783. LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
  9784. if (LHS.isInvalid() || RHS.isInvalid())
  9785. return QualType();
  9786. if (compType.isNull() || !compType->isArithmeticType())
  9787. return InvalidOperands(Loc, LHS, RHS);
  9788. if (IsDiv) {
  9789. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  9790. DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
  9791. }
  9792. return compType;
  9793. }
  9794. QualType Sema::CheckRemainderOperands(
  9795. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  9796. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9797. if (LHS.get()->getType()->isVectorType() ||
  9798. RHS.get()->getType()->isVectorType()) {
  9799. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9800. RHS.get()->getType()->hasIntegerRepresentation())
  9801. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9802. /*AllowBothBool*/ getLangOpts().AltiVec,
  9803. /*AllowBoolConversions*/ false,
  9804. /*AllowBooleanOperation*/ false,
  9805. /*ReportInvalid*/ true);
  9806. return InvalidOperands(Loc, LHS, RHS);
  9807. }
  9808. if (LHS.get()->getType()->isVLSTBuiltinType() ||
  9809. RHS.get()->getType()->isVLSTBuiltinType()) {
  9810. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9811. RHS.get()->getType()->hasIntegerRepresentation())
  9812. return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9813. ACK_Arithmetic);
  9814. return InvalidOperands(Loc, LHS, RHS);
  9815. }
  9816. QualType compType = UsualArithmeticConversions(
  9817. LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
  9818. if (LHS.isInvalid() || RHS.isInvalid())
  9819. return QualType();
  9820. if (compType.isNull() || !compType->isIntegerType())
  9821. return InvalidOperands(Loc, LHS, RHS);
  9822. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  9823. return compType;
  9824. }
  9825. /// Diagnose invalid arithmetic on two void pointers.
  9826. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  9827. Expr *LHSExpr, Expr *RHSExpr) {
  9828. S.Diag(Loc, S.getLangOpts().CPlusPlus
  9829. ? diag::err_typecheck_pointer_arith_void_type
  9830. : diag::ext_gnu_void_ptr)
  9831. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  9832. << RHSExpr->getSourceRange();
  9833. }
  9834. /// Diagnose invalid arithmetic on a void pointer.
  9835. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  9836. Expr *Pointer) {
  9837. S.Diag(Loc, S.getLangOpts().CPlusPlus
  9838. ? diag::err_typecheck_pointer_arith_void_type
  9839. : diag::ext_gnu_void_ptr)
  9840. << 0 /* one pointer */ << Pointer->getSourceRange();
  9841. }
  9842. /// Diagnose invalid arithmetic on a null pointer.
  9843. ///
  9844. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  9845. /// idiom, which we recognize as a GNU extension.
  9846. ///
  9847. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  9848. Expr *Pointer, bool IsGNUIdiom) {
  9849. if (IsGNUIdiom)
  9850. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  9851. << Pointer->getSourceRange();
  9852. else
  9853. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  9854. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  9855. }
  9856. /// Diagnose invalid subraction on a null pointer.
  9857. ///
  9858. static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
  9859. Expr *Pointer, bool BothNull) {
  9860. // Null - null is valid in C++ [expr.add]p7
  9861. if (BothNull && S.getLangOpts().CPlusPlus)
  9862. return;
  9863. // Is this s a macro from a system header?
  9864. if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
  9865. return;
  9866. S.DiagRuntimeBehavior(Loc, Pointer,
  9867. S.PDiag(diag::warn_pointer_sub_null_ptr)
  9868. << S.getLangOpts().CPlusPlus
  9869. << Pointer->getSourceRange());
  9870. }
  9871. /// Diagnose invalid arithmetic on two function pointers.
  9872. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  9873. Expr *LHS, Expr *RHS) {
  9874. assert(LHS->getType()->isAnyPointerType());
  9875. assert(RHS->getType()->isAnyPointerType());
  9876. S.Diag(Loc, S.getLangOpts().CPlusPlus
  9877. ? diag::err_typecheck_pointer_arith_function_type
  9878. : diag::ext_gnu_ptr_func_arith)
  9879. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  9880. // We only show the second type if it differs from the first.
  9881. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  9882. RHS->getType())
  9883. << RHS->getType()->getPointeeType()
  9884. << LHS->getSourceRange() << RHS->getSourceRange();
  9885. }
  9886. /// Diagnose invalid arithmetic on a function pointer.
  9887. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  9888. Expr *Pointer) {
  9889. assert(Pointer->getType()->isAnyPointerType());
  9890. S.Diag(Loc, S.getLangOpts().CPlusPlus
  9891. ? diag::err_typecheck_pointer_arith_function_type
  9892. : diag::ext_gnu_ptr_func_arith)
  9893. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  9894. << 0 /* one pointer, so only one type */
  9895. << Pointer->getSourceRange();
  9896. }
  9897. /// Emit error if Operand is incomplete pointer type
  9898. ///
  9899. /// \returns True if pointer has incomplete type
  9900. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  9901. Expr *Operand) {
  9902. QualType ResType = Operand->getType();
  9903. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  9904. ResType = ResAtomicType->getValueType();
  9905. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  9906. QualType PointeeTy = ResType->getPointeeType();
  9907. return S.RequireCompleteSizedType(
  9908. Loc, PointeeTy,
  9909. diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
  9910. Operand->getSourceRange());
  9911. }
  9912. /// Check the validity of an arithmetic pointer operand.
  9913. ///
  9914. /// If the operand has pointer type, this code will check for pointer types
  9915. /// which are invalid in arithmetic operations. These will be diagnosed
  9916. /// appropriately, including whether or not the use is supported as an
  9917. /// extension.
  9918. ///
  9919. /// \returns True when the operand is valid to use (even if as an extension).
  9920. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  9921. Expr *Operand) {
  9922. QualType ResType = Operand->getType();
  9923. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  9924. ResType = ResAtomicType->getValueType();
  9925. if (!ResType->isAnyPointerType()) return true;
  9926. QualType PointeeTy = ResType->getPointeeType();
  9927. if (PointeeTy->isVoidType()) {
  9928. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  9929. return !S.getLangOpts().CPlusPlus;
  9930. }
  9931. if (PointeeTy->isFunctionType()) {
  9932. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  9933. return !S.getLangOpts().CPlusPlus;
  9934. }
  9935. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  9936. return true;
  9937. }
  9938. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  9939. /// operands.
  9940. ///
  9941. /// This routine will diagnose any invalid arithmetic on pointer operands much
  9942. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  9943. /// for emitting a single diagnostic even for operations where both LHS and RHS
  9944. /// are (potentially problematic) pointers.
  9945. ///
  9946. /// \returns True when the operand is valid to use (even if as an extension).
  9947. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  9948. Expr *LHSExpr, Expr *RHSExpr) {
  9949. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  9950. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  9951. if (!isLHSPointer && !isRHSPointer) return true;
  9952. QualType LHSPointeeTy, RHSPointeeTy;
  9953. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  9954. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  9955. // if both are pointers check if operation is valid wrt address spaces
  9956. if (isLHSPointer && isRHSPointer) {
  9957. if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
  9958. S.Diag(Loc,
  9959. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9960. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  9961. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  9962. return false;
  9963. }
  9964. }
  9965. // Check for arithmetic on pointers to incomplete types.
  9966. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  9967. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  9968. if (isLHSVoidPtr || isRHSVoidPtr) {
  9969. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  9970. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  9971. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  9972. return !S.getLangOpts().CPlusPlus;
  9973. }
  9974. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  9975. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  9976. if (isLHSFuncPtr || isRHSFuncPtr) {
  9977. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  9978. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  9979. RHSExpr);
  9980. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  9981. return !S.getLangOpts().CPlusPlus;
  9982. }
  9983. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  9984. return false;
  9985. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  9986. return false;
  9987. return true;
  9988. }
  9989. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  9990. /// literal.
  9991. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  9992. Expr *LHSExpr, Expr *RHSExpr) {
  9993. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  9994. Expr* IndexExpr = RHSExpr;
  9995. if (!StrExpr) {
  9996. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  9997. IndexExpr = LHSExpr;
  9998. }
  9999. bool IsStringPlusInt = StrExpr &&
  10000. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  10001. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  10002. return;
  10003. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  10004. Self.Diag(OpLoc, diag::warn_string_plus_int)
  10005. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  10006. // Only print a fixit for "str" + int, not for int + "str".
  10007. if (IndexExpr == RHSExpr) {
  10008. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  10009. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  10010. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  10011. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  10012. << FixItHint::CreateInsertion(EndLoc, "]");
  10013. } else
  10014. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  10015. }
  10016. /// Emit a warning when adding a char literal to a string.
  10017. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  10018. Expr *LHSExpr, Expr *RHSExpr) {
  10019. const Expr *StringRefExpr = LHSExpr;
  10020. const CharacterLiteral *CharExpr =
  10021. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  10022. if (!CharExpr) {
  10023. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  10024. StringRefExpr = RHSExpr;
  10025. }
  10026. if (!CharExpr || !StringRefExpr)
  10027. return;
  10028. const QualType StringType = StringRefExpr->getType();
  10029. // Return if not a PointerType.
  10030. if (!StringType->isAnyPointerType())
  10031. return;
  10032. // Return if not a CharacterType.
  10033. if (!StringType->getPointeeType()->isAnyCharacterType())
  10034. return;
  10035. ASTContext &Ctx = Self.getASTContext();
  10036. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  10037. const QualType CharType = CharExpr->getType();
  10038. if (!CharType->isAnyCharacterType() &&
  10039. CharType->isIntegerType() &&
  10040. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  10041. Self.Diag(OpLoc, diag::warn_string_plus_char)
  10042. << DiagRange << Ctx.CharTy;
  10043. } else {
  10044. Self.Diag(OpLoc, diag::warn_string_plus_char)
  10045. << DiagRange << CharExpr->getType();
  10046. }
  10047. // Only print a fixit for str + char, not for char + str.
  10048. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  10049. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  10050. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  10051. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  10052. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  10053. << FixItHint::CreateInsertion(EndLoc, "]");
  10054. } else {
  10055. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  10056. }
  10057. }
  10058. /// Emit error when two pointers are incompatible.
  10059. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  10060. Expr *LHSExpr, Expr *RHSExpr) {
  10061. assert(LHSExpr->getType()->isAnyPointerType());
  10062. assert(RHSExpr->getType()->isAnyPointerType());
  10063. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  10064. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  10065. << RHSExpr->getSourceRange();
  10066. }
  10067. // C99 6.5.6
  10068. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  10069. SourceLocation Loc, BinaryOperatorKind Opc,
  10070. QualType* CompLHSTy) {
  10071. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  10072. if (LHS.get()->getType()->isVectorType() ||
  10073. RHS.get()->getType()->isVectorType()) {
  10074. QualType compType =
  10075. CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
  10076. /*AllowBothBool*/ getLangOpts().AltiVec,
  10077. /*AllowBoolConversions*/ getLangOpts().ZVector,
  10078. /*AllowBooleanOperation*/ false,
  10079. /*ReportInvalid*/ true);
  10080. if (CompLHSTy) *CompLHSTy = compType;
  10081. return compType;
  10082. }
  10083. if (LHS.get()->getType()->isVLSTBuiltinType() ||
  10084. RHS.get()->getType()->isVLSTBuiltinType()) {
  10085. QualType compType =
  10086. CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
  10087. if (CompLHSTy)
  10088. *CompLHSTy = compType;
  10089. return compType;
  10090. }
  10091. if (LHS.get()->getType()->isConstantMatrixType() ||
  10092. RHS.get()->getType()->isConstantMatrixType()) {
  10093. QualType compType =
  10094. CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
  10095. if (CompLHSTy)
  10096. *CompLHSTy = compType;
  10097. return compType;
  10098. }
  10099. QualType compType = UsualArithmeticConversions(
  10100. LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
  10101. if (LHS.isInvalid() || RHS.isInvalid())
  10102. return QualType();
  10103. // Diagnose "string literal" '+' int and string '+' "char literal".
  10104. if (Opc == BO_Add) {
  10105. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  10106. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  10107. }
  10108. // handle the common case first (both operands are arithmetic).
  10109. if (!compType.isNull() && compType->isArithmeticType()) {
  10110. if (CompLHSTy) *CompLHSTy = compType;
  10111. return compType;
  10112. }
  10113. // Type-checking. Ultimately the pointer's going to be in PExp;
  10114. // note that we bias towards the LHS being the pointer.
  10115. Expr *PExp = LHS.get(), *IExp = RHS.get();
  10116. bool isObjCPointer;
  10117. if (PExp->getType()->isPointerType()) {
  10118. isObjCPointer = false;
  10119. } else if (PExp->getType()->isObjCObjectPointerType()) {
  10120. isObjCPointer = true;
  10121. } else {
  10122. std::swap(PExp, IExp);
  10123. if (PExp->getType()->isPointerType()) {
  10124. isObjCPointer = false;
  10125. } else if (PExp->getType()->isObjCObjectPointerType()) {
  10126. isObjCPointer = true;
  10127. } else {
  10128. return InvalidOperands(Loc, LHS, RHS);
  10129. }
  10130. }
  10131. assert(PExp->getType()->isAnyPointerType());
  10132. if (!IExp->getType()->isIntegerType())
  10133. return InvalidOperands(Loc, LHS, RHS);
  10134. // Adding to a null pointer results in undefined behavior.
  10135. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  10136. Context, Expr::NPC_ValueDependentIsNotNull)) {
  10137. // In C++ adding zero to a null pointer is defined.
  10138. Expr::EvalResult KnownVal;
  10139. if (!getLangOpts().CPlusPlus ||
  10140. (!IExp->isValueDependent() &&
  10141. (!IExp->EvaluateAsInt(KnownVal, Context) ||
  10142. KnownVal.Val.getInt() != 0))) {
  10143. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  10144. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  10145. Context, BO_Add, PExp, IExp);
  10146. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  10147. }
  10148. }
  10149. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  10150. return QualType();
  10151. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  10152. return QualType();
  10153. // Check array bounds for pointer arithemtic
  10154. CheckArrayAccess(PExp, IExp);
  10155. if (CompLHSTy) {
  10156. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  10157. if (LHSTy.isNull()) {
  10158. LHSTy = LHS.get()->getType();
  10159. if (Context.isPromotableIntegerType(LHSTy))
  10160. LHSTy = Context.getPromotedIntegerType(LHSTy);
  10161. }
  10162. *CompLHSTy = LHSTy;
  10163. }
  10164. return PExp->getType();
  10165. }
  10166. // C99 6.5.6
  10167. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  10168. SourceLocation Loc,
  10169. QualType* CompLHSTy) {
  10170. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  10171. if (LHS.get()->getType()->isVectorType() ||
  10172. RHS.get()->getType()->isVectorType()) {
  10173. QualType compType =
  10174. CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
  10175. /*AllowBothBool*/ getLangOpts().AltiVec,
  10176. /*AllowBoolConversions*/ getLangOpts().ZVector,
  10177. /*AllowBooleanOperation*/ false,
  10178. /*ReportInvalid*/ true);
  10179. if (CompLHSTy) *CompLHSTy = compType;
  10180. return compType;
  10181. }
  10182. if (LHS.get()->getType()->isVLSTBuiltinType() ||
  10183. RHS.get()->getType()->isVLSTBuiltinType()) {
  10184. QualType compType =
  10185. CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
  10186. if (CompLHSTy)
  10187. *CompLHSTy = compType;
  10188. return compType;
  10189. }
  10190. if (LHS.get()->getType()->isConstantMatrixType() ||
  10191. RHS.get()->getType()->isConstantMatrixType()) {
  10192. QualType compType =
  10193. CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
  10194. if (CompLHSTy)
  10195. *CompLHSTy = compType;
  10196. return compType;
  10197. }
  10198. QualType compType = UsualArithmeticConversions(
  10199. LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
  10200. if (LHS.isInvalid() || RHS.isInvalid())
  10201. return QualType();
  10202. // Enforce type constraints: C99 6.5.6p3.
  10203. // Handle the common case first (both operands are arithmetic).
  10204. if (!compType.isNull() && compType->isArithmeticType()) {
  10205. if (CompLHSTy) *CompLHSTy = compType;
  10206. return compType;
  10207. }
  10208. // Either ptr - int or ptr - ptr.
  10209. if (LHS.get()->getType()->isAnyPointerType()) {
  10210. QualType lpointee = LHS.get()->getType()->getPointeeType();
  10211. // Diagnose bad cases where we step over interface counts.
  10212. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  10213. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  10214. return QualType();
  10215. // The result type of a pointer-int computation is the pointer type.
  10216. if (RHS.get()->getType()->isIntegerType()) {
  10217. // Subtracting from a null pointer should produce a warning.
  10218. // The last argument to the diagnose call says this doesn't match the
  10219. // GNU int-to-pointer idiom.
  10220. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  10221. Expr::NPC_ValueDependentIsNotNull)) {
  10222. // In C++ adding zero to a null pointer is defined.
  10223. Expr::EvalResult KnownVal;
  10224. if (!getLangOpts().CPlusPlus ||
  10225. (!RHS.get()->isValueDependent() &&
  10226. (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
  10227. KnownVal.Val.getInt() != 0))) {
  10228. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  10229. }
  10230. }
  10231. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  10232. return QualType();
  10233. // Check array bounds for pointer arithemtic
  10234. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  10235. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  10236. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  10237. return LHS.get()->getType();
  10238. }
  10239. // Handle pointer-pointer subtractions.
  10240. if (const PointerType *RHSPTy
  10241. = RHS.get()->getType()->getAs<PointerType>()) {
  10242. QualType rpointee = RHSPTy->getPointeeType();
  10243. if (getLangOpts().CPlusPlus) {
  10244. // Pointee types must be the same: C++ [expr.add]
  10245. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  10246. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  10247. }
  10248. } else {
  10249. // Pointee types must be compatible C99 6.5.6p3
  10250. if (!Context.typesAreCompatible(
  10251. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  10252. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  10253. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  10254. return QualType();
  10255. }
  10256. }
  10257. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  10258. LHS.get(), RHS.get()))
  10259. return QualType();
  10260. bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
  10261. Context, Expr::NPC_ValueDependentIsNotNull);
  10262. bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
  10263. Context, Expr::NPC_ValueDependentIsNotNull);
  10264. // Subtracting nullptr or from nullptr is suspect
  10265. if (LHSIsNullPtr)
  10266. diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
  10267. if (RHSIsNullPtr)
  10268. diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
  10269. // The pointee type may have zero size. As an extension, a structure or
  10270. // union may have zero size or an array may have zero length. In this
  10271. // case subtraction does not make sense.
  10272. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  10273. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  10274. if (ElementSize.isZero()) {
  10275. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  10276. << rpointee.getUnqualifiedType()
  10277. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  10278. }
  10279. }
  10280. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  10281. return Context.getPointerDiffType();
  10282. }
  10283. }
  10284. return InvalidOperands(Loc, LHS, RHS);
  10285. }
  10286. static bool isScopedEnumerationType(QualType T) {
  10287. if (const EnumType *ET = T->getAs<EnumType>())
  10288. return ET->getDecl()->isScoped();
  10289. return false;
  10290. }
  10291. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  10292. SourceLocation Loc, BinaryOperatorKind Opc,
  10293. QualType LHSType) {
  10294. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  10295. // so skip remaining warnings as we don't want to modify values within Sema.
  10296. if (S.getLangOpts().OpenCL)
  10297. return;
  10298. // Check right/shifter operand
  10299. Expr::EvalResult RHSResult;
  10300. if (RHS.get()->isValueDependent() ||
  10301. !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
  10302. return;
  10303. llvm::APSInt Right = RHSResult.Val.getInt();
  10304. if (Right.isNegative()) {
  10305. S.DiagRuntimeBehavior(Loc, RHS.get(),
  10306. S.PDiag(diag::warn_shift_negative)
  10307. << RHS.get()->getSourceRange());
  10308. return;
  10309. }
  10310. QualType LHSExprType = LHS.get()->getType();
  10311. uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
  10312. if (LHSExprType->isBitIntType())
  10313. LeftSize = S.Context.getIntWidth(LHSExprType);
  10314. else if (LHSExprType->isFixedPointType()) {
  10315. auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
  10316. LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
  10317. }
  10318. llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
  10319. if (Right.uge(LeftBits)) {
  10320. S.DiagRuntimeBehavior(Loc, RHS.get(),
  10321. S.PDiag(diag::warn_shift_gt_typewidth)
  10322. << RHS.get()->getSourceRange());
  10323. return;
  10324. }
  10325. // FIXME: We probably need to handle fixed point types specially here.
  10326. if (Opc != BO_Shl || LHSExprType->isFixedPointType())
  10327. return;
  10328. // When left shifting an ICE which is signed, we can check for overflow which
  10329. // according to C++ standards prior to C++2a has undefined behavior
  10330. // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
  10331. // more than the maximum value representable in the result type, so never
  10332. // warn for those. (FIXME: Unsigned left-shift overflow in a constant
  10333. // expression is still probably a bug.)
  10334. Expr::EvalResult LHSResult;
  10335. if (LHS.get()->isValueDependent() ||
  10336. LHSType->hasUnsignedIntegerRepresentation() ||
  10337. !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
  10338. return;
  10339. llvm::APSInt Left = LHSResult.Val.getInt();
  10340. // Don't warn if signed overflow is defined, then all the rest of the
  10341. // diagnostics will not be triggered because the behavior is defined.
  10342. // Also don't warn in C++20 mode (and newer), as signed left shifts
  10343. // always wrap and never overflow.
  10344. if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
  10345. return;
  10346. // If LHS does not have a non-negative value then, the
  10347. // behavior is undefined before C++2a. Warn about it.
  10348. if (Left.isNegative()) {
  10349. S.DiagRuntimeBehavior(Loc, LHS.get(),
  10350. S.PDiag(diag::warn_shift_lhs_negative)
  10351. << LHS.get()->getSourceRange());
  10352. return;
  10353. }
  10354. llvm::APInt ResultBits =
  10355. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  10356. if (LeftBits.uge(ResultBits))
  10357. return;
  10358. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  10359. Result = Result.shl(Right);
  10360. // Print the bit representation of the signed integer as an unsigned
  10361. // hexadecimal number.
  10362. SmallString<40> HexResult;
  10363. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  10364. // If we are only missing a sign bit, this is less likely to result in actual
  10365. // bugs -- if the result is cast back to an unsigned type, it will have the
  10366. // expected value. Thus we place this behind a different warning that can be
  10367. // turned off separately if needed.
  10368. if (LeftBits == ResultBits - 1) {
  10369. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  10370. << HexResult << LHSType
  10371. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  10372. return;
  10373. }
  10374. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  10375. << HexResult.str() << Result.getMinSignedBits() << LHSType
  10376. << Left.getBitWidth() << LHS.get()->getSourceRange()
  10377. << RHS.get()->getSourceRange();
  10378. }
  10379. /// Return the resulting type when a vector is shifted
  10380. /// by a scalar or vector shift amount.
  10381. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  10382. SourceLocation Loc, bool IsCompAssign) {
  10383. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  10384. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  10385. !LHS.get()->getType()->isVectorType()) {
  10386. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  10387. << RHS.get()->getType() << LHS.get()->getType()
  10388. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  10389. return QualType();
  10390. }
  10391. if (!IsCompAssign) {
  10392. LHS = S.UsualUnaryConversions(LHS.get());
  10393. if (LHS.isInvalid()) return QualType();
  10394. }
  10395. RHS = S.UsualUnaryConversions(RHS.get());
  10396. if (RHS.isInvalid()) return QualType();
  10397. QualType LHSType = LHS.get()->getType();
  10398. // Note that LHS might be a scalar because the routine calls not only in
  10399. // OpenCL case.
  10400. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  10401. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  10402. // Note that RHS might not be a vector.
  10403. QualType RHSType = RHS.get()->getType();
  10404. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  10405. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  10406. // Do not allow shifts for boolean vectors.
  10407. if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
  10408. (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
  10409. S.Diag(Loc, diag::err_typecheck_invalid_operands)
  10410. << LHS.get()->getType() << RHS.get()->getType()
  10411. << LHS.get()->getSourceRange();
  10412. return QualType();
  10413. }
  10414. // The operands need to be integers.
  10415. if (!LHSEleType->isIntegerType()) {
  10416. S.Diag(Loc, diag::err_typecheck_expect_int)
  10417. << LHS.get()->getType() << LHS.get()->getSourceRange();
  10418. return QualType();
  10419. }
  10420. if (!RHSEleType->isIntegerType()) {
  10421. S.Diag(Loc, diag::err_typecheck_expect_int)
  10422. << RHS.get()->getType() << RHS.get()->getSourceRange();
  10423. return QualType();
  10424. }
  10425. if (!LHSVecTy) {
  10426. assert(RHSVecTy);
  10427. if (IsCompAssign)
  10428. return RHSType;
  10429. if (LHSEleType != RHSEleType) {
  10430. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  10431. LHSEleType = RHSEleType;
  10432. }
  10433. QualType VecTy =
  10434. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  10435. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  10436. LHSType = VecTy;
  10437. } else if (RHSVecTy) {
  10438. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  10439. // are applied component-wise. So if RHS is a vector, then ensure
  10440. // that the number of elements is the same as LHS...
  10441. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  10442. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  10443. << LHS.get()->getType() << RHS.get()->getType()
  10444. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  10445. return QualType();
  10446. }
  10447. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  10448. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  10449. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  10450. if (LHSBT != RHSBT &&
  10451. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  10452. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  10453. << LHS.get()->getType() << RHS.get()->getType()
  10454. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  10455. }
  10456. }
  10457. } else {
  10458. // ...else expand RHS to match the number of elements in LHS.
  10459. QualType VecTy =
  10460. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  10461. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  10462. }
  10463. return LHSType;
  10464. }
  10465. static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
  10466. ExprResult &RHS, SourceLocation Loc,
  10467. bool IsCompAssign) {
  10468. if (!IsCompAssign) {
  10469. LHS = S.UsualUnaryConversions(LHS.get());
  10470. if (LHS.isInvalid())
  10471. return QualType();
  10472. }
  10473. RHS = S.UsualUnaryConversions(RHS.get());
  10474. if (RHS.isInvalid())
  10475. return QualType();
  10476. QualType LHSType = LHS.get()->getType();
  10477. const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
  10478. QualType LHSEleType = LHSType->isVLSTBuiltinType()
  10479. ? LHSBuiltinTy->getSveEltType(S.getASTContext())
  10480. : LHSType;
  10481. // Note that RHS might not be a vector
  10482. QualType RHSType = RHS.get()->getType();
  10483. const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
  10484. QualType RHSEleType = RHSType->isVLSTBuiltinType()
  10485. ? RHSBuiltinTy->getSveEltType(S.getASTContext())
  10486. : RHSType;
  10487. if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
  10488. (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
  10489. S.Diag(Loc, diag::err_typecheck_invalid_operands)
  10490. << LHSType << RHSType << LHS.get()->getSourceRange();
  10491. return QualType();
  10492. }
  10493. if (!LHSEleType->isIntegerType()) {
  10494. S.Diag(Loc, diag::err_typecheck_expect_int)
  10495. << LHS.get()->getType() << LHS.get()->getSourceRange();
  10496. return QualType();
  10497. }
  10498. if (!RHSEleType->isIntegerType()) {
  10499. S.Diag(Loc, diag::err_typecheck_expect_int)
  10500. << RHS.get()->getType() << RHS.get()->getSourceRange();
  10501. return QualType();
  10502. }
  10503. if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
  10504. (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
  10505. S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
  10506. S.Diag(Loc, diag::err_typecheck_invalid_operands)
  10507. << LHSType << RHSType << LHS.get()->getSourceRange()
  10508. << RHS.get()->getSourceRange();
  10509. return QualType();
  10510. }
  10511. if (!LHSType->isVLSTBuiltinType()) {
  10512. assert(RHSType->isVLSTBuiltinType());
  10513. if (IsCompAssign)
  10514. return RHSType;
  10515. if (LHSEleType != RHSEleType) {
  10516. LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
  10517. LHSEleType = RHSEleType;
  10518. }
  10519. const llvm::ElementCount VecSize =
  10520. S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
  10521. QualType VecTy =
  10522. S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
  10523. LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
  10524. LHSType = VecTy;
  10525. } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
  10526. if (S.Context.getTypeSize(RHSBuiltinTy) !=
  10527. S.Context.getTypeSize(LHSBuiltinTy)) {
  10528. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  10529. << LHSType << RHSType << LHS.get()->getSourceRange()
  10530. << RHS.get()->getSourceRange();
  10531. return QualType();
  10532. }
  10533. } else {
  10534. const llvm::ElementCount VecSize =
  10535. S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
  10536. if (LHSEleType != RHSEleType) {
  10537. RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
  10538. RHSEleType = LHSEleType;
  10539. }
  10540. QualType VecTy =
  10541. S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
  10542. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  10543. }
  10544. return LHSType;
  10545. }
  10546. // C99 6.5.7
  10547. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  10548. SourceLocation Loc, BinaryOperatorKind Opc,
  10549. bool IsCompAssign) {
  10550. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  10551. // Vector shifts promote their scalar inputs to vector type.
  10552. if (LHS.get()->getType()->isVectorType() ||
  10553. RHS.get()->getType()->isVectorType()) {
  10554. if (LangOpts.ZVector) {
  10555. // The shift operators for the z vector extensions work basically
  10556. // like general shifts, except that neither the LHS nor the RHS is
  10557. // allowed to be a "vector bool".
  10558. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  10559. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  10560. return InvalidOperands(Loc, LHS, RHS);
  10561. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  10562. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  10563. return InvalidOperands(Loc, LHS, RHS);
  10564. }
  10565. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  10566. }
  10567. if (LHS.get()->getType()->isVLSTBuiltinType() ||
  10568. RHS.get()->getType()->isVLSTBuiltinType())
  10569. return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  10570. // Shifts don't perform usual arithmetic conversions, they just do integer
  10571. // promotions on each operand. C99 6.5.7p3
  10572. // For the LHS, do usual unary conversions, but then reset them away
  10573. // if this is a compound assignment.
  10574. ExprResult OldLHS = LHS;
  10575. LHS = UsualUnaryConversions(LHS.get());
  10576. if (LHS.isInvalid())
  10577. return QualType();
  10578. QualType LHSType = LHS.get()->getType();
  10579. if (IsCompAssign) LHS = OldLHS;
  10580. // The RHS is simpler.
  10581. RHS = UsualUnaryConversions(RHS.get());
  10582. if (RHS.isInvalid())
  10583. return QualType();
  10584. QualType RHSType = RHS.get()->getType();
  10585. // C99 6.5.7p2: Each of the operands shall have integer type.
  10586. // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
  10587. if ((!LHSType->isFixedPointOrIntegerType() &&
  10588. !LHSType->hasIntegerRepresentation()) ||
  10589. !RHSType->hasIntegerRepresentation())
  10590. return InvalidOperands(Loc, LHS, RHS);
  10591. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  10592. // hasIntegerRepresentation() above instead of this.
  10593. if (isScopedEnumerationType(LHSType) ||
  10594. isScopedEnumerationType(RHSType)) {
  10595. return InvalidOperands(Loc, LHS, RHS);
  10596. }
  10597. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  10598. // "The type of the result is that of the promoted left operand."
  10599. return LHSType;
  10600. }
  10601. /// Diagnose bad pointer comparisons.
  10602. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  10603. ExprResult &LHS, ExprResult &RHS,
  10604. bool IsError) {
  10605. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  10606. : diag::ext_typecheck_comparison_of_distinct_pointers)
  10607. << LHS.get()->getType() << RHS.get()->getType()
  10608. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  10609. }
  10610. /// Returns false if the pointers are converted to a composite type,
  10611. /// true otherwise.
  10612. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  10613. ExprResult &LHS, ExprResult &RHS) {
  10614. // C++ [expr.rel]p2:
  10615. // [...] Pointer conversions (4.10) and qualification
  10616. // conversions (4.4) are performed on pointer operands (or on
  10617. // a pointer operand and a null pointer constant) to bring
  10618. // them to their composite pointer type. [...]
  10619. //
  10620. // C++ [expr.eq]p1 uses the same notion for (in)equality
  10621. // comparisons of pointers.
  10622. QualType LHSType = LHS.get()->getType();
  10623. QualType RHSType = RHS.get()->getType();
  10624. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  10625. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  10626. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  10627. if (T.isNull()) {
  10628. if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
  10629. (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
  10630. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  10631. else
  10632. S.InvalidOperands(Loc, LHS, RHS);
  10633. return true;
  10634. }
  10635. return false;
  10636. }
  10637. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  10638. ExprResult &LHS,
  10639. ExprResult &RHS,
  10640. bool IsError) {
  10641. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  10642. : diag::ext_typecheck_comparison_of_fptr_to_void)
  10643. << LHS.get()->getType() << RHS.get()->getType()
  10644. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  10645. }
  10646. static bool isObjCObjectLiteral(ExprResult &E) {
  10647. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  10648. case Stmt::ObjCArrayLiteralClass:
  10649. case Stmt::ObjCDictionaryLiteralClass:
  10650. case Stmt::ObjCStringLiteralClass:
  10651. case Stmt::ObjCBoxedExprClass:
  10652. return true;
  10653. default:
  10654. // Note that ObjCBoolLiteral is NOT an object literal!
  10655. return false;
  10656. }
  10657. }
  10658. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  10659. const ObjCObjectPointerType *Type =
  10660. LHS->getType()->getAs<ObjCObjectPointerType>();
  10661. // If this is not actually an Objective-C object, bail out.
  10662. if (!Type)
  10663. return false;
  10664. // Get the LHS object's interface type.
  10665. QualType InterfaceType = Type->getPointeeType();
  10666. // If the RHS isn't an Objective-C object, bail out.
  10667. if (!RHS->getType()->isObjCObjectPointerType())
  10668. return false;
  10669. // Try to find the -isEqual: method.
  10670. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  10671. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  10672. InterfaceType,
  10673. /*IsInstance=*/true);
  10674. if (!Method) {
  10675. if (Type->isObjCIdType()) {
  10676. // For 'id', just check the global pool.
  10677. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  10678. /*receiverId=*/true);
  10679. } else {
  10680. // Check protocols.
  10681. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  10682. /*IsInstance=*/true);
  10683. }
  10684. }
  10685. if (!Method)
  10686. return false;
  10687. QualType T = Method->parameters()[0]->getType();
  10688. if (!T->isObjCObjectPointerType())
  10689. return false;
  10690. QualType R = Method->getReturnType();
  10691. if (!R->isScalarType())
  10692. return false;
  10693. return true;
  10694. }
  10695. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  10696. FromE = FromE->IgnoreParenImpCasts();
  10697. switch (FromE->getStmtClass()) {
  10698. default:
  10699. break;
  10700. case Stmt::ObjCStringLiteralClass:
  10701. // "string literal"
  10702. return LK_String;
  10703. case Stmt::ObjCArrayLiteralClass:
  10704. // "array literal"
  10705. return LK_Array;
  10706. case Stmt::ObjCDictionaryLiteralClass:
  10707. // "dictionary literal"
  10708. return LK_Dictionary;
  10709. case Stmt::BlockExprClass:
  10710. return LK_Block;
  10711. case Stmt::ObjCBoxedExprClass: {
  10712. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  10713. switch (Inner->getStmtClass()) {
  10714. case Stmt::IntegerLiteralClass:
  10715. case Stmt::FloatingLiteralClass:
  10716. case Stmt::CharacterLiteralClass:
  10717. case Stmt::ObjCBoolLiteralExprClass:
  10718. case Stmt::CXXBoolLiteralExprClass:
  10719. // "numeric literal"
  10720. return LK_Numeric;
  10721. case Stmt::ImplicitCastExprClass: {
  10722. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  10723. // Boolean literals can be represented by implicit casts.
  10724. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  10725. return LK_Numeric;
  10726. break;
  10727. }
  10728. default:
  10729. break;
  10730. }
  10731. return LK_Boxed;
  10732. }
  10733. }
  10734. return LK_None;
  10735. }
  10736. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  10737. ExprResult &LHS, ExprResult &RHS,
  10738. BinaryOperator::Opcode Opc){
  10739. Expr *Literal;
  10740. Expr *Other;
  10741. if (isObjCObjectLiteral(LHS)) {
  10742. Literal = LHS.get();
  10743. Other = RHS.get();
  10744. } else {
  10745. Literal = RHS.get();
  10746. Other = LHS.get();
  10747. }
  10748. // Don't warn on comparisons against nil.
  10749. Other = Other->IgnoreParenCasts();
  10750. if (Other->isNullPointerConstant(S.getASTContext(),
  10751. Expr::NPC_ValueDependentIsNotNull))
  10752. return;
  10753. // This should be kept in sync with warn_objc_literal_comparison.
  10754. // LK_String should always be after the other literals, since it has its own
  10755. // warning flag.
  10756. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  10757. assert(LiteralKind != Sema::LK_Block);
  10758. if (LiteralKind == Sema::LK_None) {
  10759. llvm_unreachable("Unknown Objective-C object literal kind");
  10760. }
  10761. if (LiteralKind == Sema::LK_String)
  10762. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  10763. << Literal->getSourceRange();
  10764. else
  10765. S.Diag(Loc, diag::warn_objc_literal_comparison)
  10766. << LiteralKind << Literal->getSourceRange();
  10767. if (BinaryOperator::isEqualityOp(Opc) &&
  10768. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  10769. SourceLocation Start = LHS.get()->getBeginLoc();
  10770. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  10771. CharSourceRange OpRange =
  10772. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  10773. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  10774. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  10775. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  10776. << FixItHint::CreateInsertion(End, "]");
  10777. }
  10778. }
  10779. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  10780. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  10781. ExprResult &RHS, SourceLocation Loc,
  10782. BinaryOperatorKind Opc) {
  10783. // Check that left hand side is !something.
  10784. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  10785. if (!UO || UO->getOpcode() != UO_LNot) return;
  10786. // Only check if the right hand side is non-bool arithmetic type.
  10787. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  10788. // Make sure that the something in !something is not bool.
  10789. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  10790. if (SubExpr->isKnownToHaveBooleanValue()) return;
  10791. // Emit warning.
  10792. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  10793. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  10794. << Loc << IsBitwiseOp;
  10795. // First note suggest !(x < y)
  10796. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  10797. SourceLocation FirstClose = RHS.get()->getEndLoc();
  10798. FirstClose = S.getLocForEndOfToken(FirstClose);
  10799. if (FirstClose.isInvalid())
  10800. FirstOpen = SourceLocation();
  10801. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  10802. << IsBitwiseOp
  10803. << FixItHint::CreateInsertion(FirstOpen, "(")
  10804. << FixItHint::CreateInsertion(FirstClose, ")");
  10805. // Second note suggests (!x) < y
  10806. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  10807. SourceLocation SecondClose = LHS.get()->getEndLoc();
  10808. SecondClose = S.getLocForEndOfToken(SecondClose);
  10809. if (SecondClose.isInvalid())
  10810. SecondOpen = SourceLocation();
  10811. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  10812. << FixItHint::CreateInsertion(SecondOpen, "(")
  10813. << FixItHint::CreateInsertion(SecondClose, ")");
  10814. }
  10815. // Returns true if E refers to a non-weak array.
  10816. static bool checkForArray(const Expr *E) {
  10817. const ValueDecl *D = nullptr;
  10818. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  10819. D = DR->getDecl();
  10820. } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  10821. if (Mem->isImplicitAccess())
  10822. D = Mem->getMemberDecl();
  10823. }
  10824. if (!D)
  10825. return false;
  10826. return D->getType()->isArrayType() && !D->isWeak();
  10827. }
  10828. /// Diagnose some forms of syntactically-obvious tautological comparison.
  10829. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  10830. Expr *LHS, Expr *RHS,
  10831. BinaryOperatorKind Opc) {
  10832. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  10833. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  10834. QualType LHSType = LHS->getType();
  10835. QualType RHSType = RHS->getType();
  10836. if (LHSType->hasFloatingRepresentation() ||
  10837. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  10838. S.inTemplateInstantiation())
  10839. return;
  10840. // Comparisons between two array types are ill-formed for operator<=>, so
  10841. // we shouldn't emit any additional warnings about it.
  10842. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  10843. return;
  10844. // For non-floating point types, check for self-comparisons of the form
  10845. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  10846. // often indicate logic errors in the program.
  10847. //
  10848. // NOTE: Don't warn about comparison expressions resulting from macro
  10849. // expansion. Also don't warn about comparisons which are only self
  10850. // comparisons within a template instantiation. The warnings should catch
  10851. // obvious cases in the definition of the template anyways. The idea is to
  10852. // warn when the typed comparison operator will always evaluate to the same
  10853. // result.
  10854. // Used for indexing into %select in warn_comparison_always
  10855. enum {
  10856. AlwaysConstant,
  10857. AlwaysTrue,
  10858. AlwaysFalse,
  10859. AlwaysEqual, // std::strong_ordering::equal from operator<=>
  10860. };
  10861. // C++2a [depr.array.comp]:
  10862. // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
  10863. // operands of array type are deprecated.
  10864. if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
  10865. RHSStripped->getType()->isArrayType()) {
  10866. S.Diag(Loc, diag::warn_depr_array_comparison)
  10867. << LHS->getSourceRange() << RHS->getSourceRange()
  10868. << LHSStripped->getType() << RHSStripped->getType();
  10869. // Carry on to produce the tautological comparison warning, if this
  10870. // expression is potentially-evaluated, we can resolve the array to a
  10871. // non-weak declaration, and so on.
  10872. }
  10873. if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
  10874. if (Expr::isSameComparisonOperand(LHS, RHS)) {
  10875. unsigned Result;
  10876. switch (Opc) {
  10877. case BO_EQ:
  10878. case BO_LE:
  10879. case BO_GE:
  10880. Result = AlwaysTrue;
  10881. break;
  10882. case BO_NE:
  10883. case BO_LT:
  10884. case BO_GT:
  10885. Result = AlwaysFalse;
  10886. break;
  10887. case BO_Cmp:
  10888. Result = AlwaysEqual;
  10889. break;
  10890. default:
  10891. Result = AlwaysConstant;
  10892. break;
  10893. }
  10894. S.DiagRuntimeBehavior(Loc, nullptr,
  10895. S.PDiag(diag::warn_comparison_always)
  10896. << 0 /*self-comparison*/
  10897. << Result);
  10898. } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
  10899. // What is it always going to evaluate to?
  10900. unsigned Result;
  10901. switch (Opc) {
  10902. case BO_EQ: // e.g. array1 == array2
  10903. Result = AlwaysFalse;
  10904. break;
  10905. case BO_NE: // e.g. array1 != array2
  10906. Result = AlwaysTrue;
  10907. break;
  10908. default: // e.g. array1 <= array2
  10909. // The best we can say is 'a constant'
  10910. Result = AlwaysConstant;
  10911. break;
  10912. }
  10913. S.DiagRuntimeBehavior(Loc, nullptr,
  10914. S.PDiag(diag::warn_comparison_always)
  10915. << 1 /*array comparison*/
  10916. << Result);
  10917. }
  10918. }
  10919. if (isa<CastExpr>(LHSStripped))
  10920. LHSStripped = LHSStripped->IgnoreParenCasts();
  10921. if (isa<CastExpr>(RHSStripped))
  10922. RHSStripped = RHSStripped->IgnoreParenCasts();
  10923. // Warn about comparisons against a string constant (unless the other
  10924. // operand is null); the user probably wants string comparison function.
  10925. Expr *LiteralString = nullptr;
  10926. Expr *LiteralStringStripped = nullptr;
  10927. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  10928. !RHSStripped->isNullPointerConstant(S.Context,
  10929. Expr::NPC_ValueDependentIsNull)) {
  10930. LiteralString = LHS;
  10931. LiteralStringStripped = LHSStripped;
  10932. } else if ((isa<StringLiteral>(RHSStripped) ||
  10933. isa<ObjCEncodeExpr>(RHSStripped)) &&
  10934. !LHSStripped->isNullPointerConstant(S.Context,
  10935. Expr::NPC_ValueDependentIsNull)) {
  10936. LiteralString = RHS;
  10937. LiteralStringStripped = RHSStripped;
  10938. }
  10939. if (LiteralString) {
  10940. S.DiagRuntimeBehavior(Loc, nullptr,
  10941. S.PDiag(diag::warn_stringcompare)
  10942. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  10943. << LiteralString->getSourceRange());
  10944. }
  10945. }
  10946. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  10947. switch (CK) {
  10948. default: {
  10949. #ifndef NDEBUG
  10950. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  10951. << "\n";
  10952. #endif
  10953. llvm_unreachable("unhandled cast kind");
  10954. }
  10955. case CK_UserDefinedConversion:
  10956. return ICK_Identity;
  10957. case CK_LValueToRValue:
  10958. return ICK_Lvalue_To_Rvalue;
  10959. case CK_ArrayToPointerDecay:
  10960. return ICK_Array_To_Pointer;
  10961. case CK_FunctionToPointerDecay:
  10962. return ICK_Function_To_Pointer;
  10963. case CK_IntegralCast:
  10964. return ICK_Integral_Conversion;
  10965. case CK_FloatingCast:
  10966. return ICK_Floating_Conversion;
  10967. case CK_IntegralToFloating:
  10968. case CK_FloatingToIntegral:
  10969. return ICK_Floating_Integral;
  10970. case CK_IntegralComplexCast:
  10971. case CK_FloatingComplexCast:
  10972. case CK_FloatingComplexToIntegralComplex:
  10973. case CK_IntegralComplexToFloatingComplex:
  10974. return ICK_Complex_Conversion;
  10975. case CK_FloatingComplexToReal:
  10976. case CK_FloatingRealToComplex:
  10977. case CK_IntegralComplexToReal:
  10978. case CK_IntegralRealToComplex:
  10979. return ICK_Complex_Real;
  10980. }
  10981. }
  10982. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  10983. QualType FromType,
  10984. SourceLocation Loc) {
  10985. // Check for a narrowing implicit conversion.
  10986. StandardConversionSequence SCS;
  10987. SCS.setAsIdentityConversion();
  10988. SCS.setToType(0, FromType);
  10989. SCS.setToType(1, ToType);
  10990. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  10991. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  10992. APValue PreNarrowingValue;
  10993. QualType PreNarrowingType;
  10994. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  10995. PreNarrowingType,
  10996. /*IgnoreFloatToIntegralConversion*/ true)) {
  10997. case NK_Dependent_Narrowing:
  10998. // Implicit conversion to a narrower type, but the expression is
  10999. // value-dependent so we can't tell whether it's actually narrowing.
  11000. case NK_Not_Narrowing:
  11001. return false;
  11002. case NK_Constant_Narrowing:
  11003. // Implicit conversion to a narrower type, and the value is not a constant
  11004. // expression.
  11005. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  11006. << /*Constant*/ 1
  11007. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  11008. return true;
  11009. case NK_Variable_Narrowing:
  11010. // Implicit conversion to a narrower type, and the value is not a constant
  11011. // expression.
  11012. case NK_Type_Narrowing:
  11013. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  11014. << /*Constant*/ 0 << FromType << ToType;
  11015. // TODO: It's not a constant expression, but what if the user intended it
  11016. // to be? Can we produce notes to help them figure out why it isn't?
  11017. return true;
  11018. }
  11019. llvm_unreachable("unhandled case in switch");
  11020. }
  11021. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  11022. ExprResult &LHS,
  11023. ExprResult &RHS,
  11024. SourceLocation Loc) {
  11025. QualType LHSType = LHS.get()->getType();
  11026. QualType RHSType = RHS.get()->getType();
  11027. // Dig out the original argument type and expression before implicit casts
  11028. // were applied. These are the types/expressions we need to check the
  11029. // [expr.spaceship] requirements against.
  11030. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  11031. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  11032. QualType LHSStrippedType = LHSStripped.get()->getType();
  11033. QualType RHSStrippedType = RHSStripped.get()->getType();
  11034. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  11035. // other is not, the program is ill-formed.
  11036. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  11037. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  11038. return QualType();
  11039. }
  11040. // FIXME: Consider combining this with checkEnumArithmeticConversions.
  11041. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  11042. RHSStrippedType->isEnumeralType();
  11043. if (NumEnumArgs == 1) {
  11044. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  11045. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  11046. if (OtherTy->hasFloatingRepresentation()) {
  11047. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  11048. return QualType();
  11049. }
  11050. }
  11051. if (NumEnumArgs == 2) {
  11052. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  11053. // type E, the operator yields the result of converting the operands
  11054. // to the underlying type of E and applying <=> to the converted operands.
  11055. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  11056. S.InvalidOperands(Loc, LHS, RHS);
  11057. return QualType();
  11058. }
  11059. QualType IntType =
  11060. LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
  11061. assert(IntType->isArithmeticType());
  11062. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  11063. // promote the boolean type, and all other promotable integer types, to
  11064. // avoid this.
  11065. if (S.Context.isPromotableIntegerType(IntType))
  11066. IntType = S.Context.getPromotedIntegerType(IntType);
  11067. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  11068. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  11069. LHSType = RHSType = IntType;
  11070. }
  11071. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  11072. // usual arithmetic conversions are applied to the operands.
  11073. QualType Type =
  11074. S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
  11075. if (LHS.isInvalid() || RHS.isInvalid())
  11076. return QualType();
  11077. if (Type.isNull())
  11078. return S.InvalidOperands(Loc, LHS, RHS);
  11079. std::optional<ComparisonCategoryType> CCT =
  11080. getComparisonCategoryForBuiltinCmp(Type);
  11081. if (!CCT)
  11082. return S.InvalidOperands(Loc, LHS, RHS);
  11083. bool HasNarrowing = checkThreeWayNarrowingConversion(
  11084. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  11085. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  11086. RHS.get()->getBeginLoc());
  11087. if (HasNarrowing)
  11088. return QualType();
  11089. assert(!Type.isNull() && "composite type for <=> has not been set");
  11090. return S.CheckComparisonCategoryType(
  11091. *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
  11092. }
  11093. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  11094. ExprResult &RHS,
  11095. SourceLocation Loc,
  11096. BinaryOperatorKind Opc) {
  11097. if (Opc == BO_Cmp)
  11098. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  11099. // C99 6.5.8p3 / C99 6.5.9p4
  11100. QualType Type =
  11101. S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
  11102. if (LHS.isInvalid() || RHS.isInvalid())
  11103. return QualType();
  11104. if (Type.isNull())
  11105. return S.InvalidOperands(Loc, LHS, RHS);
  11106. assert(Type->isArithmeticType() || Type->isEnumeralType());
  11107. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  11108. return S.InvalidOperands(Loc, LHS, RHS);
  11109. // Check for comparisons of floating point operands using != and ==.
  11110. if (Type->hasFloatingRepresentation())
  11111. S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
  11112. // The result of comparisons is 'bool' in C++, 'int' in C.
  11113. return S.Context.getLogicalOperationType();
  11114. }
  11115. void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
  11116. if (!NullE.get()->getType()->isAnyPointerType())
  11117. return;
  11118. int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
  11119. if (!E.get()->getType()->isAnyPointerType() &&
  11120. E.get()->isNullPointerConstant(Context,
  11121. Expr::NPC_ValueDependentIsNotNull) ==
  11122. Expr::NPCK_ZeroExpression) {
  11123. if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
  11124. if (CL->getValue() == 0)
  11125. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  11126. << NullValue
  11127. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  11128. NullValue ? "NULL" : "(void *)0");
  11129. } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
  11130. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  11131. QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
  11132. if (T == Context.CharTy)
  11133. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  11134. << NullValue
  11135. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  11136. NullValue ? "NULL" : "(void *)0");
  11137. }
  11138. }
  11139. }
  11140. // C99 6.5.8, C++ [expr.rel]
  11141. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  11142. SourceLocation Loc,
  11143. BinaryOperatorKind Opc) {
  11144. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  11145. bool IsThreeWay = Opc == BO_Cmp;
  11146. bool IsOrdered = IsRelational || IsThreeWay;
  11147. auto IsAnyPointerType = [](ExprResult E) {
  11148. QualType Ty = E.get()->getType();
  11149. return Ty->isPointerType() || Ty->isMemberPointerType();
  11150. };
  11151. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  11152. // type, array-to-pointer, ..., conversions are performed on both operands to
  11153. // bring them to their composite type.
  11154. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  11155. // any type-related checks.
  11156. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  11157. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  11158. if (LHS.isInvalid())
  11159. return QualType();
  11160. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  11161. if (RHS.isInvalid())
  11162. return QualType();
  11163. } else {
  11164. LHS = DefaultLvalueConversion(LHS.get());
  11165. if (LHS.isInvalid())
  11166. return QualType();
  11167. RHS = DefaultLvalueConversion(RHS.get());
  11168. if (RHS.isInvalid())
  11169. return QualType();
  11170. }
  11171. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
  11172. if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
  11173. CheckPtrComparisonWithNullChar(LHS, RHS);
  11174. CheckPtrComparisonWithNullChar(RHS, LHS);
  11175. }
  11176. // Handle vector comparisons separately.
  11177. if (LHS.get()->getType()->isVectorType() ||
  11178. RHS.get()->getType()->isVectorType())
  11179. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  11180. if (LHS.get()->getType()->isVLSTBuiltinType() ||
  11181. RHS.get()->getType()->isVLSTBuiltinType())
  11182. return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
  11183. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  11184. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  11185. QualType LHSType = LHS.get()->getType();
  11186. QualType RHSType = RHS.get()->getType();
  11187. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  11188. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  11189. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  11190. const Expr::NullPointerConstantKind LHSNullKind =
  11191. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  11192. const Expr::NullPointerConstantKind RHSNullKind =
  11193. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  11194. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  11195. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  11196. auto computeResultTy = [&]() {
  11197. if (Opc != BO_Cmp)
  11198. return Context.getLogicalOperationType();
  11199. assert(getLangOpts().CPlusPlus);
  11200. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  11201. QualType CompositeTy = LHS.get()->getType();
  11202. assert(!CompositeTy->isReferenceType());
  11203. std::optional<ComparisonCategoryType> CCT =
  11204. getComparisonCategoryForBuiltinCmp(CompositeTy);
  11205. if (!CCT)
  11206. return InvalidOperands(Loc, LHS, RHS);
  11207. if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
  11208. // P0946R0: Comparisons between a null pointer constant and an object
  11209. // pointer result in std::strong_equality, which is ill-formed under
  11210. // P1959R0.
  11211. Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
  11212. << (LHSIsNull ? LHS.get()->getSourceRange()
  11213. : RHS.get()->getSourceRange());
  11214. return QualType();
  11215. }
  11216. return CheckComparisonCategoryType(
  11217. *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
  11218. };
  11219. if (!IsOrdered && LHSIsNull != RHSIsNull) {
  11220. bool IsEquality = Opc == BO_EQ;
  11221. if (RHSIsNull)
  11222. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  11223. RHS.get()->getSourceRange());
  11224. else
  11225. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  11226. LHS.get()->getSourceRange());
  11227. }
  11228. if (IsOrdered && LHSType->isFunctionPointerType() &&
  11229. RHSType->isFunctionPointerType()) {
  11230. // Valid unless a relational comparison of function pointers
  11231. bool IsError = Opc == BO_Cmp;
  11232. auto DiagID =
  11233. IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
  11234. : getLangOpts().CPlusPlus
  11235. ? diag::warn_typecheck_ordered_comparison_of_function_pointers
  11236. : diag::ext_typecheck_ordered_comparison_of_function_pointers;
  11237. Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
  11238. << RHS.get()->getSourceRange();
  11239. if (IsError)
  11240. return QualType();
  11241. }
  11242. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  11243. (RHSType->isIntegerType() && !RHSIsNull)) {
  11244. // Skip normal pointer conversion checks in this case; we have better
  11245. // diagnostics for this below.
  11246. } else if (getLangOpts().CPlusPlus) {
  11247. // Equality comparison of a function pointer to a void pointer is invalid,
  11248. // but we allow it as an extension.
  11249. // FIXME: If we really want to allow this, should it be part of composite
  11250. // pointer type computation so it works in conditionals too?
  11251. if (!IsOrdered &&
  11252. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  11253. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  11254. // This is a gcc extension compatibility comparison.
  11255. // In a SFINAE context, we treat this as a hard error to maintain
  11256. // conformance with the C++ standard.
  11257. diagnoseFunctionPointerToVoidComparison(
  11258. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  11259. if (isSFINAEContext())
  11260. return QualType();
  11261. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  11262. return computeResultTy();
  11263. }
  11264. // C++ [expr.eq]p2:
  11265. // If at least one operand is a pointer [...] bring them to their
  11266. // composite pointer type.
  11267. // C++ [expr.spaceship]p6
  11268. // If at least one of the operands is of pointer type, [...] bring them
  11269. // to their composite pointer type.
  11270. // C++ [expr.rel]p2:
  11271. // If both operands are pointers, [...] bring them to their composite
  11272. // pointer type.
  11273. // For <=>, the only valid non-pointer types are arrays and functions, and
  11274. // we already decayed those, so this is really the same as the relational
  11275. // comparison rule.
  11276. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  11277. (IsOrdered ? 2 : 1) &&
  11278. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  11279. RHSType->isObjCObjectPointerType()))) {
  11280. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  11281. return QualType();
  11282. return computeResultTy();
  11283. }
  11284. } else if (LHSType->isPointerType() &&
  11285. RHSType->isPointerType()) { // C99 6.5.8p2
  11286. // All of the following pointer-related warnings are GCC extensions, except
  11287. // when handling null pointer constants.
  11288. QualType LCanPointeeTy =
  11289. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  11290. QualType RCanPointeeTy =
  11291. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  11292. // C99 6.5.9p2 and C99 6.5.8p2
  11293. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  11294. RCanPointeeTy.getUnqualifiedType())) {
  11295. if (IsRelational) {
  11296. // Pointers both need to point to complete or incomplete types
  11297. if ((LCanPointeeTy->isIncompleteType() !=
  11298. RCanPointeeTy->isIncompleteType()) &&
  11299. !getLangOpts().C11) {
  11300. Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
  11301. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
  11302. << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
  11303. << RCanPointeeTy->isIncompleteType();
  11304. }
  11305. }
  11306. } else if (!IsRelational &&
  11307. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  11308. // Valid unless comparison between non-null pointer and function pointer
  11309. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  11310. && !LHSIsNull && !RHSIsNull)
  11311. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  11312. /*isError*/false);
  11313. } else {
  11314. // Invalid
  11315. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  11316. }
  11317. if (LCanPointeeTy != RCanPointeeTy) {
  11318. // Treat NULL constant as a special case in OpenCL.
  11319. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  11320. if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
  11321. Diag(Loc,
  11322. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  11323. << LHSType << RHSType << 0 /* comparison */
  11324. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  11325. }
  11326. }
  11327. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  11328. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  11329. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  11330. : CK_BitCast;
  11331. if (LHSIsNull && !RHSIsNull)
  11332. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  11333. else
  11334. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  11335. }
  11336. return computeResultTy();
  11337. }
  11338. // C++ [expr.eq]p4:
  11339. // Two operands of type std::nullptr_t or one operand of type
  11340. // std::nullptr_t and the other a null pointer constant compare
  11341. // equal.
  11342. // C2x 6.5.9p5:
  11343. // If both operands have type nullptr_t or one operand has type nullptr_t
  11344. // and the other is a null pointer constant, they compare equal.
  11345. if (!IsOrdered && LHSIsNull && RHSIsNull) {
  11346. if (LHSType->isNullPtrType()) {
  11347. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  11348. return computeResultTy();
  11349. }
  11350. if (RHSType->isNullPtrType()) {
  11351. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  11352. return computeResultTy();
  11353. }
  11354. }
  11355. if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
  11356. // C2x 6.5.9p6:
  11357. // Otherwise, at least one operand is a pointer. If one is a pointer and
  11358. // the other is a null pointer constant, the null pointer constant is
  11359. // converted to the type of the pointer.
  11360. if (LHSIsNull && RHSType->isPointerType()) {
  11361. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  11362. return computeResultTy();
  11363. }
  11364. if (RHSIsNull && LHSType->isPointerType()) {
  11365. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  11366. return computeResultTy();
  11367. }
  11368. }
  11369. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  11370. // These aren't covered by the composite pointer type rules.
  11371. if (!IsOrdered && RHSType->isNullPtrType() &&
  11372. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  11373. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  11374. return computeResultTy();
  11375. }
  11376. if (!IsOrdered && LHSType->isNullPtrType() &&
  11377. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  11378. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  11379. return computeResultTy();
  11380. }
  11381. if (getLangOpts().CPlusPlus) {
  11382. if (IsRelational &&
  11383. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  11384. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  11385. // HACK: Relational comparison of nullptr_t against a pointer type is
  11386. // invalid per DR583, but we allow it within std::less<> and friends,
  11387. // since otherwise common uses of it break.
  11388. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  11389. // friends to have std::nullptr_t overload candidates.
  11390. DeclContext *DC = CurContext;
  11391. if (isa<FunctionDecl>(DC))
  11392. DC = DC->getParent();
  11393. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  11394. if (CTSD->isInStdNamespace() &&
  11395. llvm::StringSwitch<bool>(CTSD->getName())
  11396. .Cases("less", "less_equal", "greater", "greater_equal", true)
  11397. .Default(false)) {
  11398. if (RHSType->isNullPtrType())
  11399. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  11400. else
  11401. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  11402. return computeResultTy();
  11403. }
  11404. }
  11405. }
  11406. // C++ [expr.eq]p2:
  11407. // If at least one operand is a pointer to member, [...] bring them to
  11408. // their composite pointer type.
  11409. if (!IsOrdered &&
  11410. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  11411. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  11412. return QualType();
  11413. else
  11414. return computeResultTy();
  11415. }
  11416. }
  11417. // Handle block pointer types.
  11418. if (!IsOrdered && LHSType->isBlockPointerType() &&
  11419. RHSType->isBlockPointerType()) {
  11420. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  11421. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  11422. if (!LHSIsNull && !RHSIsNull &&
  11423. !Context.typesAreCompatible(lpointee, rpointee)) {
  11424. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  11425. << LHSType << RHSType << LHS.get()->getSourceRange()
  11426. << RHS.get()->getSourceRange();
  11427. }
  11428. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  11429. return computeResultTy();
  11430. }
  11431. // Allow block pointers to be compared with null pointer constants.
  11432. if (!IsOrdered
  11433. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  11434. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  11435. if (!LHSIsNull && !RHSIsNull) {
  11436. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  11437. ->getPointeeType()->isVoidType())
  11438. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  11439. ->getPointeeType()->isVoidType())))
  11440. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  11441. << LHSType << RHSType << LHS.get()->getSourceRange()
  11442. << RHS.get()->getSourceRange();
  11443. }
  11444. if (LHSIsNull && !RHSIsNull)
  11445. LHS = ImpCastExprToType(LHS.get(), RHSType,
  11446. RHSType->isPointerType() ? CK_BitCast
  11447. : CK_AnyPointerToBlockPointerCast);
  11448. else
  11449. RHS = ImpCastExprToType(RHS.get(), LHSType,
  11450. LHSType->isPointerType() ? CK_BitCast
  11451. : CK_AnyPointerToBlockPointerCast);
  11452. return computeResultTy();
  11453. }
  11454. if (LHSType->isObjCObjectPointerType() ||
  11455. RHSType->isObjCObjectPointerType()) {
  11456. const PointerType *LPT = LHSType->getAs<PointerType>();
  11457. const PointerType *RPT = RHSType->getAs<PointerType>();
  11458. if (LPT || RPT) {
  11459. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  11460. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  11461. if (!LPtrToVoid && !RPtrToVoid &&
  11462. !Context.typesAreCompatible(LHSType, RHSType)) {
  11463. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  11464. /*isError*/false);
  11465. }
  11466. // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
  11467. // the RHS, but we have test coverage for this behavior.
  11468. // FIXME: Consider using convertPointersToCompositeType in C++.
  11469. if (LHSIsNull && !RHSIsNull) {
  11470. Expr *E = LHS.get();
  11471. if (getLangOpts().ObjCAutoRefCount)
  11472. CheckObjCConversion(SourceRange(), RHSType, E,
  11473. CCK_ImplicitConversion);
  11474. LHS = ImpCastExprToType(E, RHSType,
  11475. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  11476. }
  11477. else {
  11478. Expr *E = RHS.get();
  11479. if (getLangOpts().ObjCAutoRefCount)
  11480. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  11481. /*Diagnose=*/true,
  11482. /*DiagnoseCFAudited=*/false, Opc);
  11483. RHS = ImpCastExprToType(E, LHSType,
  11484. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  11485. }
  11486. return computeResultTy();
  11487. }
  11488. if (LHSType->isObjCObjectPointerType() &&
  11489. RHSType->isObjCObjectPointerType()) {
  11490. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  11491. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  11492. /*isError*/false);
  11493. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  11494. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  11495. if (LHSIsNull && !RHSIsNull)
  11496. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  11497. else
  11498. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  11499. return computeResultTy();
  11500. }
  11501. if (!IsOrdered && LHSType->isBlockPointerType() &&
  11502. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  11503. LHS = ImpCastExprToType(LHS.get(), RHSType,
  11504. CK_BlockPointerToObjCPointerCast);
  11505. return computeResultTy();
  11506. } else if (!IsOrdered &&
  11507. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  11508. RHSType->isBlockPointerType()) {
  11509. RHS = ImpCastExprToType(RHS.get(), LHSType,
  11510. CK_BlockPointerToObjCPointerCast);
  11511. return computeResultTy();
  11512. }
  11513. }
  11514. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  11515. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  11516. unsigned DiagID = 0;
  11517. bool isError = false;
  11518. if (LangOpts.DebuggerSupport) {
  11519. // Under a debugger, allow the comparison of pointers to integers,
  11520. // since users tend to want to compare addresses.
  11521. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  11522. (RHSIsNull && RHSType->isIntegerType())) {
  11523. if (IsOrdered) {
  11524. isError = getLangOpts().CPlusPlus;
  11525. DiagID =
  11526. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  11527. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  11528. }
  11529. } else if (getLangOpts().CPlusPlus) {
  11530. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  11531. isError = true;
  11532. } else if (IsOrdered)
  11533. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  11534. else
  11535. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  11536. if (DiagID) {
  11537. Diag(Loc, DiagID)
  11538. << LHSType << RHSType << LHS.get()->getSourceRange()
  11539. << RHS.get()->getSourceRange();
  11540. if (isError)
  11541. return QualType();
  11542. }
  11543. if (LHSType->isIntegerType())
  11544. LHS = ImpCastExprToType(LHS.get(), RHSType,
  11545. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  11546. else
  11547. RHS = ImpCastExprToType(RHS.get(), LHSType,
  11548. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  11549. return computeResultTy();
  11550. }
  11551. // Handle block pointers.
  11552. if (!IsOrdered && RHSIsNull
  11553. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  11554. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  11555. return computeResultTy();
  11556. }
  11557. if (!IsOrdered && LHSIsNull
  11558. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  11559. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  11560. return computeResultTy();
  11561. }
  11562. if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
  11563. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  11564. return computeResultTy();
  11565. }
  11566. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  11567. return computeResultTy();
  11568. }
  11569. if (LHSIsNull && RHSType->isQueueT()) {
  11570. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  11571. return computeResultTy();
  11572. }
  11573. if (LHSType->isQueueT() && RHSIsNull) {
  11574. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  11575. return computeResultTy();
  11576. }
  11577. }
  11578. return InvalidOperands(Loc, LHS, RHS);
  11579. }
  11580. // Return a signed ext_vector_type that is of identical size and number of
  11581. // elements. For floating point vectors, return an integer type of identical
  11582. // size and number of elements. In the non ext_vector_type case, search from
  11583. // the largest type to the smallest type to avoid cases where long long == long,
  11584. // where long gets picked over long long.
  11585. QualType Sema::GetSignedVectorType(QualType V) {
  11586. const VectorType *VTy = V->castAs<VectorType>();
  11587. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  11588. if (isa<ExtVectorType>(VTy)) {
  11589. if (VTy->isExtVectorBoolType())
  11590. return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
  11591. if (TypeSize == Context.getTypeSize(Context.CharTy))
  11592. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  11593. if (TypeSize == Context.getTypeSize(Context.ShortTy))
  11594. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  11595. if (TypeSize == Context.getTypeSize(Context.IntTy))
  11596. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  11597. if (TypeSize == Context.getTypeSize(Context.Int128Ty))
  11598. return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
  11599. if (TypeSize == Context.getTypeSize(Context.LongTy))
  11600. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  11601. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  11602. "Unhandled vector element size in vector compare");
  11603. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  11604. }
  11605. if (TypeSize == Context.getTypeSize(Context.Int128Ty))
  11606. return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
  11607. VectorType::GenericVector);
  11608. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  11609. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  11610. VectorType::GenericVector);
  11611. if (TypeSize == Context.getTypeSize(Context.LongTy))
  11612. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  11613. VectorType::GenericVector);
  11614. if (TypeSize == Context.getTypeSize(Context.IntTy))
  11615. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  11616. VectorType::GenericVector);
  11617. if (TypeSize == Context.getTypeSize(Context.ShortTy))
  11618. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  11619. VectorType::GenericVector);
  11620. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  11621. "Unhandled vector element size in vector compare");
  11622. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  11623. VectorType::GenericVector);
  11624. }
  11625. QualType Sema::GetSignedSizelessVectorType(QualType V) {
  11626. const BuiltinType *VTy = V->castAs<BuiltinType>();
  11627. assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
  11628. const QualType ETy = V->getSveEltType(Context);
  11629. const auto TypeSize = Context.getTypeSize(ETy);
  11630. const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
  11631. const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
  11632. return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
  11633. }
  11634. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  11635. /// operates on extended vector types. Instead of producing an IntTy result,
  11636. /// like a scalar comparison, a vector comparison produces a vector of integer
  11637. /// types.
  11638. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  11639. SourceLocation Loc,
  11640. BinaryOperatorKind Opc) {
  11641. if (Opc == BO_Cmp) {
  11642. Diag(Loc, diag::err_three_way_vector_comparison);
  11643. return QualType();
  11644. }
  11645. // Check to make sure we're operating on vectors of the same type and width,
  11646. // Allowing one side to be a scalar of element type.
  11647. QualType vType =
  11648. CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
  11649. /*AllowBothBool*/ true,
  11650. /*AllowBoolConversions*/ getLangOpts().ZVector,
  11651. /*AllowBooleanOperation*/ true,
  11652. /*ReportInvalid*/ true);
  11653. if (vType.isNull())
  11654. return vType;
  11655. QualType LHSType = LHS.get()->getType();
  11656. // Determine the return type of a vector compare. By default clang will return
  11657. // a scalar for all vector compares except vector bool and vector pixel.
  11658. // With the gcc compiler we will always return a vector type and with the xl
  11659. // compiler we will always return a scalar type. This switch allows choosing
  11660. // which behavior is prefered.
  11661. if (getLangOpts().AltiVec) {
  11662. switch (getLangOpts().getAltivecSrcCompat()) {
  11663. case LangOptions::AltivecSrcCompatKind::Mixed:
  11664. // If AltiVec, the comparison results in a numeric type, i.e.
  11665. // bool for C++, int for C
  11666. if (vType->castAs<VectorType>()->getVectorKind() ==
  11667. VectorType::AltiVecVector)
  11668. return Context.getLogicalOperationType();
  11669. else
  11670. Diag(Loc, diag::warn_deprecated_altivec_src_compat);
  11671. break;
  11672. case LangOptions::AltivecSrcCompatKind::GCC:
  11673. // For GCC we always return the vector type.
  11674. break;
  11675. case LangOptions::AltivecSrcCompatKind::XL:
  11676. return Context.getLogicalOperationType();
  11677. break;
  11678. }
  11679. }
  11680. // For non-floating point types, check for self-comparisons of the form
  11681. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  11682. // often indicate logic errors in the program.
  11683. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  11684. // Check for comparisons of floating point operands using != and ==.
  11685. if (LHSType->hasFloatingRepresentation()) {
  11686. assert(RHS.get()->getType()->hasFloatingRepresentation());
  11687. CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
  11688. }
  11689. // Return a signed type for the vector.
  11690. return GetSignedVectorType(vType);
  11691. }
  11692. QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
  11693. ExprResult &RHS,
  11694. SourceLocation Loc,
  11695. BinaryOperatorKind Opc) {
  11696. if (Opc == BO_Cmp) {
  11697. Diag(Loc, diag::err_three_way_vector_comparison);
  11698. return QualType();
  11699. }
  11700. // Check to make sure we're operating on vectors of the same type and width,
  11701. // Allowing one side to be a scalar of element type.
  11702. QualType vType = CheckSizelessVectorOperands(
  11703. LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
  11704. if (vType.isNull())
  11705. return vType;
  11706. QualType LHSType = LHS.get()->getType();
  11707. // For non-floating point types, check for self-comparisons of the form
  11708. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  11709. // often indicate logic errors in the program.
  11710. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  11711. // Check for comparisons of floating point operands using != and ==.
  11712. if (LHSType->hasFloatingRepresentation()) {
  11713. assert(RHS.get()->getType()->hasFloatingRepresentation());
  11714. CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
  11715. }
  11716. const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
  11717. const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
  11718. if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
  11719. RHSBuiltinTy->isSVEBool())
  11720. return LHSType;
  11721. // Return a signed type for the vector.
  11722. return GetSignedSizelessVectorType(vType);
  11723. }
  11724. static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
  11725. const ExprResult &XorRHS,
  11726. const SourceLocation Loc) {
  11727. // Do not diagnose macros.
  11728. if (Loc.isMacroID())
  11729. return;
  11730. // Do not diagnose if both LHS and RHS are macros.
  11731. if (XorLHS.get()->getExprLoc().isMacroID() &&
  11732. XorRHS.get()->getExprLoc().isMacroID())
  11733. return;
  11734. bool Negative = false;
  11735. bool ExplicitPlus = false;
  11736. const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
  11737. const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
  11738. if (!LHSInt)
  11739. return;
  11740. if (!RHSInt) {
  11741. // Check negative literals.
  11742. if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
  11743. UnaryOperatorKind Opc = UO->getOpcode();
  11744. if (Opc != UO_Minus && Opc != UO_Plus)
  11745. return;
  11746. RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
  11747. if (!RHSInt)
  11748. return;
  11749. Negative = (Opc == UO_Minus);
  11750. ExplicitPlus = !Negative;
  11751. } else {
  11752. return;
  11753. }
  11754. }
  11755. const llvm::APInt &LeftSideValue = LHSInt->getValue();
  11756. llvm::APInt RightSideValue = RHSInt->getValue();
  11757. if (LeftSideValue != 2 && LeftSideValue != 10)
  11758. return;
  11759. if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
  11760. return;
  11761. CharSourceRange ExprRange = CharSourceRange::getCharRange(
  11762. LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
  11763. llvm::StringRef ExprStr =
  11764. Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
  11765. CharSourceRange XorRange =
  11766. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  11767. llvm::StringRef XorStr =
  11768. Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
  11769. // Do not diagnose if xor keyword/macro is used.
  11770. if (XorStr == "xor")
  11771. return;
  11772. std::string LHSStr = std::string(Lexer::getSourceText(
  11773. CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
  11774. S.getSourceManager(), S.getLangOpts()));
  11775. std::string RHSStr = std::string(Lexer::getSourceText(
  11776. CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
  11777. S.getSourceManager(), S.getLangOpts()));
  11778. if (Negative) {
  11779. RightSideValue = -RightSideValue;
  11780. RHSStr = "-" + RHSStr;
  11781. } else if (ExplicitPlus) {
  11782. RHSStr = "+" + RHSStr;
  11783. }
  11784. StringRef LHSStrRef = LHSStr;
  11785. StringRef RHSStrRef = RHSStr;
  11786. // Do not diagnose literals with digit separators, binary, hexadecimal, octal
  11787. // literals.
  11788. if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
  11789. RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
  11790. LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
  11791. RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
  11792. (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
  11793. (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
  11794. LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
  11795. return;
  11796. bool SuggestXor =
  11797. S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
  11798. const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
  11799. int64_t RightSideIntValue = RightSideValue.getSExtValue();
  11800. if (LeftSideValue == 2 && RightSideIntValue >= 0) {
  11801. std::string SuggestedExpr = "1 << " + RHSStr;
  11802. bool Overflow = false;
  11803. llvm::APInt One = (LeftSideValue - 1);
  11804. llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
  11805. if (Overflow) {
  11806. if (RightSideIntValue < 64)
  11807. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  11808. << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
  11809. << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
  11810. else if (RightSideIntValue == 64)
  11811. S.Diag(Loc, diag::warn_xor_used_as_pow)
  11812. << ExprStr << toString(XorValue, 10, true);
  11813. else
  11814. return;
  11815. } else {
  11816. S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
  11817. << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
  11818. << toString(PowValue, 10, true)
  11819. << FixItHint::CreateReplacement(
  11820. ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
  11821. }
  11822. S.Diag(Loc, diag::note_xor_used_as_pow_silence)
  11823. << ("0x2 ^ " + RHSStr) << SuggestXor;
  11824. } else if (LeftSideValue == 10) {
  11825. std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
  11826. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  11827. << ExprStr << toString(XorValue, 10, true) << SuggestedValue
  11828. << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
  11829. S.Diag(Loc, diag::note_xor_used_as_pow_silence)
  11830. << ("0xA ^ " + RHSStr) << SuggestXor;
  11831. }
  11832. }
  11833. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  11834. SourceLocation Loc) {
  11835. // Ensure that either both operands are of the same vector type, or
  11836. // one operand is of a vector type and the other is of its element type.
  11837. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  11838. /*AllowBothBool*/ true,
  11839. /*AllowBoolConversions*/ false,
  11840. /*AllowBooleanOperation*/ false,
  11841. /*ReportInvalid*/ false);
  11842. if (vType.isNull())
  11843. return InvalidOperands(Loc, LHS, RHS);
  11844. if (getLangOpts().OpenCL &&
  11845. getLangOpts().getOpenCLCompatibleVersion() < 120 &&
  11846. vType->hasFloatingRepresentation())
  11847. return InvalidOperands(Loc, LHS, RHS);
  11848. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  11849. // usage of the logical operators && and || with vectors in C. This
  11850. // check could be notionally dropped.
  11851. if (!getLangOpts().CPlusPlus &&
  11852. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  11853. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  11854. return GetSignedVectorType(LHS.get()->getType());
  11855. }
  11856. QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
  11857. SourceLocation Loc,
  11858. bool IsCompAssign) {
  11859. if (!IsCompAssign) {
  11860. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  11861. if (LHS.isInvalid())
  11862. return QualType();
  11863. }
  11864. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  11865. if (RHS.isInvalid())
  11866. return QualType();
  11867. // For conversion purposes, we ignore any qualifiers.
  11868. // For example, "const float" and "float" are equivalent.
  11869. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  11870. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  11871. const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
  11872. const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
  11873. assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
  11874. if (Context.hasSameType(LHSType, RHSType))
  11875. return Context.getCommonSugaredType(LHSType, RHSType);
  11876. // Type conversion may change LHS/RHS. Keep copies to the original results, in
  11877. // case we have to return InvalidOperands.
  11878. ExprResult OriginalLHS = LHS;
  11879. ExprResult OriginalRHS = RHS;
  11880. if (LHSMatType && !RHSMatType) {
  11881. RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
  11882. if (!RHS.isInvalid())
  11883. return LHSType;
  11884. return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
  11885. }
  11886. if (!LHSMatType && RHSMatType) {
  11887. LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
  11888. if (!LHS.isInvalid())
  11889. return RHSType;
  11890. return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
  11891. }
  11892. return InvalidOperands(Loc, LHS, RHS);
  11893. }
  11894. QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
  11895. SourceLocation Loc,
  11896. bool IsCompAssign) {
  11897. if (!IsCompAssign) {
  11898. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  11899. if (LHS.isInvalid())
  11900. return QualType();
  11901. }
  11902. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  11903. if (RHS.isInvalid())
  11904. return QualType();
  11905. auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
  11906. auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
  11907. assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
  11908. if (LHSMatType && RHSMatType) {
  11909. if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
  11910. return InvalidOperands(Loc, LHS, RHS);
  11911. if (Context.hasSameType(LHSMatType, RHSMatType))
  11912. return Context.getCommonSugaredType(
  11913. LHS.get()->getType().getUnqualifiedType(),
  11914. RHS.get()->getType().getUnqualifiedType());
  11915. QualType LHSELTy = LHSMatType->getElementType(),
  11916. RHSELTy = RHSMatType->getElementType();
  11917. if (!Context.hasSameType(LHSELTy, RHSELTy))
  11918. return InvalidOperands(Loc, LHS, RHS);
  11919. return Context.getConstantMatrixType(
  11920. Context.getCommonSugaredType(LHSELTy, RHSELTy),
  11921. LHSMatType->getNumRows(), RHSMatType->getNumColumns());
  11922. }
  11923. return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
  11924. }
  11925. static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
  11926. switch (Opc) {
  11927. default:
  11928. return false;
  11929. case BO_And:
  11930. case BO_AndAssign:
  11931. case BO_Or:
  11932. case BO_OrAssign:
  11933. case BO_Xor:
  11934. case BO_XorAssign:
  11935. return true;
  11936. }
  11937. }
  11938. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  11939. SourceLocation Loc,
  11940. BinaryOperatorKind Opc) {
  11941. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  11942. bool IsCompAssign =
  11943. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  11944. bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
  11945. if (LHS.get()->getType()->isVectorType() ||
  11946. RHS.get()->getType()->isVectorType()) {
  11947. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  11948. RHS.get()->getType()->hasIntegerRepresentation())
  11949. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  11950. /*AllowBothBool*/ true,
  11951. /*AllowBoolConversions*/ getLangOpts().ZVector,
  11952. /*AllowBooleanOperation*/ LegalBoolVecOperator,
  11953. /*ReportInvalid*/ true);
  11954. return InvalidOperands(Loc, LHS, RHS);
  11955. }
  11956. if (LHS.get()->getType()->isVLSTBuiltinType() ||
  11957. RHS.get()->getType()->isVLSTBuiltinType()) {
  11958. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  11959. RHS.get()->getType()->hasIntegerRepresentation())
  11960. return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
  11961. ACK_BitwiseOp);
  11962. return InvalidOperands(Loc, LHS, RHS);
  11963. }
  11964. if (LHS.get()->getType()->isVLSTBuiltinType() ||
  11965. RHS.get()->getType()->isVLSTBuiltinType()) {
  11966. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  11967. RHS.get()->getType()->hasIntegerRepresentation())
  11968. return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
  11969. ACK_BitwiseOp);
  11970. return InvalidOperands(Loc, LHS, RHS);
  11971. }
  11972. if (Opc == BO_And)
  11973. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  11974. if (LHS.get()->getType()->hasFloatingRepresentation() ||
  11975. RHS.get()->getType()->hasFloatingRepresentation())
  11976. return InvalidOperands(Loc, LHS, RHS);
  11977. ExprResult LHSResult = LHS, RHSResult = RHS;
  11978. QualType compType = UsualArithmeticConversions(
  11979. LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
  11980. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  11981. return QualType();
  11982. LHS = LHSResult.get();
  11983. RHS = RHSResult.get();
  11984. if (Opc == BO_Xor)
  11985. diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
  11986. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  11987. return compType;
  11988. return InvalidOperands(Loc, LHS, RHS);
  11989. }
  11990. // C99 6.5.[13,14]
  11991. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  11992. SourceLocation Loc,
  11993. BinaryOperatorKind Opc) {
  11994. // Check vector operands differently.
  11995. if (LHS.get()->getType()->isVectorType() ||
  11996. RHS.get()->getType()->isVectorType())
  11997. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  11998. bool EnumConstantInBoolContext = false;
  11999. for (const ExprResult &HS : {LHS, RHS}) {
  12000. if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
  12001. const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
  12002. if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
  12003. EnumConstantInBoolContext = true;
  12004. }
  12005. }
  12006. if (EnumConstantInBoolContext)
  12007. Diag(Loc, diag::warn_enum_constant_in_bool_context);
  12008. // Diagnose cases where the user write a logical and/or but probably meant a
  12009. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  12010. // is a constant.
  12011. if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
  12012. !LHS.get()->getType()->isBooleanType() &&
  12013. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  12014. // Don't warn in macros or template instantiations.
  12015. !Loc.isMacroID() && !inTemplateInstantiation()) {
  12016. // If the RHS can be constant folded, and if it constant folds to something
  12017. // that isn't 0 or 1 (which indicate a potential logical operation that
  12018. // happened to fold to true/false) then warn.
  12019. // Parens on the RHS are ignored.
  12020. Expr::EvalResult EVResult;
  12021. if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
  12022. llvm::APSInt Result = EVResult.Val.getInt();
  12023. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  12024. !RHS.get()->getExprLoc().isMacroID()) ||
  12025. (Result != 0 && Result != 1)) {
  12026. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  12027. << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
  12028. // Suggest replacing the logical operator with the bitwise version
  12029. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  12030. << (Opc == BO_LAnd ? "&" : "|")
  12031. << FixItHint::CreateReplacement(
  12032. SourceRange(Loc, getLocForEndOfToken(Loc)),
  12033. Opc == BO_LAnd ? "&" : "|");
  12034. if (Opc == BO_LAnd)
  12035. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  12036. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  12037. << FixItHint::CreateRemoval(
  12038. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  12039. RHS.get()->getEndLoc()));
  12040. }
  12041. }
  12042. }
  12043. if (!Context.getLangOpts().CPlusPlus) {
  12044. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  12045. // not operate on the built-in scalar and vector float types.
  12046. if (Context.getLangOpts().OpenCL &&
  12047. Context.getLangOpts().OpenCLVersion < 120) {
  12048. if (LHS.get()->getType()->isFloatingType() ||
  12049. RHS.get()->getType()->isFloatingType())
  12050. return InvalidOperands(Loc, LHS, RHS);
  12051. }
  12052. LHS = UsualUnaryConversions(LHS.get());
  12053. if (LHS.isInvalid())
  12054. return QualType();
  12055. RHS = UsualUnaryConversions(RHS.get());
  12056. if (RHS.isInvalid())
  12057. return QualType();
  12058. if (!LHS.get()->getType()->isScalarType() ||
  12059. !RHS.get()->getType()->isScalarType())
  12060. return InvalidOperands(Loc, LHS, RHS);
  12061. return Context.IntTy;
  12062. }
  12063. // The following is safe because we only use this method for
  12064. // non-overloadable operands.
  12065. // C++ [expr.log.and]p1
  12066. // C++ [expr.log.or]p1
  12067. // The operands are both contextually converted to type bool.
  12068. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  12069. if (LHSRes.isInvalid())
  12070. return InvalidOperands(Loc, LHS, RHS);
  12071. LHS = LHSRes;
  12072. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  12073. if (RHSRes.isInvalid())
  12074. return InvalidOperands(Loc, LHS, RHS);
  12075. RHS = RHSRes;
  12076. // C++ [expr.log.and]p2
  12077. // C++ [expr.log.or]p2
  12078. // The result is a bool.
  12079. return Context.BoolTy;
  12080. }
  12081. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  12082. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  12083. if (!ME) return false;
  12084. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  12085. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  12086. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  12087. if (!Base) return false;
  12088. return Base->getMethodDecl() != nullptr;
  12089. }
  12090. /// Is the given expression (which must be 'const') a reference to a
  12091. /// variable which was originally non-const, but which has become
  12092. /// 'const' due to being captured within a block?
  12093. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  12094. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  12095. assert(E->isLValue() && E->getType().isConstQualified());
  12096. E = E->IgnoreParens();
  12097. // Must be a reference to a declaration from an enclosing scope.
  12098. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  12099. if (!DRE) return NCCK_None;
  12100. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  12101. // The declaration must be a variable which is not declared 'const'.
  12102. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  12103. if (!var) return NCCK_None;
  12104. if (var->getType().isConstQualified()) return NCCK_None;
  12105. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  12106. // Decide whether the first capture was for a block or a lambda.
  12107. DeclContext *DC = S.CurContext, *Prev = nullptr;
  12108. // Decide whether the first capture was for a block or a lambda.
  12109. while (DC) {
  12110. // For init-capture, it is possible that the variable belongs to the
  12111. // template pattern of the current context.
  12112. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  12113. if (var->isInitCapture() &&
  12114. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  12115. break;
  12116. if (DC == var->getDeclContext())
  12117. break;
  12118. Prev = DC;
  12119. DC = DC->getParent();
  12120. }
  12121. // Unless we have an init-capture, we've gone one step too far.
  12122. if (!var->isInitCapture())
  12123. DC = Prev;
  12124. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  12125. }
  12126. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  12127. Ty = Ty.getNonReferenceType();
  12128. if (IsDereference && Ty->isPointerType())
  12129. Ty = Ty->getPointeeType();
  12130. return !Ty.isConstQualified();
  12131. }
  12132. // Update err_typecheck_assign_const and note_typecheck_assign_const
  12133. // when this enum is changed.
  12134. enum {
  12135. ConstFunction,
  12136. ConstVariable,
  12137. ConstMember,
  12138. ConstMethod,
  12139. NestedConstMember,
  12140. ConstUnknown, // Keep as last element
  12141. };
  12142. /// Emit the "read-only variable not assignable" error and print notes to give
  12143. /// more information about why the variable is not assignable, such as pointing
  12144. /// to the declaration of a const variable, showing that a method is const, or
  12145. /// that the function is returning a const reference.
  12146. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  12147. SourceLocation Loc) {
  12148. SourceRange ExprRange = E->getSourceRange();
  12149. // Only emit one error on the first const found. All other consts will emit
  12150. // a note to the error.
  12151. bool DiagnosticEmitted = false;
  12152. // Track if the current expression is the result of a dereference, and if the
  12153. // next checked expression is the result of a dereference.
  12154. bool IsDereference = false;
  12155. bool NextIsDereference = false;
  12156. // Loop to process MemberExpr chains.
  12157. while (true) {
  12158. IsDereference = NextIsDereference;
  12159. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  12160. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  12161. NextIsDereference = ME->isArrow();
  12162. const ValueDecl *VD = ME->getMemberDecl();
  12163. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  12164. // Mutable fields can be modified even if the class is const.
  12165. if (Field->isMutable()) {
  12166. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  12167. break;
  12168. }
  12169. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  12170. if (!DiagnosticEmitted) {
  12171. S.Diag(Loc, diag::err_typecheck_assign_const)
  12172. << ExprRange << ConstMember << false /*static*/ << Field
  12173. << Field->getType();
  12174. DiagnosticEmitted = true;
  12175. }
  12176. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  12177. << ConstMember << false /*static*/ << Field << Field->getType()
  12178. << Field->getSourceRange();
  12179. }
  12180. E = ME->getBase();
  12181. continue;
  12182. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  12183. if (VDecl->getType().isConstQualified()) {
  12184. if (!DiagnosticEmitted) {
  12185. S.Diag(Loc, diag::err_typecheck_assign_const)
  12186. << ExprRange << ConstMember << true /*static*/ << VDecl
  12187. << VDecl->getType();
  12188. DiagnosticEmitted = true;
  12189. }
  12190. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  12191. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  12192. << VDecl->getSourceRange();
  12193. }
  12194. // Static fields do not inherit constness from parents.
  12195. break;
  12196. }
  12197. break; // End MemberExpr
  12198. } else if (const ArraySubscriptExpr *ASE =
  12199. dyn_cast<ArraySubscriptExpr>(E)) {
  12200. E = ASE->getBase()->IgnoreParenImpCasts();
  12201. continue;
  12202. } else if (const ExtVectorElementExpr *EVE =
  12203. dyn_cast<ExtVectorElementExpr>(E)) {
  12204. E = EVE->getBase()->IgnoreParenImpCasts();
  12205. continue;
  12206. }
  12207. break;
  12208. }
  12209. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  12210. // Function calls
  12211. const FunctionDecl *FD = CE->getDirectCallee();
  12212. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  12213. if (!DiagnosticEmitted) {
  12214. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  12215. << ConstFunction << FD;
  12216. DiagnosticEmitted = true;
  12217. }
  12218. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  12219. diag::note_typecheck_assign_const)
  12220. << ConstFunction << FD << FD->getReturnType()
  12221. << FD->getReturnTypeSourceRange();
  12222. }
  12223. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  12224. // Point to variable declaration.
  12225. if (const ValueDecl *VD = DRE->getDecl()) {
  12226. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  12227. if (!DiagnosticEmitted) {
  12228. S.Diag(Loc, diag::err_typecheck_assign_const)
  12229. << ExprRange << ConstVariable << VD << VD->getType();
  12230. DiagnosticEmitted = true;
  12231. }
  12232. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  12233. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  12234. }
  12235. }
  12236. } else if (isa<CXXThisExpr>(E)) {
  12237. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  12238. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  12239. if (MD->isConst()) {
  12240. if (!DiagnosticEmitted) {
  12241. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  12242. << ConstMethod << MD;
  12243. DiagnosticEmitted = true;
  12244. }
  12245. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  12246. << ConstMethod << MD << MD->getSourceRange();
  12247. }
  12248. }
  12249. }
  12250. }
  12251. if (DiagnosticEmitted)
  12252. return;
  12253. // Can't determine a more specific message, so display the generic error.
  12254. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  12255. }
  12256. enum OriginalExprKind {
  12257. OEK_Variable,
  12258. OEK_Member,
  12259. OEK_LValue
  12260. };
  12261. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  12262. const RecordType *Ty,
  12263. SourceLocation Loc, SourceRange Range,
  12264. OriginalExprKind OEK,
  12265. bool &DiagnosticEmitted) {
  12266. std::vector<const RecordType *> RecordTypeList;
  12267. RecordTypeList.push_back(Ty);
  12268. unsigned NextToCheckIndex = 0;
  12269. // We walk the record hierarchy breadth-first to ensure that we print
  12270. // diagnostics in field nesting order.
  12271. while (RecordTypeList.size() > NextToCheckIndex) {
  12272. bool IsNested = NextToCheckIndex > 0;
  12273. for (const FieldDecl *Field :
  12274. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  12275. // First, check every field for constness.
  12276. QualType FieldTy = Field->getType();
  12277. if (FieldTy.isConstQualified()) {
  12278. if (!DiagnosticEmitted) {
  12279. S.Diag(Loc, diag::err_typecheck_assign_const)
  12280. << Range << NestedConstMember << OEK << VD
  12281. << IsNested << Field;
  12282. DiagnosticEmitted = true;
  12283. }
  12284. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  12285. << NestedConstMember << IsNested << Field
  12286. << FieldTy << Field->getSourceRange();
  12287. }
  12288. // Then we append it to the list to check next in order.
  12289. FieldTy = FieldTy.getCanonicalType();
  12290. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  12291. if (!llvm::is_contained(RecordTypeList, FieldRecTy))
  12292. RecordTypeList.push_back(FieldRecTy);
  12293. }
  12294. }
  12295. ++NextToCheckIndex;
  12296. }
  12297. }
  12298. /// Emit an error for the case where a record we are trying to assign to has a
  12299. /// const-qualified field somewhere in its hierarchy.
  12300. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  12301. SourceLocation Loc) {
  12302. QualType Ty = E->getType();
  12303. assert(Ty->isRecordType() && "lvalue was not record?");
  12304. SourceRange Range = E->getSourceRange();
  12305. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  12306. bool DiagEmitted = false;
  12307. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  12308. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  12309. Range, OEK_Member, DiagEmitted);
  12310. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  12311. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  12312. Range, OEK_Variable, DiagEmitted);
  12313. else
  12314. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  12315. Range, OEK_LValue, DiagEmitted);
  12316. if (!DiagEmitted)
  12317. DiagnoseConstAssignment(S, E, Loc);
  12318. }
  12319. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  12320. /// emit an error and return true. If so, return false.
  12321. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  12322. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  12323. S.CheckShadowingDeclModification(E, Loc);
  12324. SourceLocation OrigLoc = Loc;
  12325. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  12326. &Loc);
  12327. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  12328. IsLV = Expr::MLV_InvalidMessageExpression;
  12329. if (IsLV == Expr::MLV_Valid)
  12330. return false;
  12331. unsigned DiagID = 0;
  12332. bool NeedType = false;
  12333. switch (IsLV) { // C99 6.5.16p2
  12334. case Expr::MLV_ConstQualified:
  12335. // Use a specialized diagnostic when we're assigning to an object
  12336. // from an enclosing function or block.
  12337. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  12338. if (NCCK == NCCK_Block)
  12339. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  12340. else
  12341. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  12342. break;
  12343. }
  12344. // In ARC, use some specialized diagnostics for occasions where we
  12345. // infer 'const'. These are always pseudo-strong variables.
  12346. if (S.getLangOpts().ObjCAutoRefCount) {
  12347. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  12348. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  12349. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  12350. // Use the normal diagnostic if it's pseudo-__strong but the
  12351. // user actually wrote 'const'.
  12352. if (var->isARCPseudoStrong() &&
  12353. (!var->getTypeSourceInfo() ||
  12354. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  12355. // There are three pseudo-strong cases:
  12356. // - self
  12357. ObjCMethodDecl *method = S.getCurMethodDecl();
  12358. if (method && var == method->getSelfDecl()) {
  12359. DiagID = method->isClassMethod()
  12360. ? diag::err_typecheck_arc_assign_self_class_method
  12361. : diag::err_typecheck_arc_assign_self;
  12362. // - Objective-C externally_retained attribute.
  12363. } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
  12364. isa<ParmVarDecl>(var)) {
  12365. DiagID = diag::err_typecheck_arc_assign_externally_retained;
  12366. // - fast enumeration variables
  12367. } else {
  12368. DiagID = diag::err_typecheck_arr_assign_enumeration;
  12369. }
  12370. SourceRange Assign;
  12371. if (Loc != OrigLoc)
  12372. Assign = SourceRange(OrigLoc, OrigLoc);
  12373. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  12374. // We need to preserve the AST regardless, so migration tool
  12375. // can do its job.
  12376. return false;
  12377. }
  12378. }
  12379. }
  12380. // If none of the special cases above are triggered, then this is a
  12381. // simple const assignment.
  12382. if (DiagID == 0) {
  12383. DiagnoseConstAssignment(S, E, Loc);
  12384. return true;
  12385. }
  12386. break;
  12387. case Expr::MLV_ConstAddrSpace:
  12388. DiagnoseConstAssignment(S, E, Loc);
  12389. return true;
  12390. case Expr::MLV_ConstQualifiedField:
  12391. DiagnoseRecursiveConstFields(S, E, Loc);
  12392. return true;
  12393. case Expr::MLV_ArrayType:
  12394. case Expr::MLV_ArrayTemporary:
  12395. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  12396. NeedType = true;
  12397. break;
  12398. case Expr::MLV_NotObjectType:
  12399. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  12400. NeedType = true;
  12401. break;
  12402. case Expr::MLV_LValueCast:
  12403. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  12404. break;
  12405. case Expr::MLV_Valid:
  12406. llvm_unreachable("did not take early return for MLV_Valid");
  12407. case Expr::MLV_InvalidExpression:
  12408. case Expr::MLV_MemberFunction:
  12409. case Expr::MLV_ClassTemporary:
  12410. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  12411. break;
  12412. case Expr::MLV_IncompleteType:
  12413. case Expr::MLV_IncompleteVoidType:
  12414. return S.RequireCompleteType(Loc, E->getType(),
  12415. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  12416. case Expr::MLV_DuplicateVectorComponents:
  12417. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  12418. break;
  12419. case Expr::MLV_NoSetterProperty:
  12420. llvm_unreachable("readonly properties should be processed differently");
  12421. case Expr::MLV_InvalidMessageExpression:
  12422. DiagID = diag::err_readonly_message_assignment;
  12423. break;
  12424. case Expr::MLV_SubObjCPropertySetting:
  12425. DiagID = diag::err_no_subobject_property_setting;
  12426. break;
  12427. }
  12428. SourceRange Assign;
  12429. if (Loc != OrigLoc)
  12430. Assign = SourceRange(OrigLoc, OrigLoc);
  12431. if (NeedType)
  12432. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  12433. else
  12434. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  12435. return true;
  12436. }
  12437. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  12438. SourceLocation Loc,
  12439. Sema &Sema) {
  12440. if (Sema.inTemplateInstantiation())
  12441. return;
  12442. if (Sema.isUnevaluatedContext())
  12443. return;
  12444. if (Loc.isInvalid() || Loc.isMacroID())
  12445. return;
  12446. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  12447. return;
  12448. // C / C++ fields
  12449. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  12450. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  12451. if (ML && MR) {
  12452. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  12453. return;
  12454. const ValueDecl *LHSDecl =
  12455. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  12456. const ValueDecl *RHSDecl =
  12457. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  12458. if (LHSDecl != RHSDecl)
  12459. return;
  12460. if (LHSDecl->getType().isVolatileQualified())
  12461. return;
  12462. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  12463. if (RefTy->getPointeeType().isVolatileQualified())
  12464. return;
  12465. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  12466. }
  12467. // Objective-C instance variables
  12468. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  12469. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  12470. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  12471. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  12472. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  12473. if (RL && RR && RL->getDecl() == RR->getDecl())
  12474. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  12475. }
  12476. }
  12477. // C99 6.5.16.1
  12478. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  12479. SourceLocation Loc,
  12480. QualType CompoundType,
  12481. BinaryOperatorKind Opc) {
  12482. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  12483. // Verify that LHS is a modifiable lvalue, and emit error if not.
  12484. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  12485. return QualType();
  12486. QualType LHSType = LHSExpr->getType();
  12487. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  12488. CompoundType;
  12489. // OpenCL v1.2 s6.1.1.1 p2:
  12490. // The half data type can only be used to declare a pointer to a buffer that
  12491. // contains half values
  12492. if (getLangOpts().OpenCL &&
  12493. !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
  12494. LHSType->isHalfType()) {
  12495. Diag(Loc, diag::err_opencl_half_load_store) << 1
  12496. << LHSType.getUnqualifiedType();
  12497. return QualType();
  12498. }
  12499. AssignConvertType ConvTy;
  12500. if (CompoundType.isNull()) {
  12501. Expr *RHSCheck = RHS.get();
  12502. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  12503. QualType LHSTy(LHSType);
  12504. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  12505. if (RHS.isInvalid())
  12506. return QualType();
  12507. // Special case of NSObject attributes on c-style pointer types.
  12508. if (ConvTy == IncompatiblePointer &&
  12509. ((Context.isObjCNSObjectType(LHSType) &&
  12510. RHSType->isObjCObjectPointerType()) ||
  12511. (Context.isObjCNSObjectType(RHSType) &&
  12512. LHSType->isObjCObjectPointerType())))
  12513. ConvTy = Compatible;
  12514. if (ConvTy == Compatible &&
  12515. LHSType->isObjCObjectType())
  12516. Diag(Loc, diag::err_objc_object_assignment)
  12517. << LHSType;
  12518. // If the RHS is a unary plus or minus, check to see if they = and + are
  12519. // right next to each other. If so, the user may have typo'd "x =+ 4"
  12520. // instead of "x += 4".
  12521. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  12522. RHSCheck = ICE->getSubExpr();
  12523. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  12524. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  12525. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  12526. // Only if the two operators are exactly adjacent.
  12527. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  12528. // And there is a space or other character before the subexpr of the
  12529. // unary +/-. We don't want to warn on "x=-1".
  12530. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  12531. UO->getSubExpr()->getBeginLoc().isFileID()) {
  12532. Diag(Loc, diag::warn_not_compound_assign)
  12533. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  12534. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  12535. }
  12536. }
  12537. if (ConvTy == Compatible) {
  12538. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  12539. // Warn about retain cycles where a block captures the LHS, but
  12540. // not if the LHS is a simple variable into which the block is
  12541. // being stored...unless that variable can be captured by reference!
  12542. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  12543. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  12544. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  12545. checkRetainCycles(LHSExpr, RHS.get());
  12546. }
  12547. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  12548. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  12549. // It is safe to assign a weak reference into a strong variable.
  12550. // Although this code can still have problems:
  12551. // id x = self.weakProp;
  12552. // id y = self.weakProp;
  12553. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  12554. // paths through the function. This should be revisited if
  12555. // -Wrepeated-use-of-weak is made flow-sensitive.
  12556. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  12557. // variable, which will be valid for the current autorelease scope.
  12558. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  12559. RHS.get()->getBeginLoc()))
  12560. getCurFunction()->markSafeWeakUse(RHS.get());
  12561. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  12562. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  12563. }
  12564. }
  12565. } else {
  12566. // Compound assignment "x += y"
  12567. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  12568. }
  12569. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  12570. RHS.get(), AA_Assigning))
  12571. return QualType();
  12572. CheckForNullPointerDereference(*this, LHSExpr);
  12573. if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
  12574. if (CompoundType.isNull()) {
  12575. // C++2a [expr.ass]p5:
  12576. // A simple-assignment whose left operand is of a volatile-qualified
  12577. // type is deprecated unless the assignment is either a discarded-value
  12578. // expression or an unevaluated operand
  12579. ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
  12580. }
  12581. }
  12582. // C11 6.5.16p3: The type of an assignment expression is the type of the
  12583. // left operand would have after lvalue conversion.
  12584. // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
  12585. // qualified type, the value has the unqualified version of the type of the
  12586. // lvalue; additionally, if the lvalue has atomic type, the value has the
  12587. // non-atomic version of the type of the lvalue.
  12588. // C++ 5.17p1: the type of the assignment expression is that of its left
  12589. // operand.
  12590. return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
  12591. }
  12592. // Scenarios to ignore if expression E is:
  12593. // 1. an explicit cast expression into void
  12594. // 2. a function call expression that returns void
  12595. static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
  12596. E = E->IgnoreParens();
  12597. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  12598. if (CE->getCastKind() == CK_ToVoid) {
  12599. return true;
  12600. }
  12601. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  12602. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  12603. CE->getSubExpr()->getType()->isDependentType()) {
  12604. return true;
  12605. }
  12606. }
  12607. if (const auto *CE = dyn_cast<CallExpr>(E))
  12608. return CE->getCallReturnType(Context)->isVoidType();
  12609. return false;
  12610. }
  12611. // Look for instances where it is likely the comma operator is confused with
  12612. // another operator. There is an explicit list of acceptable expressions for
  12613. // the left hand side of the comma operator, otherwise emit a warning.
  12614. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  12615. // No warnings in macros
  12616. if (Loc.isMacroID())
  12617. return;
  12618. // Don't warn in template instantiations.
  12619. if (inTemplateInstantiation())
  12620. return;
  12621. // Scope isn't fine-grained enough to explicitly list the specific cases, so
  12622. // instead, skip more than needed, then call back into here with the
  12623. // CommaVisitor in SemaStmt.cpp.
  12624. // The listed locations are the initialization and increment portions
  12625. // of a for loop. The additional checks are on the condition of
  12626. // if statements, do/while loops, and for loops.
  12627. // Differences in scope flags for C89 mode requires the extra logic.
  12628. const unsigned ForIncrementFlags =
  12629. getLangOpts().C99 || getLangOpts().CPlusPlus
  12630. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  12631. : Scope::ContinueScope | Scope::BreakScope;
  12632. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  12633. const unsigned ScopeFlags = getCurScope()->getFlags();
  12634. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  12635. (ScopeFlags & ForInitFlags) == ForInitFlags)
  12636. return;
  12637. // If there are multiple comma operators used together, get the RHS of the
  12638. // of the comma operator as the LHS.
  12639. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  12640. if (BO->getOpcode() != BO_Comma)
  12641. break;
  12642. LHS = BO->getRHS();
  12643. }
  12644. // Only allow some expressions on LHS to not warn.
  12645. if (IgnoreCommaOperand(LHS, Context))
  12646. return;
  12647. Diag(Loc, diag::warn_comma_operator);
  12648. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  12649. << LHS->getSourceRange()
  12650. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  12651. LangOpts.CPlusPlus ? "static_cast<void>("
  12652. : "(void)(")
  12653. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  12654. ")");
  12655. }
  12656. // C99 6.5.17
  12657. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  12658. SourceLocation Loc) {
  12659. LHS = S.CheckPlaceholderExpr(LHS.get());
  12660. RHS = S.CheckPlaceholderExpr(RHS.get());
  12661. if (LHS.isInvalid() || RHS.isInvalid())
  12662. return QualType();
  12663. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  12664. // operands, but not unary promotions.
  12665. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  12666. // So we treat the LHS as a ignored value, and in C++ we allow the
  12667. // containing site to determine what should be done with the RHS.
  12668. LHS = S.IgnoredValueConversions(LHS.get());
  12669. if (LHS.isInvalid())
  12670. return QualType();
  12671. S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
  12672. if (!S.getLangOpts().CPlusPlus) {
  12673. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  12674. if (RHS.isInvalid())
  12675. return QualType();
  12676. if (!RHS.get()->getType()->isVoidType())
  12677. S.RequireCompleteType(Loc, RHS.get()->getType(),
  12678. diag::err_incomplete_type);
  12679. }
  12680. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  12681. S.DiagnoseCommaOperator(LHS.get(), Loc);
  12682. return RHS.get()->getType();
  12683. }
  12684. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  12685. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  12686. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  12687. ExprValueKind &VK,
  12688. ExprObjectKind &OK,
  12689. SourceLocation OpLoc,
  12690. bool IsInc, bool IsPrefix) {
  12691. if (Op->isTypeDependent())
  12692. return S.Context.DependentTy;
  12693. QualType ResType = Op->getType();
  12694. // Atomic types can be used for increment / decrement where the non-atomic
  12695. // versions can, so ignore the _Atomic() specifier for the purpose of
  12696. // checking.
  12697. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  12698. ResType = ResAtomicType->getValueType();
  12699. assert(!ResType.isNull() && "no type for increment/decrement expression");
  12700. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  12701. // Decrement of bool is not allowed.
  12702. if (!IsInc) {
  12703. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  12704. return QualType();
  12705. }
  12706. // Increment of bool sets it to true, but is deprecated.
  12707. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  12708. : diag::warn_increment_bool)
  12709. << Op->getSourceRange();
  12710. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  12711. // Error on enum increments and decrements in C++ mode
  12712. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  12713. return QualType();
  12714. } else if (ResType->isRealType()) {
  12715. // OK!
  12716. } else if (ResType->isPointerType()) {
  12717. // C99 6.5.2.4p2, 6.5.6p2
  12718. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  12719. return QualType();
  12720. } else if (ResType->isObjCObjectPointerType()) {
  12721. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  12722. // Otherwise, we just need a complete type.
  12723. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  12724. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  12725. return QualType();
  12726. } else if (ResType->isAnyComplexType()) {
  12727. // C99 does not support ++/-- on complex types, we allow as an extension.
  12728. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  12729. << ResType << Op->getSourceRange();
  12730. } else if (ResType->isPlaceholderType()) {
  12731. ExprResult PR = S.CheckPlaceholderExpr(Op);
  12732. if (PR.isInvalid()) return QualType();
  12733. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  12734. IsInc, IsPrefix);
  12735. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  12736. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  12737. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  12738. (ResType->castAs<VectorType>()->getVectorKind() !=
  12739. VectorType::AltiVecBool)) {
  12740. // The z vector extensions allow ++ and -- for non-bool vectors.
  12741. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  12742. ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
  12743. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  12744. } else {
  12745. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  12746. << ResType << int(IsInc) << Op->getSourceRange();
  12747. return QualType();
  12748. }
  12749. // At this point, we know we have a real, complex or pointer type.
  12750. // Now make sure the operand is a modifiable lvalue.
  12751. if (CheckForModifiableLvalue(Op, OpLoc, S))
  12752. return QualType();
  12753. if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
  12754. // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
  12755. // An operand with volatile-qualified type is deprecated
  12756. S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
  12757. << IsInc << ResType;
  12758. }
  12759. // In C++, a prefix increment is the same type as the operand. Otherwise
  12760. // (in C or with postfix), the increment is the unqualified type of the
  12761. // operand.
  12762. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  12763. VK = VK_LValue;
  12764. OK = Op->getObjectKind();
  12765. return ResType;
  12766. } else {
  12767. VK = VK_PRValue;
  12768. return ResType.getUnqualifiedType();
  12769. }
  12770. }
  12771. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  12772. /// This routine allows us to typecheck complex/recursive expressions
  12773. /// where the declaration is needed for type checking. We only need to
  12774. /// handle cases when the expression references a function designator
  12775. /// or is an lvalue. Here are some examples:
  12776. /// - &(x) => x
  12777. /// - &*****f => f for f a function designator.
  12778. /// - &s.xx => s
  12779. /// - &s.zz[1].yy -> s, if zz is an array
  12780. /// - *(x + 1) -> x, if x is an array
  12781. /// - &"123"[2] -> 0
  12782. /// - & __real__ x -> x
  12783. ///
  12784. /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
  12785. /// members.
  12786. static ValueDecl *getPrimaryDecl(Expr *E) {
  12787. switch (E->getStmtClass()) {
  12788. case Stmt::DeclRefExprClass:
  12789. return cast<DeclRefExpr>(E)->getDecl();
  12790. case Stmt::MemberExprClass:
  12791. // If this is an arrow operator, the address is an offset from
  12792. // the base's value, so the object the base refers to is
  12793. // irrelevant.
  12794. if (cast<MemberExpr>(E)->isArrow())
  12795. return nullptr;
  12796. // Otherwise, the expression refers to a part of the base
  12797. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  12798. case Stmt::ArraySubscriptExprClass: {
  12799. // FIXME: This code shouldn't be necessary! We should catch the implicit
  12800. // promotion of register arrays earlier.
  12801. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  12802. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  12803. if (ICE->getSubExpr()->getType()->isArrayType())
  12804. return getPrimaryDecl(ICE->getSubExpr());
  12805. }
  12806. return nullptr;
  12807. }
  12808. case Stmt::UnaryOperatorClass: {
  12809. UnaryOperator *UO = cast<UnaryOperator>(E);
  12810. switch(UO->getOpcode()) {
  12811. case UO_Real:
  12812. case UO_Imag:
  12813. case UO_Extension:
  12814. return getPrimaryDecl(UO->getSubExpr());
  12815. default:
  12816. return nullptr;
  12817. }
  12818. }
  12819. case Stmt::ParenExprClass:
  12820. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  12821. case Stmt::ImplicitCastExprClass:
  12822. // If the result of an implicit cast is an l-value, we care about
  12823. // the sub-expression; otherwise, the result here doesn't matter.
  12824. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  12825. case Stmt::CXXUuidofExprClass:
  12826. return cast<CXXUuidofExpr>(E)->getGuidDecl();
  12827. default:
  12828. return nullptr;
  12829. }
  12830. }
  12831. namespace {
  12832. enum {
  12833. AO_Bit_Field = 0,
  12834. AO_Vector_Element = 1,
  12835. AO_Property_Expansion = 2,
  12836. AO_Register_Variable = 3,
  12837. AO_Matrix_Element = 4,
  12838. AO_No_Error = 5
  12839. };
  12840. }
  12841. /// Diagnose invalid operand for address of operations.
  12842. ///
  12843. /// \param Type The type of operand which cannot have its address taken.
  12844. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  12845. Expr *E, unsigned Type) {
  12846. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  12847. }
  12848. /// CheckAddressOfOperand - The operand of & must be either a function
  12849. /// designator or an lvalue designating an object. If it is an lvalue, the
  12850. /// object cannot be declared with storage class register or be a bit field.
  12851. /// Note: The usual conversions are *not* applied to the operand of the &
  12852. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  12853. /// In C++, the operand might be an overloaded function name, in which case
  12854. /// we allow the '&' but retain the overloaded-function type.
  12855. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  12856. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  12857. if (PTy->getKind() == BuiltinType::Overload) {
  12858. Expr *E = OrigOp.get()->IgnoreParens();
  12859. if (!isa<OverloadExpr>(E)) {
  12860. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  12861. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  12862. << OrigOp.get()->getSourceRange();
  12863. return QualType();
  12864. }
  12865. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  12866. if (isa<UnresolvedMemberExpr>(Ovl))
  12867. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  12868. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  12869. << OrigOp.get()->getSourceRange();
  12870. return QualType();
  12871. }
  12872. return Context.OverloadTy;
  12873. }
  12874. if (PTy->getKind() == BuiltinType::UnknownAny)
  12875. return Context.UnknownAnyTy;
  12876. if (PTy->getKind() == BuiltinType::BoundMember) {
  12877. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  12878. << OrigOp.get()->getSourceRange();
  12879. return QualType();
  12880. }
  12881. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  12882. if (OrigOp.isInvalid()) return QualType();
  12883. }
  12884. if (OrigOp.get()->isTypeDependent())
  12885. return Context.DependentTy;
  12886. assert(!OrigOp.get()->hasPlaceholderType());
  12887. // Make sure to ignore parentheses in subsequent checks
  12888. Expr *op = OrigOp.get()->IgnoreParens();
  12889. // In OpenCL captures for blocks called as lambda functions
  12890. // are located in the private address space. Blocks used in
  12891. // enqueue_kernel can be located in a different address space
  12892. // depending on a vendor implementation. Thus preventing
  12893. // taking an address of the capture to avoid invalid AS casts.
  12894. if (LangOpts.OpenCL) {
  12895. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  12896. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  12897. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  12898. return QualType();
  12899. }
  12900. }
  12901. if (getLangOpts().C99) {
  12902. // Implement C99-only parts of addressof rules.
  12903. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  12904. if (uOp->getOpcode() == UO_Deref)
  12905. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  12906. // (assuming the deref expression is valid).
  12907. return uOp->getSubExpr()->getType();
  12908. }
  12909. // Technically, there should be a check for array subscript
  12910. // expressions here, but the result of one is always an lvalue anyway.
  12911. }
  12912. ValueDecl *dcl = getPrimaryDecl(op);
  12913. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  12914. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  12915. op->getBeginLoc()))
  12916. return QualType();
  12917. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  12918. unsigned AddressOfError = AO_No_Error;
  12919. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  12920. bool sfinae = (bool)isSFINAEContext();
  12921. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  12922. : diag::ext_typecheck_addrof_temporary)
  12923. << op->getType() << op->getSourceRange();
  12924. if (sfinae)
  12925. return QualType();
  12926. // Materialize the temporary as an lvalue so that we can take its address.
  12927. OrigOp = op =
  12928. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  12929. } else if (isa<ObjCSelectorExpr>(op)) {
  12930. return Context.getPointerType(op->getType());
  12931. } else if (lval == Expr::LV_MemberFunction) {
  12932. // If it's an instance method, make a member pointer.
  12933. // The expression must have exactly the form &A::foo.
  12934. // If the underlying expression isn't a decl ref, give up.
  12935. if (!isa<DeclRefExpr>(op)) {
  12936. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  12937. << OrigOp.get()->getSourceRange();
  12938. return QualType();
  12939. }
  12940. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  12941. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  12942. // The id-expression was parenthesized.
  12943. if (OrigOp.get() != DRE) {
  12944. Diag(OpLoc, diag::err_parens_pointer_member_function)
  12945. << OrigOp.get()->getSourceRange();
  12946. // The method was named without a qualifier.
  12947. } else if (!DRE->getQualifier()) {
  12948. if (MD->getParent()->getName().empty())
  12949. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  12950. << op->getSourceRange();
  12951. else {
  12952. SmallString<32> Str;
  12953. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  12954. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  12955. << op->getSourceRange()
  12956. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  12957. }
  12958. }
  12959. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  12960. if (isa<CXXDestructorDecl>(MD))
  12961. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  12962. QualType MPTy = Context.getMemberPointerType(
  12963. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  12964. // Under the MS ABI, lock down the inheritance model now.
  12965. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  12966. (void)isCompleteType(OpLoc, MPTy);
  12967. return MPTy;
  12968. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  12969. // C99 6.5.3.2p1
  12970. // The operand must be either an l-value or a function designator
  12971. if (!op->getType()->isFunctionType()) {
  12972. // Use a special diagnostic for loads from property references.
  12973. if (isa<PseudoObjectExpr>(op)) {
  12974. AddressOfError = AO_Property_Expansion;
  12975. } else {
  12976. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  12977. << op->getType() << op->getSourceRange();
  12978. return QualType();
  12979. }
  12980. }
  12981. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  12982. // The operand cannot be a bit-field
  12983. AddressOfError = AO_Bit_Field;
  12984. } else if (op->getObjectKind() == OK_VectorComponent) {
  12985. // The operand cannot be an element of a vector
  12986. AddressOfError = AO_Vector_Element;
  12987. } else if (op->getObjectKind() == OK_MatrixComponent) {
  12988. // The operand cannot be an element of a matrix.
  12989. AddressOfError = AO_Matrix_Element;
  12990. } else if (dcl) { // C99 6.5.3.2p1
  12991. // We have an lvalue with a decl. Make sure the decl is not declared
  12992. // with the register storage-class specifier.
  12993. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  12994. // in C++ it is not error to take address of a register
  12995. // variable (c++03 7.1.1P3)
  12996. if (vd->getStorageClass() == SC_Register &&
  12997. !getLangOpts().CPlusPlus) {
  12998. AddressOfError = AO_Register_Variable;
  12999. }
  13000. } else if (isa<MSPropertyDecl>(dcl)) {
  13001. AddressOfError = AO_Property_Expansion;
  13002. } else if (isa<FunctionTemplateDecl>(dcl)) {
  13003. return Context.OverloadTy;
  13004. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  13005. // Okay: we can take the address of a field.
  13006. // Could be a pointer to member, though, if there is an explicit
  13007. // scope qualifier for the class.
  13008. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  13009. DeclContext *Ctx = dcl->getDeclContext();
  13010. if (Ctx && Ctx->isRecord()) {
  13011. if (dcl->getType()->isReferenceType()) {
  13012. Diag(OpLoc,
  13013. diag::err_cannot_form_pointer_to_member_of_reference_type)
  13014. << dcl->getDeclName() << dcl->getType();
  13015. return QualType();
  13016. }
  13017. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  13018. Ctx = Ctx->getParent();
  13019. QualType MPTy = Context.getMemberPointerType(
  13020. op->getType(),
  13021. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  13022. // Under the MS ABI, lock down the inheritance model now.
  13023. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  13024. (void)isCompleteType(OpLoc, MPTy);
  13025. return MPTy;
  13026. }
  13027. }
  13028. } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
  13029. MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
  13030. llvm_unreachable("Unknown/unexpected decl type");
  13031. }
  13032. if (AddressOfError != AO_No_Error) {
  13033. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  13034. return QualType();
  13035. }
  13036. if (lval == Expr::LV_IncompleteVoidType) {
  13037. // Taking the address of a void variable is technically illegal, but we
  13038. // allow it in cases which are otherwise valid.
  13039. // Example: "extern void x; void* y = &x;".
  13040. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  13041. }
  13042. // If the operand has type "type", the result has type "pointer to type".
  13043. if (op->getType()->isObjCObjectType())
  13044. return Context.getObjCObjectPointerType(op->getType());
  13045. CheckAddressOfPackedMember(op);
  13046. return Context.getPointerType(op->getType());
  13047. }
  13048. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  13049. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  13050. if (!DRE)
  13051. return;
  13052. const Decl *D = DRE->getDecl();
  13053. if (!D)
  13054. return;
  13055. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  13056. if (!Param)
  13057. return;
  13058. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  13059. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  13060. return;
  13061. if (FunctionScopeInfo *FD = S.getCurFunction())
  13062. FD->ModifiedNonNullParams.insert(Param);
  13063. }
  13064. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  13065. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  13066. SourceLocation OpLoc,
  13067. bool IsAfterAmp = false) {
  13068. if (Op->isTypeDependent())
  13069. return S.Context.DependentTy;
  13070. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  13071. if (ConvResult.isInvalid())
  13072. return QualType();
  13073. Op = ConvResult.get();
  13074. QualType OpTy = Op->getType();
  13075. QualType Result;
  13076. if (isa<CXXReinterpretCastExpr>(Op)) {
  13077. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  13078. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  13079. Op->getSourceRange());
  13080. }
  13081. if (const PointerType *PT = OpTy->getAs<PointerType>())
  13082. {
  13083. Result = PT->getPointeeType();
  13084. }
  13085. else if (const ObjCObjectPointerType *OPT =
  13086. OpTy->getAs<ObjCObjectPointerType>())
  13087. Result = OPT->getPointeeType();
  13088. else {
  13089. ExprResult PR = S.CheckPlaceholderExpr(Op);
  13090. if (PR.isInvalid()) return QualType();
  13091. if (PR.get() != Op)
  13092. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  13093. }
  13094. if (Result.isNull()) {
  13095. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  13096. << OpTy << Op->getSourceRange();
  13097. return QualType();
  13098. }
  13099. if (Result->isVoidType()) {
  13100. // C++ [expr.unary.op]p1:
  13101. // [...] the expression to which [the unary * operator] is applied shall
  13102. // be a pointer to an object type, or a pointer to a function type
  13103. LangOptions LO = S.getLangOpts();
  13104. if (LO.CPlusPlus)
  13105. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer_cpp)
  13106. << OpTy << Op->getSourceRange();
  13107. else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
  13108. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  13109. << OpTy << Op->getSourceRange();
  13110. }
  13111. // Dereferences are usually l-values...
  13112. VK = VK_LValue;
  13113. // ...except that certain expressions are never l-values in C.
  13114. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  13115. VK = VK_PRValue;
  13116. return Result;
  13117. }
  13118. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  13119. BinaryOperatorKind Opc;
  13120. switch (Kind) {
  13121. default: llvm_unreachable("Unknown binop!");
  13122. case tok::periodstar: Opc = BO_PtrMemD; break;
  13123. case tok::arrowstar: Opc = BO_PtrMemI; break;
  13124. case tok::star: Opc = BO_Mul; break;
  13125. case tok::slash: Opc = BO_Div; break;
  13126. case tok::percent: Opc = BO_Rem; break;
  13127. case tok::plus: Opc = BO_Add; break;
  13128. case tok::minus: Opc = BO_Sub; break;
  13129. case tok::lessless: Opc = BO_Shl; break;
  13130. case tok::greatergreater: Opc = BO_Shr; break;
  13131. case tok::lessequal: Opc = BO_LE; break;
  13132. case tok::less: Opc = BO_LT; break;
  13133. case tok::greaterequal: Opc = BO_GE; break;
  13134. case tok::greater: Opc = BO_GT; break;
  13135. case tok::exclaimequal: Opc = BO_NE; break;
  13136. case tok::equalequal: Opc = BO_EQ; break;
  13137. case tok::spaceship: Opc = BO_Cmp; break;
  13138. case tok::amp: Opc = BO_And; break;
  13139. case tok::caret: Opc = BO_Xor; break;
  13140. case tok::pipe: Opc = BO_Or; break;
  13141. case tok::ampamp: Opc = BO_LAnd; break;
  13142. case tok::pipepipe: Opc = BO_LOr; break;
  13143. case tok::equal: Opc = BO_Assign; break;
  13144. case tok::starequal: Opc = BO_MulAssign; break;
  13145. case tok::slashequal: Opc = BO_DivAssign; break;
  13146. case tok::percentequal: Opc = BO_RemAssign; break;
  13147. case tok::plusequal: Opc = BO_AddAssign; break;
  13148. case tok::minusequal: Opc = BO_SubAssign; break;
  13149. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  13150. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  13151. case tok::ampequal: Opc = BO_AndAssign; break;
  13152. case tok::caretequal: Opc = BO_XorAssign; break;
  13153. case tok::pipeequal: Opc = BO_OrAssign; break;
  13154. case tok::comma: Opc = BO_Comma; break;
  13155. }
  13156. return Opc;
  13157. }
  13158. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  13159. tok::TokenKind Kind) {
  13160. UnaryOperatorKind Opc;
  13161. switch (Kind) {
  13162. default: llvm_unreachable("Unknown unary op!");
  13163. case tok::plusplus: Opc = UO_PreInc; break;
  13164. case tok::minusminus: Opc = UO_PreDec; break;
  13165. case tok::amp: Opc = UO_AddrOf; break;
  13166. case tok::star: Opc = UO_Deref; break;
  13167. case tok::plus: Opc = UO_Plus; break;
  13168. case tok::minus: Opc = UO_Minus; break;
  13169. case tok::tilde: Opc = UO_Not; break;
  13170. case tok::exclaim: Opc = UO_LNot; break;
  13171. case tok::kw___real: Opc = UO_Real; break;
  13172. case tok::kw___imag: Opc = UO_Imag; break;
  13173. case tok::kw___extension__: Opc = UO_Extension; break;
  13174. }
  13175. return Opc;
  13176. }
  13177. const FieldDecl *
  13178. Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
  13179. // Explore the case for adding 'this->' to the LHS of a self assignment, very
  13180. // common for setters.
  13181. // struct A {
  13182. // int X;
  13183. // -void setX(int X) { X = X; }
  13184. // +void setX(int X) { this->X = X; }
  13185. // };
  13186. // Only consider parameters for self assignment fixes.
  13187. if (!isa<ParmVarDecl>(SelfAssigned))
  13188. return nullptr;
  13189. const auto *Method =
  13190. dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
  13191. if (!Method)
  13192. return nullptr;
  13193. const CXXRecordDecl *Parent = Method->getParent();
  13194. // In theory this is fixable if the lambda explicitly captures this, but
  13195. // that's added complexity that's rarely going to be used.
  13196. if (Parent->isLambda())
  13197. return nullptr;
  13198. // FIXME: Use an actual Lookup operation instead of just traversing fields
  13199. // in order to get base class fields.
  13200. auto Field =
  13201. llvm::find_if(Parent->fields(),
  13202. [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
  13203. return F->getDeclName() == Name;
  13204. });
  13205. return (Field != Parent->field_end()) ? *Field : nullptr;
  13206. }
  13207. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  13208. /// This warning suppressed in the event of macro expansions.
  13209. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  13210. SourceLocation OpLoc, bool IsBuiltin) {
  13211. if (S.inTemplateInstantiation())
  13212. return;
  13213. if (S.isUnevaluatedContext())
  13214. return;
  13215. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  13216. return;
  13217. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  13218. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  13219. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  13220. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  13221. if (!LHSDeclRef || !RHSDeclRef ||
  13222. LHSDeclRef->getLocation().isMacroID() ||
  13223. RHSDeclRef->getLocation().isMacroID())
  13224. return;
  13225. const ValueDecl *LHSDecl =
  13226. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  13227. const ValueDecl *RHSDecl =
  13228. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  13229. if (LHSDecl != RHSDecl)
  13230. return;
  13231. if (LHSDecl->getType().isVolatileQualified())
  13232. return;
  13233. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  13234. if (RefTy->getPointeeType().isVolatileQualified())
  13235. return;
  13236. auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  13237. : diag::warn_self_assignment_overloaded)
  13238. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  13239. << RHSExpr->getSourceRange();
  13240. if (const FieldDecl *SelfAssignField =
  13241. S.getSelfAssignmentClassMemberCandidate(RHSDecl))
  13242. Diag << 1 << SelfAssignField
  13243. << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
  13244. else
  13245. Diag << 0;
  13246. }
  13247. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  13248. /// is usually indicative of introspection within the Objective-C pointer.
  13249. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  13250. SourceLocation OpLoc) {
  13251. if (!S.getLangOpts().ObjC)
  13252. return;
  13253. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  13254. const Expr *LHS = L.get();
  13255. const Expr *RHS = R.get();
  13256. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  13257. ObjCPointerExpr = LHS;
  13258. OtherExpr = RHS;
  13259. }
  13260. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  13261. ObjCPointerExpr = RHS;
  13262. OtherExpr = LHS;
  13263. }
  13264. // This warning is deliberately made very specific to reduce false
  13265. // positives with logic that uses '&' for hashing. This logic mainly
  13266. // looks for code trying to introspect into tagged pointers, which
  13267. // code should generally never do.
  13268. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  13269. unsigned Diag = diag::warn_objc_pointer_masking;
  13270. // Determine if we are introspecting the result of performSelectorXXX.
  13271. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  13272. // Special case messages to -performSelector and friends, which
  13273. // can return non-pointer values boxed in a pointer value.
  13274. // Some clients may wish to silence warnings in this subcase.
  13275. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  13276. Selector S = ME->getSelector();
  13277. StringRef SelArg0 = S.getNameForSlot(0);
  13278. if (SelArg0.startswith("performSelector"))
  13279. Diag = diag::warn_objc_pointer_masking_performSelector;
  13280. }
  13281. S.Diag(OpLoc, Diag)
  13282. << ObjCPointerExpr->getSourceRange();
  13283. }
  13284. }
  13285. static NamedDecl *getDeclFromExpr(Expr *E) {
  13286. if (!E)
  13287. return nullptr;
  13288. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  13289. return DRE->getDecl();
  13290. if (auto *ME = dyn_cast<MemberExpr>(E))
  13291. return ME->getMemberDecl();
  13292. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  13293. return IRE->getDecl();
  13294. return nullptr;
  13295. }
  13296. // This helper function promotes a binary operator's operands (which are of a
  13297. // half vector type) to a vector of floats and then truncates the result to
  13298. // a vector of either half or short.
  13299. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  13300. BinaryOperatorKind Opc, QualType ResultTy,
  13301. ExprValueKind VK, ExprObjectKind OK,
  13302. bool IsCompAssign, SourceLocation OpLoc,
  13303. FPOptionsOverride FPFeatures) {
  13304. auto &Context = S.getASTContext();
  13305. assert((isVector(ResultTy, Context.HalfTy) ||
  13306. isVector(ResultTy, Context.ShortTy)) &&
  13307. "Result must be a vector of half or short");
  13308. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  13309. isVector(RHS.get()->getType(), Context.HalfTy) &&
  13310. "both operands expected to be a half vector");
  13311. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  13312. QualType BinOpResTy = RHS.get()->getType();
  13313. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  13314. // change BinOpResTy to a vector of ints.
  13315. if (isVector(ResultTy, Context.ShortTy))
  13316. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  13317. if (IsCompAssign)
  13318. return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
  13319. ResultTy, VK, OK, OpLoc, FPFeatures,
  13320. BinOpResTy, BinOpResTy);
  13321. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  13322. auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
  13323. BinOpResTy, VK, OK, OpLoc, FPFeatures);
  13324. return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
  13325. }
  13326. static std::pair<ExprResult, ExprResult>
  13327. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  13328. Expr *RHSExpr) {
  13329. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  13330. if (!S.Context.isDependenceAllowed()) {
  13331. // C cannot handle TypoExpr nodes on either side of a binop because it
  13332. // doesn't handle dependent types properly, so make sure any TypoExprs have
  13333. // been dealt with before checking the operands.
  13334. LHS = S.CorrectDelayedTyposInExpr(LHS);
  13335. RHS = S.CorrectDelayedTyposInExpr(
  13336. RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
  13337. [Opc, LHS](Expr *E) {
  13338. if (Opc != BO_Assign)
  13339. return ExprResult(E);
  13340. // Avoid correcting the RHS to the same Expr as the LHS.
  13341. Decl *D = getDeclFromExpr(E);
  13342. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  13343. });
  13344. }
  13345. return std::make_pair(LHS, RHS);
  13346. }
  13347. /// Returns true if conversion between vectors of halfs and vectors of floats
  13348. /// is needed.
  13349. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  13350. Expr *E0, Expr *E1 = nullptr) {
  13351. if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
  13352. Ctx.getTargetInfo().useFP16ConversionIntrinsics())
  13353. return false;
  13354. auto HasVectorOfHalfType = [&Ctx](Expr *E) {
  13355. QualType Ty = E->IgnoreImplicit()->getType();
  13356. // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
  13357. // to vectors of floats. Although the element type of the vectors is __fp16,
  13358. // the vectors shouldn't be treated as storage-only types. See the
  13359. // discussion here: https://reviews.llvm.org/rG825235c140e7
  13360. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  13361. if (VT->getVectorKind() == VectorType::NeonVector)
  13362. return false;
  13363. return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
  13364. }
  13365. return false;
  13366. };
  13367. return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
  13368. }
  13369. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  13370. /// operator @p Opc at location @c TokLoc. This routine only supports
  13371. /// built-in operations; ActOnBinOp handles overloaded operators.
  13372. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  13373. BinaryOperatorKind Opc,
  13374. Expr *LHSExpr, Expr *RHSExpr) {
  13375. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  13376. // The syntax only allows initializer lists on the RHS of assignment,
  13377. // so we don't need to worry about accepting invalid code for
  13378. // non-assignment operators.
  13379. // C++11 5.17p9:
  13380. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  13381. // of x = {} is x = T().
  13382. InitializationKind Kind = InitializationKind::CreateDirectList(
  13383. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  13384. InitializedEntity Entity =
  13385. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  13386. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  13387. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  13388. if (Init.isInvalid())
  13389. return Init;
  13390. RHSExpr = Init.get();
  13391. }
  13392. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  13393. QualType ResultTy; // Result type of the binary operator.
  13394. // The following two variables are used for compound assignment operators
  13395. QualType CompLHSTy; // Type of LHS after promotions for computation
  13396. QualType CompResultTy; // Type of computation result
  13397. ExprValueKind VK = VK_PRValue;
  13398. ExprObjectKind OK = OK_Ordinary;
  13399. bool ConvertHalfVec = false;
  13400. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  13401. if (!LHS.isUsable() || !RHS.isUsable())
  13402. return ExprError();
  13403. if (getLangOpts().OpenCL) {
  13404. QualType LHSTy = LHSExpr->getType();
  13405. QualType RHSTy = RHSExpr->getType();
  13406. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  13407. // the ATOMIC_VAR_INIT macro.
  13408. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  13409. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  13410. if (BO_Assign == Opc)
  13411. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  13412. else
  13413. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  13414. return ExprError();
  13415. }
  13416. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  13417. // only with a builtin functions and therefore should be disallowed here.
  13418. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  13419. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  13420. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  13421. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  13422. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  13423. return ExprError();
  13424. }
  13425. }
  13426. checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
  13427. checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
  13428. switch (Opc) {
  13429. case BO_Assign:
  13430. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
  13431. if (getLangOpts().CPlusPlus &&
  13432. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  13433. VK = LHS.get()->getValueKind();
  13434. OK = LHS.get()->getObjectKind();
  13435. }
  13436. if (!ResultTy.isNull()) {
  13437. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  13438. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  13439. // Avoid copying a block to the heap if the block is assigned to a local
  13440. // auto variable that is declared in the same scope as the block. This
  13441. // optimization is unsafe if the local variable is declared in an outer
  13442. // scope. For example:
  13443. //
  13444. // BlockTy b;
  13445. // {
  13446. // b = ^{...};
  13447. // }
  13448. // // It is unsafe to invoke the block here if it wasn't copied to the
  13449. // // heap.
  13450. // b();
  13451. if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
  13452. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
  13453. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  13454. if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
  13455. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  13456. if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
  13457. checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
  13458. NTCUC_Assignment, NTCUK_Copy);
  13459. }
  13460. RecordModifiableNonNullParam(*this, LHS.get());
  13461. break;
  13462. case BO_PtrMemD:
  13463. case BO_PtrMemI:
  13464. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  13465. Opc == BO_PtrMemI);
  13466. break;
  13467. case BO_Mul:
  13468. case BO_Div:
  13469. ConvertHalfVec = true;
  13470. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  13471. Opc == BO_Div);
  13472. break;
  13473. case BO_Rem:
  13474. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  13475. break;
  13476. case BO_Add:
  13477. ConvertHalfVec = true;
  13478. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  13479. break;
  13480. case BO_Sub:
  13481. ConvertHalfVec = true;
  13482. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  13483. break;
  13484. case BO_Shl:
  13485. case BO_Shr:
  13486. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  13487. break;
  13488. case BO_LE:
  13489. case BO_LT:
  13490. case BO_GE:
  13491. case BO_GT:
  13492. ConvertHalfVec = true;
  13493. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  13494. break;
  13495. case BO_EQ:
  13496. case BO_NE:
  13497. ConvertHalfVec = true;
  13498. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  13499. break;
  13500. case BO_Cmp:
  13501. ConvertHalfVec = true;
  13502. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  13503. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  13504. break;
  13505. case BO_And:
  13506. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  13507. [[fallthrough]];
  13508. case BO_Xor:
  13509. case BO_Or:
  13510. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  13511. break;
  13512. case BO_LAnd:
  13513. case BO_LOr:
  13514. ConvertHalfVec = true;
  13515. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  13516. break;
  13517. case BO_MulAssign:
  13518. case BO_DivAssign:
  13519. ConvertHalfVec = true;
  13520. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  13521. Opc == BO_DivAssign);
  13522. CompLHSTy = CompResultTy;
  13523. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  13524. ResultTy =
  13525. CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
  13526. break;
  13527. case BO_RemAssign:
  13528. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  13529. CompLHSTy = CompResultTy;
  13530. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  13531. ResultTy =
  13532. CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
  13533. break;
  13534. case BO_AddAssign:
  13535. ConvertHalfVec = true;
  13536. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  13537. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  13538. ResultTy =
  13539. CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
  13540. break;
  13541. case BO_SubAssign:
  13542. ConvertHalfVec = true;
  13543. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  13544. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  13545. ResultTy =
  13546. CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
  13547. break;
  13548. case BO_ShlAssign:
  13549. case BO_ShrAssign:
  13550. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  13551. CompLHSTy = CompResultTy;
  13552. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  13553. ResultTy =
  13554. CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
  13555. break;
  13556. case BO_AndAssign:
  13557. case BO_OrAssign: // fallthrough
  13558. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  13559. [[fallthrough]];
  13560. case BO_XorAssign:
  13561. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  13562. CompLHSTy = CompResultTy;
  13563. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  13564. ResultTy =
  13565. CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
  13566. break;
  13567. case BO_Comma:
  13568. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  13569. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  13570. VK = RHS.get()->getValueKind();
  13571. OK = RHS.get()->getObjectKind();
  13572. }
  13573. break;
  13574. }
  13575. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  13576. return ExprError();
  13577. // Some of the binary operations require promoting operands of half vector to
  13578. // float vectors and truncating the result back to half vector. For now, we do
  13579. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  13580. // arm64).
  13581. assert(
  13582. (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
  13583. isVector(LHS.get()->getType(), Context.HalfTy)) &&
  13584. "both sides are half vectors or neither sides are");
  13585. ConvertHalfVec =
  13586. needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
  13587. // Check for array bounds violations for both sides of the BinaryOperator
  13588. CheckArrayAccess(LHS.get());
  13589. CheckArrayAccess(RHS.get());
  13590. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  13591. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  13592. &Context.Idents.get("object_setClass"),
  13593. SourceLocation(), LookupOrdinaryName);
  13594. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  13595. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  13596. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  13597. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  13598. "object_setClass(")
  13599. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  13600. ",")
  13601. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  13602. }
  13603. else
  13604. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  13605. }
  13606. else if (const ObjCIvarRefExpr *OIRE =
  13607. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  13608. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  13609. // Opc is not a compound assignment if CompResultTy is null.
  13610. if (CompResultTy.isNull()) {
  13611. if (ConvertHalfVec)
  13612. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  13613. OpLoc, CurFPFeatureOverrides());
  13614. return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
  13615. VK, OK, OpLoc, CurFPFeatureOverrides());
  13616. }
  13617. // Handle compound assignments.
  13618. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  13619. OK_ObjCProperty) {
  13620. VK = VK_LValue;
  13621. OK = LHS.get()->getObjectKind();
  13622. }
  13623. // The LHS is not converted to the result type for fixed-point compound
  13624. // assignment as the common type is computed on demand. Reset the CompLHSTy
  13625. // to the LHS type we would have gotten after unary conversions.
  13626. if (CompResultTy->isFixedPointType())
  13627. CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
  13628. if (ConvertHalfVec)
  13629. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  13630. OpLoc, CurFPFeatureOverrides());
  13631. return CompoundAssignOperator::Create(
  13632. Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
  13633. CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
  13634. }
  13635. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  13636. /// operators are mixed in a way that suggests that the programmer forgot that
  13637. /// comparison operators have higher precedence. The most typical example of
  13638. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  13639. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  13640. SourceLocation OpLoc, Expr *LHSExpr,
  13641. Expr *RHSExpr) {
  13642. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  13643. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  13644. // Check that one of the sides is a comparison operator and the other isn't.
  13645. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  13646. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  13647. if (isLeftComp == isRightComp)
  13648. return;
  13649. // Bitwise operations are sometimes used as eager logical ops.
  13650. // Don't diagnose this.
  13651. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  13652. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  13653. if (isLeftBitwise || isRightBitwise)
  13654. return;
  13655. SourceRange DiagRange = isLeftComp
  13656. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  13657. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  13658. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  13659. SourceRange ParensRange =
  13660. isLeftComp
  13661. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  13662. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  13663. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  13664. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  13665. SuggestParentheses(Self, OpLoc,
  13666. Self.PDiag(diag::note_precedence_silence) << OpStr,
  13667. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  13668. SuggestParentheses(Self, OpLoc,
  13669. Self.PDiag(diag::note_precedence_bitwise_first)
  13670. << BinaryOperator::getOpcodeStr(Opc),
  13671. ParensRange);
  13672. }
  13673. /// It accepts a '&&' expr that is inside a '||' one.
  13674. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  13675. /// in parentheses.
  13676. static void
  13677. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  13678. BinaryOperator *Bop) {
  13679. assert(Bop->getOpcode() == BO_LAnd);
  13680. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  13681. << Bop->getSourceRange() << OpLoc;
  13682. SuggestParentheses(Self, Bop->getOperatorLoc(),
  13683. Self.PDiag(diag::note_precedence_silence)
  13684. << Bop->getOpcodeStr(),
  13685. Bop->getSourceRange());
  13686. }
  13687. /// Look for '&&' in the left hand of a '||' expr.
  13688. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  13689. Expr *LHSExpr, Expr *RHSExpr) {
  13690. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  13691. if (Bop->getOpcode() == BO_LAnd) {
  13692. // If it's "string_literal && a || b" don't warn since the precedence
  13693. // doesn't matter.
  13694. if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
  13695. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  13696. } else if (Bop->getOpcode() == BO_LOr) {
  13697. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  13698. // If it's "a || b && string_literal || c" we didn't warn earlier for
  13699. // "a || b && string_literal", but warn now.
  13700. if (RBop->getOpcode() == BO_LAnd &&
  13701. isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
  13702. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  13703. }
  13704. }
  13705. }
  13706. }
  13707. /// Look for '&&' in the right hand of a '||' expr.
  13708. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  13709. Expr *LHSExpr, Expr *RHSExpr) {
  13710. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  13711. if (Bop->getOpcode() == BO_LAnd) {
  13712. // If it's "a || b && string_literal" don't warn since the precedence
  13713. // doesn't matter.
  13714. if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
  13715. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  13716. }
  13717. }
  13718. }
  13719. /// Look for bitwise op in the left or right hand of a bitwise op with
  13720. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  13721. /// the '&' expression in parentheses.
  13722. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  13723. SourceLocation OpLoc, Expr *SubExpr) {
  13724. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  13725. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  13726. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  13727. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  13728. << Bop->getSourceRange() << OpLoc;
  13729. SuggestParentheses(S, Bop->getOperatorLoc(),
  13730. S.PDiag(diag::note_precedence_silence)
  13731. << Bop->getOpcodeStr(),
  13732. Bop->getSourceRange());
  13733. }
  13734. }
  13735. }
  13736. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  13737. Expr *SubExpr, StringRef Shift) {
  13738. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  13739. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  13740. StringRef Op = Bop->getOpcodeStr();
  13741. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  13742. << Bop->getSourceRange() << OpLoc << Shift << Op;
  13743. SuggestParentheses(S, Bop->getOperatorLoc(),
  13744. S.PDiag(diag::note_precedence_silence) << Op,
  13745. Bop->getSourceRange());
  13746. }
  13747. }
  13748. }
  13749. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  13750. Expr *LHSExpr, Expr *RHSExpr) {
  13751. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  13752. if (!OCE)
  13753. return;
  13754. FunctionDecl *FD = OCE->getDirectCallee();
  13755. if (!FD || !FD->isOverloadedOperator())
  13756. return;
  13757. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  13758. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  13759. return;
  13760. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  13761. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  13762. << (Kind == OO_LessLess);
  13763. SuggestParentheses(S, OCE->getOperatorLoc(),
  13764. S.PDiag(diag::note_precedence_silence)
  13765. << (Kind == OO_LessLess ? "<<" : ">>"),
  13766. OCE->getSourceRange());
  13767. SuggestParentheses(
  13768. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  13769. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  13770. }
  13771. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  13772. /// precedence.
  13773. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  13774. SourceLocation OpLoc, Expr *LHSExpr,
  13775. Expr *RHSExpr){
  13776. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  13777. if (BinaryOperator::isBitwiseOp(Opc))
  13778. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  13779. // Diagnose "arg1 & arg2 | arg3"
  13780. if ((Opc == BO_Or || Opc == BO_Xor) &&
  13781. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  13782. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  13783. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  13784. }
  13785. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  13786. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  13787. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  13788. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  13789. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  13790. }
  13791. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  13792. || Opc == BO_Shr) {
  13793. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  13794. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  13795. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  13796. }
  13797. // Warn on overloaded shift operators and comparisons, such as:
  13798. // cout << 5 == 4;
  13799. if (BinaryOperator::isComparisonOp(Opc))
  13800. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  13801. }
  13802. // Binary Operators. 'Tok' is the token for the operator.
  13803. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  13804. tok::TokenKind Kind,
  13805. Expr *LHSExpr, Expr *RHSExpr) {
  13806. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  13807. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  13808. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  13809. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  13810. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  13811. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  13812. }
  13813. void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
  13814. UnresolvedSetImpl &Functions) {
  13815. OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
  13816. if (OverOp != OO_None && OverOp != OO_Equal)
  13817. LookupOverloadedOperatorName(OverOp, S, Functions);
  13818. // In C++20 onwards, we may have a second operator to look up.
  13819. if (getLangOpts().CPlusPlus20) {
  13820. if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
  13821. LookupOverloadedOperatorName(ExtraOp, S, Functions);
  13822. }
  13823. }
  13824. /// Build an overloaded binary operator expression in the given scope.
  13825. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  13826. BinaryOperatorKind Opc,
  13827. Expr *LHS, Expr *RHS) {
  13828. switch (Opc) {
  13829. case BO_Assign:
  13830. case BO_DivAssign:
  13831. case BO_RemAssign:
  13832. case BO_SubAssign:
  13833. case BO_AndAssign:
  13834. case BO_OrAssign:
  13835. case BO_XorAssign:
  13836. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  13837. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  13838. break;
  13839. default:
  13840. break;
  13841. }
  13842. // Find all of the overloaded operators visible from this point.
  13843. UnresolvedSet<16> Functions;
  13844. S.LookupBinOp(Sc, OpLoc, Opc, Functions);
  13845. // Build the (potentially-overloaded, potentially-dependent)
  13846. // binary operation.
  13847. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  13848. }
  13849. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  13850. BinaryOperatorKind Opc,
  13851. Expr *LHSExpr, Expr *RHSExpr) {
  13852. ExprResult LHS, RHS;
  13853. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  13854. if (!LHS.isUsable() || !RHS.isUsable())
  13855. return ExprError();
  13856. LHSExpr = LHS.get();
  13857. RHSExpr = RHS.get();
  13858. // We want to end up calling one of checkPseudoObjectAssignment
  13859. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  13860. // both expressions are overloadable or either is type-dependent),
  13861. // or CreateBuiltinBinOp (in any other case). We also want to get
  13862. // any placeholder types out of the way.
  13863. // Handle pseudo-objects in the LHS.
  13864. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  13865. // Assignments with a pseudo-object l-value need special analysis.
  13866. if (pty->getKind() == BuiltinType::PseudoObject &&
  13867. BinaryOperator::isAssignmentOp(Opc))
  13868. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  13869. // Don't resolve overloads if the other type is overloadable.
  13870. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  13871. // We can't actually test that if we still have a placeholder,
  13872. // though. Fortunately, none of the exceptions we see in that
  13873. // code below are valid when the LHS is an overload set. Note
  13874. // that an overload set can be dependently-typed, but it never
  13875. // instantiates to having an overloadable type.
  13876. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  13877. if (resolvedRHS.isInvalid()) return ExprError();
  13878. RHSExpr = resolvedRHS.get();
  13879. if (RHSExpr->isTypeDependent() ||
  13880. RHSExpr->getType()->isOverloadableType())
  13881. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13882. }
  13883. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  13884. // template, diagnose the missing 'template' keyword instead of diagnosing
  13885. // an invalid use of a bound member function.
  13886. //
  13887. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  13888. // to C++1z [over.over]/1.4, but we already checked for that case above.
  13889. if (Opc == BO_LT && inTemplateInstantiation() &&
  13890. (pty->getKind() == BuiltinType::BoundMember ||
  13891. pty->getKind() == BuiltinType::Overload)) {
  13892. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  13893. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  13894. llvm::any_of(OE->decls(), [](NamedDecl *ND) {
  13895. return isa<FunctionTemplateDecl>(ND);
  13896. })) {
  13897. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  13898. : OE->getNameLoc(),
  13899. diag::err_template_kw_missing)
  13900. << OE->getName().getAsString() << "";
  13901. return ExprError();
  13902. }
  13903. }
  13904. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  13905. if (LHS.isInvalid()) return ExprError();
  13906. LHSExpr = LHS.get();
  13907. }
  13908. // Handle pseudo-objects in the RHS.
  13909. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  13910. // An overload in the RHS can potentially be resolved by the type
  13911. // being assigned to.
  13912. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  13913. if (getLangOpts().CPlusPlus &&
  13914. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  13915. LHSExpr->getType()->isOverloadableType()))
  13916. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13917. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  13918. }
  13919. // Don't resolve overloads if the other type is overloadable.
  13920. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  13921. LHSExpr->getType()->isOverloadableType())
  13922. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13923. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  13924. if (!resolvedRHS.isUsable()) return ExprError();
  13925. RHSExpr = resolvedRHS.get();
  13926. }
  13927. if (getLangOpts().CPlusPlus) {
  13928. // If either expression is type-dependent, always build an
  13929. // overloaded op.
  13930. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  13931. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13932. // Otherwise, build an overloaded op if either expression has an
  13933. // overloadable type.
  13934. if (LHSExpr->getType()->isOverloadableType() ||
  13935. RHSExpr->getType()->isOverloadableType())
  13936. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13937. }
  13938. if (getLangOpts().RecoveryAST &&
  13939. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
  13940. assert(!getLangOpts().CPlusPlus);
  13941. assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
  13942. "Should only occur in error-recovery path.");
  13943. if (BinaryOperator::isCompoundAssignmentOp(Opc))
  13944. // C [6.15.16] p3:
  13945. // An assignment expression has the value of the left operand after the
  13946. // assignment, but is not an lvalue.
  13947. return CompoundAssignOperator::Create(
  13948. Context, LHSExpr, RHSExpr, Opc,
  13949. LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
  13950. OpLoc, CurFPFeatureOverrides());
  13951. QualType ResultType;
  13952. switch (Opc) {
  13953. case BO_Assign:
  13954. ResultType = LHSExpr->getType().getUnqualifiedType();
  13955. break;
  13956. case BO_LT:
  13957. case BO_GT:
  13958. case BO_LE:
  13959. case BO_GE:
  13960. case BO_EQ:
  13961. case BO_NE:
  13962. case BO_LAnd:
  13963. case BO_LOr:
  13964. // These operators have a fixed result type regardless of operands.
  13965. ResultType = Context.IntTy;
  13966. break;
  13967. case BO_Comma:
  13968. ResultType = RHSExpr->getType();
  13969. break;
  13970. default:
  13971. ResultType = Context.DependentTy;
  13972. break;
  13973. }
  13974. return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
  13975. VK_PRValue, OK_Ordinary, OpLoc,
  13976. CurFPFeatureOverrides());
  13977. }
  13978. // Build a built-in binary operation.
  13979. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  13980. }
  13981. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  13982. if (T.isNull() || T->isDependentType())
  13983. return false;
  13984. if (!Ctx.isPromotableIntegerType(T))
  13985. return true;
  13986. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  13987. }
  13988. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  13989. UnaryOperatorKind Opc, Expr *InputExpr,
  13990. bool IsAfterAmp) {
  13991. ExprResult Input = InputExpr;
  13992. ExprValueKind VK = VK_PRValue;
  13993. ExprObjectKind OK = OK_Ordinary;
  13994. QualType resultType;
  13995. bool CanOverflow = false;
  13996. bool ConvertHalfVec = false;
  13997. if (getLangOpts().OpenCL) {
  13998. QualType Ty = InputExpr->getType();
  13999. // The only legal unary operation for atomics is '&'.
  14000. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  14001. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  14002. // only with a builtin functions and therefore should be disallowed here.
  14003. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  14004. || Ty->isBlockPointerType())) {
  14005. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  14006. << InputExpr->getType()
  14007. << Input.get()->getSourceRange());
  14008. }
  14009. }
  14010. if (getLangOpts().HLSL && OpLoc.isValid()) {
  14011. if (Opc == UO_AddrOf)
  14012. return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
  14013. if (Opc == UO_Deref)
  14014. return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
  14015. }
  14016. switch (Opc) {
  14017. case UO_PreInc:
  14018. case UO_PreDec:
  14019. case UO_PostInc:
  14020. case UO_PostDec:
  14021. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  14022. OpLoc,
  14023. Opc == UO_PreInc ||
  14024. Opc == UO_PostInc,
  14025. Opc == UO_PreInc ||
  14026. Opc == UO_PreDec);
  14027. CanOverflow = isOverflowingIntegerType(Context, resultType);
  14028. break;
  14029. case UO_AddrOf:
  14030. resultType = CheckAddressOfOperand(Input, OpLoc);
  14031. CheckAddressOfNoDeref(InputExpr);
  14032. RecordModifiableNonNullParam(*this, InputExpr);
  14033. break;
  14034. case UO_Deref: {
  14035. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  14036. if (Input.isInvalid()) return ExprError();
  14037. resultType =
  14038. CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
  14039. break;
  14040. }
  14041. case UO_Plus:
  14042. case UO_Minus:
  14043. CanOverflow = Opc == UO_Minus &&
  14044. isOverflowingIntegerType(Context, Input.get()->getType());
  14045. Input = UsualUnaryConversions(Input.get());
  14046. if (Input.isInvalid()) return ExprError();
  14047. // Unary plus and minus require promoting an operand of half vector to a
  14048. // float vector and truncating the result back to a half vector. For now, we
  14049. // do this only when HalfArgsAndReturns is set (that is, when the target is
  14050. // arm or arm64).
  14051. ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
  14052. // If the operand is a half vector, promote it to a float vector.
  14053. if (ConvertHalfVec)
  14054. Input = convertVector(Input.get(), Context.FloatTy, *this);
  14055. resultType = Input.get()->getType();
  14056. if (resultType->isDependentType())
  14057. break;
  14058. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  14059. break;
  14060. else if (resultType->isVectorType() &&
  14061. // The z vector extensions don't allow + or - with bool vectors.
  14062. (!Context.getLangOpts().ZVector ||
  14063. resultType->castAs<VectorType>()->getVectorKind() !=
  14064. VectorType::AltiVecBool))
  14065. break;
  14066. else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and -
  14067. break;
  14068. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  14069. Opc == UO_Plus &&
  14070. resultType->isPointerType())
  14071. break;
  14072. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  14073. << resultType << Input.get()->getSourceRange());
  14074. case UO_Not: // bitwise complement
  14075. Input = UsualUnaryConversions(Input.get());
  14076. if (Input.isInvalid())
  14077. return ExprError();
  14078. resultType = Input.get()->getType();
  14079. if (resultType->isDependentType())
  14080. break;
  14081. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  14082. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  14083. // C99 does not support '~' for complex conjugation.
  14084. Diag(OpLoc, diag::ext_integer_complement_complex)
  14085. << resultType << Input.get()->getSourceRange();
  14086. else if (resultType->hasIntegerRepresentation())
  14087. break;
  14088. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  14089. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  14090. // on vector float types.
  14091. QualType T = resultType->castAs<ExtVectorType>()->getElementType();
  14092. if (!T->isIntegerType())
  14093. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  14094. << resultType << Input.get()->getSourceRange());
  14095. } else {
  14096. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  14097. << resultType << Input.get()->getSourceRange());
  14098. }
  14099. break;
  14100. case UO_LNot: // logical negation
  14101. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  14102. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  14103. if (Input.isInvalid()) return ExprError();
  14104. resultType = Input.get()->getType();
  14105. // Though we still have to promote half FP to float...
  14106. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  14107. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  14108. resultType = Context.FloatTy;
  14109. }
  14110. if (resultType->isDependentType())
  14111. break;
  14112. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  14113. // C99 6.5.3.3p1: ok, fallthrough;
  14114. if (Context.getLangOpts().CPlusPlus) {
  14115. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  14116. // operand contextually converted to bool.
  14117. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  14118. ScalarTypeToBooleanCastKind(resultType));
  14119. } else if (Context.getLangOpts().OpenCL &&
  14120. Context.getLangOpts().OpenCLVersion < 120) {
  14121. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  14122. // operate on scalar float types.
  14123. if (!resultType->isIntegerType() && !resultType->isPointerType())
  14124. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  14125. << resultType << Input.get()->getSourceRange());
  14126. }
  14127. } else if (resultType->isExtVectorType()) {
  14128. if (Context.getLangOpts().OpenCL &&
  14129. Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
  14130. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  14131. // operate on vector float types.
  14132. QualType T = resultType->castAs<ExtVectorType>()->getElementType();
  14133. if (!T->isIntegerType())
  14134. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  14135. << resultType << Input.get()->getSourceRange());
  14136. }
  14137. // Vector logical not returns the signed variant of the operand type.
  14138. resultType = GetSignedVectorType(resultType);
  14139. break;
  14140. } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
  14141. const VectorType *VTy = resultType->castAs<VectorType>();
  14142. if (VTy->getVectorKind() != VectorType::GenericVector)
  14143. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  14144. << resultType << Input.get()->getSourceRange());
  14145. // Vector logical not returns the signed variant of the operand type.
  14146. resultType = GetSignedVectorType(resultType);
  14147. break;
  14148. } else {
  14149. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  14150. << resultType << Input.get()->getSourceRange());
  14151. }
  14152. // LNot always has type int. C99 6.5.3.3p5.
  14153. // In C++, it's bool. C++ 5.3.1p8
  14154. resultType = Context.getLogicalOperationType();
  14155. break;
  14156. case UO_Real:
  14157. case UO_Imag:
  14158. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  14159. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  14160. // complex l-values to ordinary l-values and all other values to r-values.
  14161. if (Input.isInvalid()) return ExprError();
  14162. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  14163. if (Input.get()->isGLValue() &&
  14164. Input.get()->getObjectKind() == OK_Ordinary)
  14165. VK = Input.get()->getValueKind();
  14166. } else if (!getLangOpts().CPlusPlus) {
  14167. // In C, a volatile scalar is read by __imag. In C++, it is not.
  14168. Input = DefaultLvalueConversion(Input.get());
  14169. }
  14170. break;
  14171. case UO_Extension:
  14172. resultType = Input.get()->getType();
  14173. VK = Input.get()->getValueKind();
  14174. OK = Input.get()->getObjectKind();
  14175. break;
  14176. case UO_Coawait:
  14177. // It's unnecessary to represent the pass-through operator co_await in the
  14178. // AST; just return the input expression instead.
  14179. assert(!Input.get()->getType()->isDependentType() &&
  14180. "the co_await expression must be non-dependant before "
  14181. "building operator co_await");
  14182. return Input;
  14183. }
  14184. if (resultType.isNull() || Input.isInvalid())
  14185. return ExprError();
  14186. // Check for array bounds violations in the operand of the UnaryOperator,
  14187. // except for the '*' and '&' operators that have to be handled specially
  14188. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  14189. // that are explicitly defined as valid by the standard).
  14190. if (Opc != UO_AddrOf && Opc != UO_Deref)
  14191. CheckArrayAccess(Input.get());
  14192. auto *UO =
  14193. UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
  14194. OpLoc, CanOverflow, CurFPFeatureOverrides());
  14195. if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
  14196. !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
  14197. !isUnevaluatedContext())
  14198. ExprEvalContexts.back().PossibleDerefs.insert(UO);
  14199. // Convert the result back to a half vector.
  14200. if (ConvertHalfVec)
  14201. return convertVector(UO, Context.HalfTy, *this);
  14202. return UO;
  14203. }
  14204. /// Determine whether the given expression is a qualified member
  14205. /// access expression, of a form that could be turned into a pointer to member
  14206. /// with the address-of operator.
  14207. bool Sema::isQualifiedMemberAccess(Expr *E) {
  14208. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  14209. if (!DRE->getQualifier())
  14210. return false;
  14211. ValueDecl *VD = DRE->getDecl();
  14212. if (!VD->isCXXClassMember())
  14213. return false;
  14214. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  14215. return true;
  14216. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  14217. return Method->isInstance();
  14218. return false;
  14219. }
  14220. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  14221. if (!ULE->getQualifier())
  14222. return false;
  14223. for (NamedDecl *D : ULE->decls()) {
  14224. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  14225. if (Method->isInstance())
  14226. return true;
  14227. } else {
  14228. // Overload set does not contain methods.
  14229. break;
  14230. }
  14231. }
  14232. return false;
  14233. }
  14234. return false;
  14235. }
  14236. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  14237. UnaryOperatorKind Opc, Expr *Input,
  14238. bool IsAfterAmp) {
  14239. // First things first: handle placeholders so that the
  14240. // overloaded-operator check considers the right type.
  14241. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  14242. // Increment and decrement of pseudo-object references.
  14243. if (pty->getKind() == BuiltinType::PseudoObject &&
  14244. UnaryOperator::isIncrementDecrementOp(Opc))
  14245. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  14246. // extension is always a builtin operator.
  14247. if (Opc == UO_Extension)
  14248. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  14249. // & gets special logic for several kinds of placeholder.
  14250. // The builtin code knows what to do.
  14251. if (Opc == UO_AddrOf &&
  14252. (pty->getKind() == BuiltinType::Overload ||
  14253. pty->getKind() == BuiltinType::UnknownAny ||
  14254. pty->getKind() == BuiltinType::BoundMember))
  14255. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  14256. // Anything else needs to be handled now.
  14257. ExprResult Result = CheckPlaceholderExpr(Input);
  14258. if (Result.isInvalid()) return ExprError();
  14259. Input = Result.get();
  14260. }
  14261. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  14262. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  14263. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  14264. // Find all of the overloaded operators visible from this point.
  14265. UnresolvedSet<16> Functions;
  14266. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  14267. if (S && OverOp != OO_None)
  14268. LookupOverloadedOperatorName(OverOp, S, Functions);
  14269. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  14270. }
  14271. return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
  14272. }
  14273. // Unary Operators. 'Tok' is the token for the operator.
  14274. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
  14275. Expr *Input, bool IsAfterAmp) {
  14276. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
  14277. IsAfterAmp);
  14278. }
  14279. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  14280. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  14281. LabelDecl *TheDecl) {
  14282. TheDecl->markUsed(Context);
  14283. // Create the AST node. The address of a label always has type 'void*'.
  14284. auto *Res = new (Context) AddrLabelExpr(
  14285. OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
  14286. if (getCurFunction())
  14287. getCurFunction()->AddrLabels.push_back(Res);
  14288. return Res;
  14289. }
  14290. void Sema::ActOnStartStmtExpr() {
  14291. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  14292. }
  14293. void Sema::ActOnStmtExprError() {
  14294. // Note that function is also called by TreeTransform when leaving a
  14295. // StmtExpr scope without rebuilding anything.
  14296. DiscardCleanupsInEvaluationContext();
  14297. PopExpressionEvaluationContext();
  14298. }
  14299. ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
  14300. SourceLocation RPLoc) {
  14301. return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
  14302. }
  14303. ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  14304. SourceLocation RPLoc, unsigned TemplateDepth) {
  14305. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  14306. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  14307. if (hasAnyUnrecoverableErrorsInThisFunction())
  14308. DiscardCleanupsInEvaluationContext();
  14309. assert(!Cleanup.exprNeedsCleanups() &&
  14310. "cleanups within StmtExpr not correctly bound!");
  14311. PopExpressionEvaluationContext();
  14312. // FIXME: there are a variety of strange constraints to enforce here, for
  14313. // example, it is not possible to goto into a stmt expression apparently.
  14314. // More semantic analysis is needed.
  14315. // If there are sub-stmts in the compound stmt, take the type of the last one
  14316. // as the type of the stmtexpr.
  14317. QualType Ty = Context.VoidTy;
  14318. bool StmtExprMayBindToTemp = false;
  14319. if (!Compound->body_empty()) {
  14320. // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
  14321. if (const auto *LastStmt =
  14322. dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
  14323. if (const Expr *Value = LastStmt->getExprStmt()) {
  14324. StmtExprMayBindToTemp = true;
  14325. Ty = Value->getType();
  14326. }
  14327. }
  14328. }
  14329. // FIXME: Check that expression type is complete/non-abstract; statement
  14330. // expressions are not lvalues.
  14331. Expr *ResStmtExpr =
  14332. new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
  14333. if (StmtExprMayBindToTemp)
  14334. return MaybeBindToTemporary(ResStmtExpr);
  14335. return ResStmtExpr;
  14336. }
  14337. ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
  14338. if (ER.isInvalid())
  14339. return ExprError();
  14340. // Do function/array conversion on the last expression, but not
  14341. // lvalue-to-rvalue. However, initialize an unqualified type.
  14342. ER = DefaultFunctionArrayConversion(ER.get());
  14343. if (ER.isInvalid())
  14344. return ExprError();
  14345. Expr *E = ER.get();
  14346. if (E->isTypeDependent())
  14347. return E;
  14348. // In ARC, if the final expression ends in a consume, splice
  14349. // the consume out and bind it later. In the alternate case
  14350. // (when dealing with a retainable type), the result
  14351. // initialization will create a produce. In both cases the
  14352. // result will be +1, and we'll need to balance that out with
  14353. // a bind.
  14354. auto *Cast = dyn_cast<ImplicitCastExpr>(E);
  14355. if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
  14356. return Cast->getSubExpr();
  14357. // FIXME: Provide a better location for the initialization.
  14358. return PerformCopyInitialization(
  14359. InitializedEntity::InitializeStmtExprResult(
  14360. E->getBeginLoc(), E->getType().getUnqualifiedType()),
  14361. SourceLocation(), E);
  14362. }
  14363. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  14364. TypeSourceInfo *TInfo,
  14365. ArrayRef<OffsetOfComponent> Components,
  14366. SourceLocation RParenLoc) {
  14367. QualType ArgTy = TInfo->getType();
  14368. bool Dependent = ArgTy->isDependentType();
  14369. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  14370. // We must have at least one component that refers to the type, and the first
  14371. // one is known to be a field designator. Verify that the ArgTy represents
  14372. // a struct/union/class.
  14373. if (!Dependent && !ArgTy->isRecordType())
  14374. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  14375. << ArgTy << TypeRange);
  14376. // Type must be complete per C99 7.17p3 because a declaring a variable
  14377. // with an incomplete type would be ill-formed.
  14378. if (!Dependent
  14379. && RequireCompleteType(BuiltinLoc, ArgTy,
  14380. diag::err_offsetof_incomplete_type, TypeRange))
  14381. return ExprError();
  14382. bool DidWarnAboutNonPOD = false;
  14383. QualType CurrentType = ArgTy;
  14384. SmallVector<OffsetOfNode, 4> Comps;
  14385. SmallVector<Expr*, 4> Exprs;
  14386. for (const OffsetOfComponent &OC : Components) {
  14387. if (OC.isBrackets) {
  14388. // Offset of an array sub-field. TODO: Should we allow vector elements?
  14389. if (!CurrentType->isDependentType()) {
  14390. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  14391. if(!AT)
  14392. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  14393. << CurrentType);
  14394. CurrentType = AT->getElementType();
  14395. } else
  14396. CurrentType = Context.DependentTy;
  14397. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  14398. if (IdxRval.isInvalid())
  14399. return ExprError();
  14400. Expr *Idx = IdxRval.get();
  14401. // The expression must be an integral expression.
  14402. // FIXME: An integral constant expression?
  14403. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  14404. !Idx->getType()->isIntegerType())
  14405. return ExprError(
  14406. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  14407. << Idx->getSourceRange());
  14408. // Record this array index.
  14409. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  14410. Exprs.push_back(Idx);
  14411. continue;
  14412. }
  14413. // Offset of a field.
  14414. if (CurrentType->isDependentType()) {
  14415. // We have the offset of a field, but we can't look into the dependent
  14416. // type. Just record the identifier of the field.
  14417. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  14418. CurrentType = Context.DependentTy;
  14419. continue;
  14420. }
  14421. // We need to have a complete type to look into.
  14422. if (RequireCompleteType(OC.LocStart, CurrentType,
  14423. diag::err_offsetof_incomplete_type))
  14424. return ExprError();
  14425. // Look for the designated field.
  14426. const RecordType *RC = CurrentType->getAs<RecordType>();
  14427. if (!RC)
  14428. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  14429. << CurrentType);
  14430. RecordDecl *RD = RC->getDecl();
  14431. // C++ [lib.support.types]p5:
  14432. // The macro offsetof accepts a restricted set of type arguments in this
  14433. // International Standard. type shall be a POD structure or a POD union
  14434. // (clause 9).
  14435. // C++11 [support.types]p4:
  14436. // If type is not a standard-layout class (Clause 9), the results are
  14437. // undefined.
  14438. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  14439. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  14440. unsigned DiagID =
  14441. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  14442. : diag::ext_offsetof_non_pod_type;
  14443. if (!IsSafe && !DidWarnAboutNonPOD &&
  14444. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  14445. PDiag(DiagID)
  14446. << SourceRange(Components[0].LocStart, OC.LocEnd)
  14447. << CurrentType))
  14448. DidWarnAboutNonPOD = true;
  14449. }
  14450. // Look for the field.
  14451. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  14452. LookupQualifiedName(R, RD);
  14453. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  14454. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  14455. if (!MemberDecl) {
  14456. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  14457. MemberDecl = IndirectMemberDecl->getAnonField();
  14458. }
  14459. if (!MemberDecl)
  14460. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  14461. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  14462. OC.LocEnd));
  14463. // C99 7.17p3:
  14464. // (If the specified member is a bit-field, the behavior is undefined.)
  14465. //
  14466. // We diagnose this as an error.
  14467. if (MemberDecl->isBitField()) {
  14468. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  14469. << MemberDecl->getDeclName()
  14470. << SourceRange(BuiltinLoc, RParenLoc);
  14471. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  14472. return ExprError();
  14473. }
  14474. RecordDecl *Parent = MemberDecl->getParent();
  14475. if (IndirectMemberDecl)
  14476. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  14477. // If the member was found in a base class, introduce OffsetOfNodes for
  14478. // the base class indirections.
  14479. CXXBasePaths Paths;
  14480. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  14481. Paths)) {
  14482. if (Paths.getDetectedVirtual()) {
  14483. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  14484. << MemberDecl->getDeclName()
  14485. << SourceRange(BuiltinLoc, RParenLoc);
  14486. return ExprError();
  14487. }
  14488. CXXBasePath &Path = Paths.front();
  14489. for (const CXXBasePathElement &B : Path)
  14490. Comps.push_back(OffsetOfNode(B.Base));
  14491. }
  14492. if (IndirectMemberDecl) {
  14493. for (auto *FI : IndirectMemberDecl->chain()) {
  14494. assert(isa<FieldDecl>(FI));
  14495. Comps.push_back(OffsetOfNode(OC.LocStart,
  14496. cast<FieldDecl>(FI), OC.LocEnd));
  14497. }
  14498. } else
  14499. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  14500. CurrentType = MemberDecl->getType().getNonReferenceType();
  14501. }
  14502. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  14503. Comps, Exprs, RParenLoc);
  14504. }
  14505. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  14506. SourceLocation BuiltinLoc,
  14507. SourceLocation TypeLoc,
  14508. ParsedType ParsedArgTy,
  14509. ArrayRef<OffsetOfComponent> Components,
  14510. SourceLocation RParenLoc) {
  14511. TypeSourceInfo *ArgTInfo;
  14512. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  14513. if (ArgTy.isNull())
  14514. return ExprError();
  14515. if (!ArgTInfo)
  14516. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  14517. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  14518. }
  14519. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  14520. Expr *CondExpr,
  14521. Expr *LHSExpr, Expr *RHSExpr,
  14522. SourceLocation RPLoc) {
  14523. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  14524. ExprValueKind VK = VK_PRValue;
  14525. ExprObjectKind OK = OK_Ordinary;
  14526. QualType resType;
  14527. bool CondIsTrue = false;
  14528. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  14529. resType = Context.DependentTy;
  14530. } else {
  14531. // The conditional expression is required to be a constant expression.
  14532. llvm::APSInt condEval(32);
  14533. ExprResult CondICE = VerifyIntegerConstantExpression(
  14534. CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
  14535. if (CondICE.isInvalid())
  14536. return ExprError();
  14537. CondExpr = CondICE.get();
  14538. CondIsTrue = condEval.getZExtValue();
  14539. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  14540. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  14541. resType = ActiveExpr->getType();
  14542. VK = ActiveExpr->getValueKind();
  14543. OK = ActiveExpr->getObjectKind();
  14544. }
  14545. return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
  14546. resType, VK, OK, RPLoc, CondIsTrue);
  14547. }
  14548. //===----------------------------------------------------------------------===//
  14549. // Clang Extensions.
  14550. //===----------------------------------------------------------------------===//
  14551. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  14552. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  14553. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  14554. if (LangOpts.CPlusPlus) {
  14555. MangleNumberingContext *MCtx;
  14556. Decl *ManglingContextDecl;
  14557. std::tie(MCtx, ManglingContextDecl) =
  14558. getCurrentMangleNumberContext(Block->getDeclContext());
  14559. if (MCtx) {
  14560. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  14561. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  14562. }
  14563. }
  14564. PushBlockScope(CurScope, Block);
  14565. CurContext->addDecl(Block);
  14566. if (CurScope)
  14567. PushDeclContext(CurScope, Block);
  14568. else
  14569. CurContext = Block;
  14570. getCurBlock()->HasImplicitReturnType = true;
  14571. // Enter a new evaluation context to insulate the block from any
  14572. // cleanups from the enclosing full-expression.
  14573. PushExpressionEvaluationContext(
  14574. ExpressionEvaluationContext::PotentiallyEvaluated);
  14575. }
  14576. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  14577. Scope *CurScope) {
  14578. assert(ParamInfo.getIdentifier() == nullptr &&
  14579. "block-id should have no identifier!");
  14580. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
  14581. BlockScopeInfo *CurBlock = getCurBlock();
  14582. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  14583. QualType T = Sig->getType();
  14584. // FIXME: We should allow unexpanded parameter packs here, but that would,
  14585. // in turn, make the block expression contain unexpanded parameter packs.
  14586. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  14587. // Drop the parameters.
  14588. FunctionProtoType::ExtProtoInfo EPI;
  14589. EPI.HasTrailingReturn = false;
  14590. EPI.TypeQuals.addConst();
  14591. T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
  14592. Sig = Context.getTrivialTypeSourceInfo(T);
  14593. }
  14594. // GetTypeForDeclarator always produces a function type for a block
  14595. // literal signature. Furthermore, it is always a FunctionProtoType
  14596. // unless the function was written with a typedef.
  14597. assert(T->isFunctionType() &&
  14598. "GetTypeForDeclarator made a non-function block signature");
  14599. // Look for an explicit signature in that function type.
  14600. FunctionProtoTypeLoc ExplicitSignature;
  14601. if ((ExplicitSignature = Sig->getTypeLoc()
  14602. .getAsAdjusted<FunctionProtoTypeLoc>())) {
  14603. // Check whether that explicit signature was synthesized by
  14604. // GetTypeForDeclarator. If so, don't save that as part of the
  14605. // written signature.
  14606. if (ExplicitSignature.getLocalRangeBegin() ==
  14607. ExplicitSignature.getLocalRangeEnd()) {
  14608. // This would be much cheaper if we stored TypeLocs instead of
  14609. // TypeSourceInfos.
  14610. TypeLoc Result = ExplicitSignature.getReturnLoc();
  14611. unsigned Size = Result.getFullDataSize();
  14612. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  14613. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  14614. ExplicitSignature = FunctionProtoTypeLoc();
  14615. }
  14616. }
  14617. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  14618. CurBlock->FunctionType = T;
  14619. const auto *Fn = T->castAs<FunctionType>();
  14620. QualType RetTy = Fn->getReturnType();
  14621. bool isVariadic =
  14622. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  14623. CurBlock->TheDecl->setIsVariadic(isVariadic);
  14624. // Context.DependentTy is used as a placeholder for a missing block
  14625. // return type. TODO: what should we do with declarators like:
  14626. // ^ * { ... }
  14627. // If the answer is "apply template argument deduction"....
  14628. if (RetTy != Context.DependentTy) {
  14629. CurBlock->ReturnType = RetTy;
  14630. CurBlock->TheDecl->setBlockMissingReturnType(false);
  14631. CurBlock->HasImplicitReturnType = false;
  14632. }
  14633. // Push block parameters from the declarator if we had them.
  14634. SmallVector<ParmVarDecl*, 8> Params;
  14635. if (ExplicitSignature) {
  14636. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  14637. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  14638. if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
  14639. !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
  14640. // Diagnose this as an extension in C17 and earlier.
  14641. if (!getLangOpts().C2x)
  14642. Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
  14643. }
  14644. Params.push_back(Param);
  14645. }
  14646. // Fake up parameter variables if we have a typedef, like
  14647. // ^ fntype { ... }
  14648. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  14649. for (const auto &I : Fn->param_types()) {
  14650. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  14651. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  14652. Params.push_back(Param);
  14653. }
  14654. }
  14655. // Set the parameters on the block decl.
  14656. if (!Params.empty()) {
  14657. CurBlock->TheDecl->setParams(Params);
  14658. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  14659. /*CheckParameterNames=*/false);
  14660. }
  14661. // Finally we can process decl attributes.
  14662. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  14663. // Put the parameter variables in scope.
  14664. for (auto *AI : CurBlock->TheDecl->parameters()) {
  14665. AI->setOwningFunction(CurBlock->TheDecl);
  14666. // If this has an identifier, add it to the scope stack.
  14667. if (AI->getIdentifier()) {
  14668. CheckShadow(CurBlock->TheScope, AI);
  14669. PushOnScopeChains(AI, CurBlock->TheScope);
  14670. }
  14671. }
  14672. }
  14673. /// ActOnBlockError - If there is an error parsing a block, this callback
  14674. /// is invoked to pop the information about the block from the action impl.
  14675. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  14676. // Leave the expression-evaluation context.
  14677. DiscardCleanupsInEvaluationContext();
  14678. PopExpressionEvaluationContext();
  14679. // Pop off CurBlock, handle nested blocks.
  14680. PopDeclContext();
  14681. PopFunctionScopeInfo();
  14682. }
  14683. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  14684. /// literal was successfully completed. ^(int x){...}
  14685. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  14686. Stmt *Body, Scope *CurScope) {
  14687. // If blocks are disabled, emit an error.
  14688. if (!LangOpts.Blocks)
  14689. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  14690. // Leave the expression-evaluation context.
  14691. if (hasAnyUnrecoverableErrorsInThisFunction())
  14692. DiscardCleanupsInEvaluationContext();
  14693. assert(!Cleanup.exprNeedsCleanups() &&
  14694. "cleanups within block not correctly bound!");
  14695. PopExpressionEvaluationContext();
  14696. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  14697. BlockDecl *BD = BSI->TheDecl;
  14698. if (BSI->HasImplicitReturnType)
  14699. deduceClosureReturnType(*BSI);
  14700. QualType RetTy = Context.VoidTy;
  14701. if (!BSI->ReturnType.isNull())
  14702. RetTy = BSI->ReturnType;
  14703. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  14704. QualType BlockTy;
  14705. // If the user wrote a function type in some form, try to use that.
  14706. if (!BSI->FunctionType.isNull()) {
  14707. const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
  14708. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  14709. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  14710. // Turn protoless block types into nullary block types.
  14711. if (isa<FunctionNoProtoType>(FTy)) {
  14712. FunctionProtoType::ExtProtoInfo EPI;
  14713. EPI.ExtInfo = Ext;
  14714. BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
  14715. // Otherwise, if we don't need to change anything about the function type,
  14716. // preserve its sugar structure.
  14717. } else if (FTy->getReturnType() == RetTy &&
  14718. (!NoReturn || FTy->getNoReturnAttr())) {
  14719. BlockTy = BSI->FunctionType;
  14720. // Otherwise, make the minimal modifications to the function type.
  14721. } else {
  14722. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  14723. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  14724. EPI.TypeQuals = Qualifiers();
  14725. EPI.ExtInfo = Ext;
  14726. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  14727. }
  14728. // If we don't have a function type, just build one from nothing.
  14729. } else {
  14730. FunctionProtoType::ExtProtoInfo EPI;
  14731. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  14732. BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
  14733. }
  14734. DiagnoseUnusedParameters(BD->parameters());
  14735. BlockTy = Context.getBlockPointerType(BlockTy);
  14736. // If needed, diagnose invalid gotos and switches in the block.
  14737. if (getCurFunction()->NeedsScopeChecking() &&
  14738. !PP.isCodeCompletionEnabled())
  14739. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  14740. BD->setBody(cast<CompoundStmt>(Body));
  14741. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  14742. DiagnoseUnguardedAvailabilityViolations(BD);
  14743. // Try to apply the named return value optimization. We have to check again
  14744. // if we can do this, though, because blocks keep return statements around
  14745. // to deduce an implicit return type.
  14746. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  14747. !BD->isDependentContext())
  14748. computeNRVO(Body, BSI);
  14749. if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
  14750. RetTy.hasNonTrivialToPrimitiveCopyCUnion())
  14751. checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
  14752. NTCUK_Destruct|NTCUK_Copy);
  14753. PopDeclContext();
  14754. // Set the captured variables on the block.
  14755. SmallVector<BlockDecl::Capture, 4> Captures;
  14756. for (Capture &Cap : BSI->Captures) {
  14757. if (Cap.isInvalid() || Cap.isThisCapture())
  14758. continue;
  14759. // Cap.getVariable() is always a VarDecl because
  14760. // blocks cannot capture structured bindings or other ValueDecl kinds.
  14761. auto *Var = cast<VarDecl>(Cap.getVariable());
  14762. Expr *CopyExpr = nullptr;
  14763. if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
  14764. if (const RecordType *Record =
  14765. Cap.getCaptureType()->getAs<RecordType>()) {
  14766. // The capture logic needs the destructor, so make sure we mark it.
  14767. // Usually this is unnecessary because most local variables have
  14768. // their destructors marked at declaration time, but parameters are
  14769. // an exception because it's technically only the call site that
  14770. // actually requires the destructor.
  14771. if (isa<ParmVarDecl>(Var))
  14772. FinalizeVarWithDestructor(Var, Record);
  14773. // Enter a separate potentially-evaluated context while building block
  14774. // initializers to isolate their cleanups from those of the block
  14775. // itself.
  14776. // FIXME: Is this appropriate even when the block itself occurs in an
  14777. // unevaluated operand?
  14778. EnterExpressionEvaluationContext EvalContext(
  14779. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  14780. SourceLocation Loc = Cap.getLocation();
  14781. ExprResult Result = BuildDeclarationNameExpr(
  14782. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  14783. // According to the blocks spec, the capture of a variable from
  14784. // the stack requires a const copy constructor. This is not true
  14785. // of the copy/move done to move a __block variable to the heap.
  14786. if (!Result.isInvalid() &&
  14787. !Result.get()->getType().isConstQualified()) {
  14788. Result = ImpCastExprToType(Result.get(),
  14789. Result.get()->getType().withConst(),
  14790. CK_NoOp, VK_LValue);
  14791. }
  14792. if (!Result.isInvalid()) {
  14793. Result = PerformCopyInitialization(
  14794. InitializedEntity::InitializeBlock(Var->getLocation(),
  14795. Cap.getCaptureType()),
  14796. Loc, Result.get());
  14797. }
  14798. // Build a full-expression copy expression if initialization
  14799. // succeeded and used a non-trivial constructor. Recover from
  14800. // errors by pretending that the copy isn't necessary.
  14801. if (!Result.isInvalid() &&
  14802. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  14803. ->isTrivial()) {
  14804. Result = MaybeCreateExprWithCleanups(Result);
  14805. CopyExpr = Result.get();
  14806. }
  14807. }
  14808. }
  14809. BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
  14810. CopyExpr);
  14811. Captures.push_back(NewCap);
  14812. }
  14813. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  14814. // Pop the block scope now but keep it alive to the end of this function.
  14815. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  14816. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
  14817. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  14818. // If the block isn't obviously global, i.e. it captures anything at
  14819. // all, then we need to do a few things in the surrounding context:
  14820. if (Result->getBlockDecl()->hasCaptures()) {
  14821. // First, this expression has a new cleanup object.
  14822. ExprCleanupObjects.push_back(Result->getBlockDecl());
  14823. Cleanup.setExprNeedsCleanups(true);
  14824. // It also gets a branch-protected scope if any of the captured
  14825. // variables needs destruction.
  14826. for (const auto &CI : Result->getBlockDecl()->captures()) {
  14827. const VarDecl *var = CI.getVariable();
  14828. if (var->getType().isDestructedType() != QualType::DK_none) {
  14829. setFunctionHasBranchProtectedScope();
  14830. break;
  14831. }
  14832. }
  14833. }
  14834. if (getCurFunction())
  14835. getCurFunction()->addBlock(BD);
  14836. return Result;
  14837. }
  14838. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  14839. SourceLocation RPLoc) {
  14840. TypeSourceInfo *TInfo;
  14841. GetTypeFromParser(Ty, &TInfo);
  14842. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  14843. }
  14844. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  14845. Expr *E, TypeSourceInfo *TInfo,
  14846. SourceLocation RPLoc) {
  14847. Expr *OrigExpr = E;
  14848. bool IsMS = false;
  14849. // CUDA device code does not support varargs.
  14850. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  14851. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  14852. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  14853. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  14854. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  14855. }
  14856. }
  14857. // NVPTX does not support va_arg expression.
  14858. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  14859. Context.getTargetInfo().getTriple().isNVPTX())
  14860. targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
  14861. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  14862. // as Microsoft ABI on an actual Microsoft platform, where
  14863. // __builtin_ms_va_list and __builtin_va_list are the same.)
  14864. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  14865. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  14866. QualType MSVaListType = Context.getBuiltinMSVaListType();
  14867. if (Context.hasSameType(MSVaListType, E->getType())) {
  14868. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  14869. return ExprError();
  14870. IsMS = true;
  14871. }
  14872. }
  14873. // Get the va_list type
  14874. QualType VaListType = Context.getBuiltinVaListType();
  14875. if (!IsMS) {
  14876. if (VaListType->isArrayType()) {
  14877. // Deal with implicit array decay; for example, on x86-64,
  14878. // va_list is an array, but it's supposed to decay to
  14879. // a pointer for va_arg.
  14880. VaListType = Context.getArrayDecayedType(VaListType);
  14881. // Make sure the input expression also decays appropriately.
  14882. ExprResult Result = UsualUnaryConversions(E);
  14883. if (Result.isInvalid())
  14884. return ExprError();
  14885. E = Result.get();
  14886. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  14887. // If va_list is a record type and we are compiling in C++ mode,
  14888. // check the argument using reference binding.
  14889. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  14890. Context, Context.getLValueReferenceType(VaListType), false);
  14891. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  14892. if (Init.isInvalid())
  14893. return ExprError();
  14894. E = Init.getAs<Expr>();
  14895. } else {
  14896. // Otherwise, the va_list argument must be an l-value because
  14897. // it is modified by va_arg.
  14898. if (!E->isTypeDependent() &&
  14899. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  14900. return ExprError();
  14901. }
  14902. }
  14903. if (!IsMS && !E->isTypeDependent() &&
  14904. !Context.hasSameType(VaListType, E->getType()))
  14905. return ExprError(
  14906. Diag(E->getBeginLoc(),
  14907. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  14908. << OrigExpr->getType() << E->getSourceRange());
  14909. if (!TInfo->getType()->isDependentType()) {
  14910. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  14911. diag::err_second_parameter_to_va_arg_incomplete,
  14912. TInfo->getTypeLoc()))
  14913. return ExprError();
  14914. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  14915. TInfo->getType(),
  14916. diag::err_second_parameter_to_va_arg_abstract,
  14917. TInfo->getTypeLoc()))
  14918. return ExprError();
  14919. if (!TInfo->getType().isPODType(Context)) {
  14920. Diag(TInfo->getTypeLoc().getBeginLoc(),
  14921. TInfo->getType()->isObjCLifetimeType()
  14922. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  14923. : diag::warn_second_parameter_to_va_arg_not_pod)
  14924. << TInfo->getType()
  14925. << TInfo->getTypeLoc().getSourceRange();
  14926. }
  14927. // Check for va_arg where arguments of the given type will be promoted
  14928. // (i.e. this va_arg is guaranteed to have undefined behavior).
  14929. QualType PromoteType;
  14930. if (Context.isPromotableIntegerType(TInfo->getType())) {
  14931. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  14932. // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
  14933. // and C2x 7.16.1.1p2 says, in part:
  14934. // If type is not compatible with the type of the actual next argument
  14935. // (as promoted according to the default argument promotions), the
  14936. // behavior is undefined, except for the following cases:
  14937. // - both types are pointers to qualified or unqualified versions of
  14938. // compatible types;
  14939. // - one type is a signed integer type, the other type is the
  14940. // corresponding unsigned integer type, and the value is
  14941. // representable in both types;
  14942. // - one type is pointer to qualified or unqualified void and the
  14943. // other is a pointer to a qualified or unqualified character type.
  14944. // Given that type compatibility is the primary requirement (ignoring
  14945. // qualifications), you would think we could call typesAreCompatible()
  14946. // directly to test this. However, in C++, that checks for *same type*,
  14947. // which causes false positives when passing an enumeration type to
  14948. // va_arg. Instead, get the underlying type of the enumeration and pass
  14949. // that.
  14950. QualType UnderlyingType = TInfo->getType();
  14951. if (const auto *ET = UnderlyingType->getAs<EnumType>())
  14952. UnderlyingType = ET->getDecl()->getIntegerType();
  14953. if (Context.typesAreCompatible(PromoteType, UnderlyingType,
  14954. /*CompareUnqualified*/ true))
  14955. PromoteType = QualType();
  14956. // If the types are still not compatible, we need to test whether the
  14957. // promoted type and the underlying type are the same except for
  14958. // signedness. Ask the AST for the correctly corresponding type and see
  14959. // if that's compatible.
  14960. if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
  14961. PromoteType->isUnsignedIntegerType() !=
  14962. UnderlyingType->isUnsignedIntegerType()) {
  14963. UnderlyingType =
  14964. UnderlyingType->isUnsignedIntegerType()
  14965. ? Context.getCorrespondingSignedType(UnderlyingType)
  14966. : Context.getCorrespondingUnsignedType(UnderlyingType);
  14967. if (Context.typesAreCompatible(PromoteType, UnderlyingType,
  14968. /*CompareUnqualified*/ true))
  14969. PromoteType = QualType();
  14970. }
  14971. }
  14972. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  14973. PromoteType = Context.DoubleTy;
  14974. if (!PromoteType.isNull())
  14975. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  14976. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  14977. << TInfo->getType()
  14978. << PromoteType
  14979. << TInfo->getTypeLoc().getSourceRange());
  14980. }
  14981. QualType T = TInfo->getType().getNonLValueExprType(Context);
  14982. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  14983. }
  14984. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  14985. // The type of __null will be int or long, depending on the size of
  14986. // pointers on the target.
  14987. QualType Ty;
  14988. unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
  14989. if (pw == Context.getTargetInfo().getIntWidth())
  14990. Ty = Context.IntTy;
  14991. else if (pw == Context.getTargetInfo().getLongWidth())
  14992. Ty = Context.LongTy;
  14993. else if (pw == Context.getTargetInfo().getLongLongWidth())
  14994. Ty = Context.LongLongTy;
  14995. else {
  14996. llvm_unreachable("I don't know size of pointer!");
  14997. }
  14998. return new (Context) GNUNullExpr(Ty, TokenLoc);
  14999. }
  15000. static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
  15001. CXXRecordDecl *ImplDecl = nullptr;
  15002. // Fetch the std::source_location::__impl decl.
  15003. if (NamespaceDecl *Std = S.getStdNamespace()) {
  15004. LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
  15005. Loc, Sema::LookupOrdinaryName);
  15006. if (S.LookupQualifiedName(ResultSL, Std)) {
  15007. if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
  15008. LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
  15009. Loc, Sema::LookupOrdinaryName);
  15010. if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
  15011. S.LookupQualifiedName(ResultImpl, SLDecl)) {
  15012. ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
  15013. }
  15014. }
  15015. }
  15016. }
  15017. if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
  15018. S.Diag(Loc, diag::err_std_source_location_impl_not_found);
  15019. return nullptr;
  15020. }
  15021. // Verify that __impl is a trivial struct type, with no base classes, and with
  15022. // only the four expected fields.
  15023. if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
  15024. ImplDecl->getNumBases() != 0) {
  15025. S.Diag(Loc, diag::err_std_source_location_impl_malformed);
  15026. return nullptr;
  15027. }
  15028. unsigned Count = 0;
  15029. for (FieldDecl *F : ImplDecl->fields()) {
  15030. StringRef Name = F->getName();
  15031. if (Name == "_M_file_name") {
  15032. if (F->getType() !=
  15033. S.Context.getPointerType(S.Context.CharTy.withConst()))
  15034. break;
  15035. Count++;
  15036. } else if (Name == "_M_function_name") {
  15037. if (F->getType() !=
  15038. S.Context.getPointerType(S.Context.CharTy.withConst()))
  15039. break;
  15040. Count++;
  15041. } else if (Name == "_M_line") {
  15042. if (!F->getType()->isIntegerType())
  15043. break;
  15044. Count++;
  15045. } else if (Name == "_M_column") {
  15046. if (!F->getType()->isIntegerType())
  15047. break;
  15048. Count++;
  15049. } else {
  15050. Count = 100; // invalid
  15051. break;
  15052. }
  15053. }
  15054. if (Count != 4) {
  15055. S.Diag(Loc, diag::err_std_source_location_impl_malformed);
  15056. return nullptr;
  15057. }
  15058. return ImplDecl;
  15059. }
  15060. ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
  15061. SourceLocation BuiltinLoc,
  15062. SourceLocation RPLoc) {
  15063. QualType ResultTy;
  15064. switch (Kind) {
  15065. case SourceLocExpr::File:
  15066. case SourceLocExpr::Function: {
  15067. QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
  15068. ResultTy =
  15069. Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
  15070. break;
  15071. }
  15072. case SourceLocExpr::Line:
  15073. case SourceLocExpr::Column:
  15074. ResultTy = Context.UnsignedIntTy;
  15075. break;
  15076. case SourceLocExpr::SourceLocStruct:
  15077. if (!StdSourceLocationImplDecl) {
  15078. StdSourceLocationImplDecl =
  15079. LookupStdSourceLocationImpl(*this, BuiltinLoc);
  15080. if (!StdSourceLocationImplDecl)
  15081. return ExprError();
  15082. }
  15083. ResultTy = Context.getPointerType(
  15084. Context.getRecordType(StdSourceLocationImplDecl).withConst());
  15085. break;
  15086. }
  15087. return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
  15088. }
  15089. ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
  15090. QualType ResultTy,
  15091. SourceLocation BuiltinLoc,
  15092. SourceLocation RPLoc,
  15093. DeclContext *ParentContext) {
  15094. return new (Context)
  15095. SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
  15096. }
  15097. bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
  15098. bool Diagnose) {
  15099. if (!getLangOpts().ObjC)
  15100. return false;
  15101. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  15102. if (!PT)
  15103. return false;
  15104. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  15105. // Ignore any parens, implicit casts (should only be
  15106. // array-to-pointer decays), and not-so-opaque values. The last is
  15107. // important for making this trigger for property assignments.
  15108. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  15109. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  15110. if (OV->getSourceExpr())
  15111. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  15112. if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
  15113. if (!PT->isObjCIdType() &&
  15114. !(ID && ID->getIdentifier()->isStr("NSString")))
  15115. return false;
  15116. if (!SL->isOrdinary())
  15117. return false;
  15118. if (Diagnose) {
  15119. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  15120. << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  15121. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  15122. }
  15123. return true;
  15124. }
  15125. if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
  15126. isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
  15127. isa<CXXBoolLiteralExpr>(SrcExpr)) &&
  15128. !SrcExpr->isNullPointerConstant(
  15129. getASTContext(), Expr::NPC_NeverValueDependent)) {
  15130. if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
  15131. return false;
  15132. if (Diagnose) {
  15133. Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
  15134. << /*number*/1
  15135. << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
  15136. Expr *NumLit =
  15137. BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
  15138. if (NumLit)
  15139. Exp = NumLit;
  15140. }
  15141. return true;
  15142. }
  15143. return false;
  15144. }
  15145. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  15146. const Expr *SrcExpr) {
  15147. if (!DstType->isFunctionPointerType() ||
  15148. !SrcExpr->getType()->isFunctionType())
  15149. return false;
  15150. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  15151. if (!DRE)
  15152. return false;
  15153. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  15154. if (!FD)
  15155. return false;
  15156. return !S.checkAddressOfFunctionIsAvailable(FD,
  15157. /*Complain=*/true,
  15158. SrcExpr->getBeginLoc());
  15159. }
  15160. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  15161. SourceLocation Loc,
  15162. QualType DstType, QualType SrcType,
  15163. Expr *SrcExpr, AssignmentAction Action,
  15164. bool *Complained) {
  15165. if (Complained)
  15166. *Complained = false;
  15167. // Decode the result (notice that AST's are still created for extensions).
  15168. bool CheckInferredResultType = false;
  15169. bool isInvalid = false;
  15170. unsigned DiagKind = 0;
  15171. ConversionFixItGenerator ConvHints;
  15172. bool MayHaveConvFixit = false;
  15173. bool MayHaveFunctionDiff = false;
  15174. const ObjCInterfaceDecl *IFace = nullptr;
  15175. const ObjCProtocolDecl *PDecl = nullptr;
  15176. switch (ConvTy) {
  15177. case Compatible:
  15178. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  15179. return false;
  15180. case PointerToInt:
  15181. if (getLangOpts().CPlusPlus) {
  15182. DiagKind = diag::err_typecheck_convert_pointer_int;
  15183. isInvalid = true;
  15184. } else {
  15185. DiagKind = diag::ext_typecheck_convert_pointer_int;
  15186. }
  15187. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  15188. MayHaveConvFixit = true;
  15189. break;
  15190. case IntToPointer:
  15191. if (getLangOpts().CPlusPlus) {
  15192. DiagKind = diag::err_typecheck_convert_int_pointer;
  15193. isInvalid = true;
  15194. } else {
  15195. DiagKind = diag::ext_typecheck_convert_int_pointer;
  15196. }
  15197. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  15198. MayHaveConvFixit = true;
  15199. break;
  15200. case IncompatibleFunctionPointerStrict:
  15201. DiagKind =
  15202. diag::warn_typecheck_convert_incompatible_function_pointer_strict;
  15203. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  15204. MayHaveConvFixit = true;
  15205. break;
  15206. case IncompatibleFunctionPointer:
  15207. if (getLangOpts().CPlusPlus) {
  15208. DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
  15209. isInvalid = true;
  15210. } else {
  15211. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  15212. }
  15213. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  15214. MayHaveConvFixit = true;
  15215. break;
  15216. case IncompatiblePointer:
  15217. if (Action == AA_Passing_CFAudited) {
  15218. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  15219. } else if (getLangOpts().CPlusPlus) {
  15220. DiagKind = diag::err_typecheck_convert_incompatible_pointer;
  15221. isInvalid = true;
  15222. } else {
  15223. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  15224. }
  15225. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  15226. SrcType->isObjCObjectPointerType();
  15227. if (!CheckInferredResultType) {
  15228. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  15229. } else if (CheckInferredResultType) {
  15230. SrcType = SrcType.getUnqualifiedType();
  15231. DstType = DstType.getUnqualifiedType();
  15232. }
  15233. MayHaveConvFixit = true;
  15234. break;
  15235. case IncompatiblePointerSign:
  15236. if (getLangOpts().CPlusPlus) {
  15237. DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
  15238. isInvalid = true;
  15239. } else {
  15240. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  15241. }
  15242. break;
  15243. case FunctionVoidPointer:
  15244. if (getLangOpts().CPlusPlus) {
  15245. DiagKind = diag::err_typecheck_convert_pointer_void_func;
  15246. isInvalid = true;
  15247. } else {
  15248. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  15249. }
  15250. break;
  15251. case IncompatiblePointerDiscardsQualifiers: {
  15252. // Perform array-to-pointer decay if necessary.
  15253. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  15254. isInvalid = true;
  15255. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  15256. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  15257. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  15258. DiagKind = diag::err_typecheck_incompatible_address_space;
  15259. break;
  15260. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  15261. DiagKind = diag::err_typecheck_incompatible_ownership;
  15262. break;
  15263. }
  15264. llvm_unreachable("unknown error case for discarding qualifiers!");
  15265. // fallthrough
  15266. }
  15267. case CompatiblePointerDiscardsQualifiers:
  15268. // If the qualifiers lost were because we were applying the
  15269. // (deprecated) C++ conversion from a string literal to a char*
  15270. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  15271. // Ideally, this check would be performed in
  15272. // checkPointerTypesForAssignment. However, that would require a
  15273. // bit of refactoring (so that the second argument is an
  15274. // expression, rather than a type), which should be done as part
  15275. // of a larger effort to fix checkPointerTypesForAssignment for
  15276. // C++ semantics.
  15277. if (getLangOpts().CPlusPlus &&
  15278. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  15279. return false;
  15280. if (getLangOpts().CPlusPlus) {
  15281. DiagKind = diag::err_typecheck_convert_discards_qualifiers;
  15282. isInvalid = true;
  15283. } else {
  15284. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  15285. }
  15286. break;
  15287. case IncompatibleNestedPointerQualifiers:
  15288. if (getLangOpts().CPlusPlus) {
  15289. isInvalid = true;
  15290. DiagKind = diag::err_nested_pointer_qualifier_mismatch;
  15291. } else {
  15292. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  15293. }
  15294. break;
  15295. case IncompatibleNestedPointerAddressSpaceMismatch:
  15296. DiagKind = diag::err_typecheck_incompatible_nested_address_space;
  15297. isInvalid = true;
  15298. break;
  15299. case IntToBlockPointer:
  15300. DiagKind = diag::err_int_to_block_pointer;
  15301. isInvalid = true;
  15302. break;
  15303. case IncompatibleBlockPointer:
  15304. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  15305. isInvalid = true;
  15306. break;
  15307. case IncompatibleObjCQualifiedId: {
  15308. if (SrcType->isObjCQualifiedIdType()) {
  15309. const ObjCObjectPointerType *srcOPT =
  15310. SrcType->castAs<ObjCObjectPointerType>();
  15311. for (auto *srcProto : srcOPT->quals()) {
  15312. PDecl = srcProto;
  15313. break;
  15314. }
  15315. if (const ObjCInterfaceType *IFaceT =
  15316. DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
  15317. IFace = IFaceT->getDecl();
  15318. }
  15319. else if (DstType->isObjCQualifiedIdType()) {
  15320. const ObjCObjectPointerType *dstOPT =
  15321. DstType->castAs<ObjCObjectPointerType>();
  15322. for (auto *dstProto : dstOPT->quals()) {
  15323. PDecl = dstProto;
  15324. break;
  15325. }
  15326. if (const ObjCInterfaceType *IFaceT =
  15327. SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
  15328. IFace = IFaceT->getDecl();
  15329. }
  15330. if (getLangOpts().CPlusPlus) {
  15331. DiagKind = diag::err_incompatible_qualified_id;
  15332. isInvalid = true;
  15333. } else {
  15334. DiagKind = diag::warn_incompatible_qualified_id;
  15335. }
  15336. break;
  15337. }
  15338. case IncompatibleVectors:
  15339. if (getLangOpts().CPlusPlus) {
  15340. DiagKind = diag::err_incompatible_vectors;
  15341. isInvalid = true;
  15342. } else {
  15343. DiagKind = diag::warn_incompatible_vectors;
  15344. }
  15345. break;
  15346. case IncompatibleObjCWeakRef:
  15347. DiagKind = diag::err_arc_weak_unavailable_assign;
  15348. isInvalid = true;
  15349. break;
  15350. case Incompatible:
  15351. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  15352. if (Complained)
  15353. *Complained = true;
  15354. return true;
  15355. }
  15356. DiagKind = diag::err_typecheck_convert_incompatible;
  15357. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  15358. MayHaveConvFixit = true;
  15359. isInvalid = true;
  15360. MayHaveFunctionDiff = true;
  15361. break;
  15362. }
  15363. QualType FirstType, SecondType;
  15364. switch (Action) {
  15365. case AA_Assigning:
  15366. case AA_Initializing:
  15367. // The destination type comes first.
  15368. FirstType = DstType;
  15369. SecondType = SrcType;
  15370. break;
  15371. case AA_Returning:
  15372. case AA_Passing:
  15373. case AA_Passing_CFAudited:
  15374. case AA_Converting:
  15375. case AA_Sending:
  15376. case AA_Casting:
  15377. // The source type comes first.
  15378. FirstType = SrcType;
  15379. SecondType = DstType;
  15380. break;
  15381. }
  15382. PartialDiagnostic FDiag = PDiag(DiagKind);
  15383. AssignmentAction ActionForDiag = Action;
  15384. if (Action == AA_Passing_CFAudited)
  15385. ActionForDiag = AA_Passing;
  15386. FDiag << FirstType << SecondType << ActionForDiag
  15387. << SrcExpr->getSourceRange();
  15388. if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
  15389. DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
  15390. auto isPlainChar = [](const clang::Type *Type) {
  15391. return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
  15392. Type->isSpecificBuiltinType(BuiltinType::Char_U);
  15393. };
  15394. FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
  15395. isPlainChar(SecondType->getPointeeOrArrayElementType()));
  15396. }
  15397. // If we can fix the conversion, suggest the FixIts.
  15398. if (!ConvHints.isNull()) {
  15399. for (FixItHint &H : ConvHints.Hints)
  15400. FDiag << H;
  15401. }
  15402. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  15403. if (MayHaveFunctionDiff)
  15404. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  15405. Diag(Loc, FDiag);
  15406. if ((DiagKind == diag::warn_incompatible_qualified_id ||
  15407. DiagKind == diag::err_incompatible_qualified_id) &&
  15408. PDecl && IFace && !IFace->hasDefinition())
  15409. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  15410. << IFace << PDecl;
  15411. if (SecondType == Context.OverloadTy)
  15412. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  15413. FirstType, /*TakingAddress=*/true);
  15414. if (CheckInferredResultType)
  15415. EmitRelatedResultTypeNote(SrcExpr);
  15416. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  15417. EmitRelatedResultTypeNoteForReturn(DstType);
  15418. if (Complained)
  15419. *Complained = true;
  15420. return isInvalid;
  15421. }
  15422. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  15423. llvm::APSInt *Result,
  15424. AllowFoldKind CanFold) {
  15425. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  15426. public:
  15427. SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
  15428. QualType T) override {
  15429. return S.Diag(Loc, diag::err_ice_not_integral)
  15430. << T << S.LangOpts.CPlusPlus;
  15431. }
  15432. SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
  15433. return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
  15434. }
  15435. } Diagnoser;
  15436. return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
  15437. }
  15438. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  15439. llvm::APSInt *Result,
  15440. unsigned DiagID,
  15441. AllowFoldKind CanFold) {
  15442. class IDDiagnoser : public VerifyICEDiagnoser {
  15443. unsigned DiagID;
  15444. public:
  15445. IDDiagnoser(unsigned DiagID)
  15446. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  15447. SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
  15448. return S.Diag(Loc, DiagID);
  15449. }
  15450. } Diagnoser(DiagID);
  15451. return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
  15452. }
  15453. Sema::SemaDiagnosticBuilder
  15454. Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
  15455. QualType T) {
  15456. return diagnoseNotICE(S, Loc);
  15457. }
  15458. Sema::SemaDiagnosticBuilder
  15459. Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
  15460. return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
  15461. }
  15462. ExprResult
  15463. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  15464. VerifyICEDiagnoser &Diagnoser,
  15465. AllowFoldKind CanFold) {
  15466. SourceLocation DiagLoc = E->getBeginLoc();
  15467. if (getLangOpts().CPlusPlus11) {
  15468. // C++11 [expr.const]p5:
  15469. // If an expression of literal class type is used in a context where an
  15470. // integral constant expression is required, then that class type shall
  15471. // have a single non-explicit conversion function to an integral or
  15472. // unscoped enumeration type
  15473. ExprResult Converted;
  15474. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  15475. VerifyICEDiagnoser &BaseDiagnoser;
  15476. public:
  15477. CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
  15478. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
  15479. BaseDiagnoser.Suppress, true),
  15480. BaseDiagnoser(BaseDiagnoser) {}
  15481. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  15482. QualType T) override {
  15483. return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
  15484. }
  15485. SemaDiagnosticBuilder diagnoseIncomplete(
  15486. Sema &S, SourceLocation Loc, QualType T) override {
  15487. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  15488. }
  15489. SemaDiagnosticBuilder diagnoseExplicitConv(
  15490. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  15491. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  15492. }
  15493. SemaDiagnosticBuilder noteExplicitConv(
  15494. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  15495. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  15496. << ConvTy->isEnumeralType() << ConvTy;
  15497. }
  15498. SemaDiagnosticBuilder diagnoseAmbiguous(
  15499. Sema &S, SourceLocation Loc, QualType T) override {
  15500. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  15501. }
  15502. SemaDiagnosticBuilder noteAmbiguous(
  15503. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  15504. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  15505. << ConvTy->isEnumeralType() << ConvTy;
  15506. }
  15507. SemaDiagnosticBuilder diagnoseConversion(
  15508. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  15509. llvm_unreachable("conversion functions are permitted");
  15510. }
  15511. } ConvertDiagnoser(Diagnoser);
  15512. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  15513. ConvertDiagnoser);
  15514. if (Converted.isInvalid())
  15515. return Converted;
  15516. E = Converted.get();
  15517. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  15518. return ExprError();
  15519. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  15520. // An ICE must be of integral or unscoped enumeration type.
  15521. if (!Diagnoser.Suppress)
  15522. Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
  15523. << E->getSourceRange();
  15524. return ExprError();
  15525. }
  15526. ExprResult RValueExpr = DefaultLvalueConversion(E);
  15527. if (RValueExpr.isInvalid())
  15528. return ExprError();
  15529. E = RValueExpr.get();
  15530. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  15531. // in the non-ICE case.
  15532. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  15533. if (Result)
  15534. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  15535. if (!isa<ConstantExpr>(E))
  15536. E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
  15537. : ConstantExpr::Create(Context, E);
  15538. return E;
  15539. }
  15540. Expr::EvalResult EvalResult;
  15541. SmallVector<PartialDiagnosticAt, 8> Notes;
  15542. EvalResult.Diag = &Notes;
  15543. // Try to evaluate the expression, and produce diagnostics explaining why it's
  15544. // not a constant expression as a side-effect.
  15545. bool Folded =
  15546. E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
  15547. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  15548. if (!isa<ConstantExpr>(E))
  15549. E = ConstantExpr::Create(Context, E, EvalResult.Val);
  15550. // In C++11, we can rely on diagnostics being produced for any expression
  15551. // which is not a constant expression. If no diagnostics were produced, then
  15552. // this is a constant expression.
  15553. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  15554. if (Result)
  15555. *Result = EvalResult.Val.getInt();
  15556. return E;
  15557. }
  15558. // If our only note is the usual "invalid subexpression" note, just point
  15559. // the caret at its location rather than producing an essentially
  15560. // redundant note.
  15561. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  15562. diag::note_invalid_subexpr_in_const_expr) {
  15563. DiagLoc = Notes[0].first;
  15564. Notes.clear();
  15565. }
  15566. if (!Folded || !CanFold) {
  15567. if (!Diagnoser.Suppress) {
  15568. Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
  15569. for (const PartialDiagnosticAt &Note : Notes)
  15570. Diag(Note.first, Note.second);
  15571. }
  15572. return ExprError();
  15573. }
  15574. Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
  15575. for (const PartialDiagnosticAt &Note : Notes)
  15576. Diag(Note.first, Note.second);
  15577. if (Result)
  15578. *Result = EvalResult.Val.getInt();
  15579. return E;
  15580. }
  15581. namespace {
  15582. // Handle the case where we conclude a expression which we speculatively
  15583. // considered to be unevaluated is actually evaluated.
  15584. class TransformToPE : public TreeTransform<TransformToPE> {
  15585. typedef TreeTransform<TransformToPE> BaseTransform;
  15586. public:
  15587. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  15588. // Make sure we redo semantic analysis
  15589. bool AlwaysRebuild() { return true; }
  15590. bool ReplacingOriginal() { return true; }
  15591. // We need to special-case DeclRefExprs referring to FieldDecls which
  15592. // are not part of a member pointer formation; normal TreeTransforming
  15593. // doesn't catch this case because of the way we represent them in the AST.
  15594. // FIXME: This is a bit ugly; is it really the best way to handle this
  15595. // case?
  15596. //
  15597. // Error on DeclRefExprs referring to FieldDecls.
  15598. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  15599. if (isa<FieldDecl>(E->getDecl()) &&
  15600. !SemaRef.isUnevaluatedContext())
  15601. return SemaRef.Diag(E->getLocation(),
  15602. diag::err_invalid_non_static_member_use)
  15603. << E->getDecl() << E->getSourceRange();
  15604. return BaseTransform::TransformDeclRefExpr(E);
  15605. }
  15606. // Exception: filter out member pointer formation
  15607. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  15608. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  15609. return E;
  15610. return BaseTransform::TransformUnaryOperator(E);
  15611. }
  15612. // The body of a lambda-expression is in a separate expression evaluation
  15613. // context so never needs to be transformed.
  15614. // FIXME: Ideally we wouldn't transform the closure type either, and would
  15615. // just recreate the capture expressions and lambda expression.
  15616. StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
  15617. return SkipLambdaBody(E, Body);
  15618. }
  15619. };
  15620. }
  15621. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  15622. assert(isUnevaluatedContext() &&
  15623. "Should only transform unevaluated expressions");
  15624. ExprEvalContexts.back().Context =
  15625. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  15626. if (isUnevaluatedContext())
  15627. return E;
  15628. return TransformToPE(*this).TransformExpr(E);
  15629. }
  15630. TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
  15631. assert(isUnevaluatedContext() &&
  15632. "Should only transform unevaluated expressions");
  15633. ExprEvalContexts.back().Context =
  15634. ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
  15635. if (isUnevaluatedContext())
  15636. return TInfo;
  15637. return TransformToPE(*this).TransformType(TInfo);
  15638. }
  15639. void
  15640. Sema::PushExpressionEvaluationContext(
  15641. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  15642. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  15643. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  15644. LambdaContextDecl, ExprContext);
  15645. // Discarded statements and immediate contexts nested in other
  15646. // discarded statements or immediate context are themselves
  15647. // a discarded statement or an immediate context, respectively.
  15648. ExprEvalContexts.back().InDiscardedStatement =
  15649. ExprEvalContexts[ExprEvalContexts.size() - 2]
  15650. .isDiscardedStatementContext();
  15651. ExprEvalContexts.back().InImmediateFunctionContext =
  15652. ExprEvalContexts[ExprEvalContexts.size() - 2]
  15653. .isImmediateFunctionContext();
  15654. Cleanup.reset();
  15655. if (!MaybeODRUseExprs.empty())
  15656. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  15657. }
  15658. void
  15659. Sema::PushExpressionEvaluationContext(
  15660. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  15661. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  15662. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  15663. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  15664. }
  15665. namespace {
  15666. const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
  15667. PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
  15668. if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
  15669. if (E->getOpcode() == UO_Deref)
  15670. return CheckPossibleDeref(S, E->getSubExpr());
  15671. } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
  15672. return CheckPossibleDeref(S, E->getBase());
  15673. } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
  15674. return CheckPossibleDeref(S, E->getBase());
  15675. } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
  15676. QualType Inner;
  15677. QualType Ty = E->getType();
  15678. if (const auto *Ptr = Ty->getAs<PointerType>())
  15679. Inner = Ptr->getPointeeType();
  15680. else if (const auto *Arr = S.Context.getAsArrayType(Ty))
  15681. Inner = Arr->getElementType();
  15682. else
  15683. return nullptr;
  15684. if (Inner->hasAttr(attr::NoDeref))
  15685. return E;
  15686. }
  15687. return nullptr;
  15688. }
  15689. } // namespace
  15690. void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
  15691. for (const Expr *E : Rec.PossibleDerefs) {
  15692. const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
  15693. if (DeclRef) {
  15694. const ValueDecl *Decl = DeclRef->getDecl();
  15695. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
  15696. << Decl->getName() << E->getSourceRange();
  15697. Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
  15698. } else {
  15699. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
  15700. << E->getSourceRange();
  15701. }
  15702. }
  15703. Rec.PossibleDerefs.clear();
  15704. }
  15705. /// Check whether E, which is either a discarded-value expression or an
  15706. /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
  15707. /// and if so, remove it from the list of volatile-qualified assignments that
  15708. /// we are going to warn are deprecated.
  15709. void Sema::CheckUnusedVolatileAssignment(Expr *E) {
  15710. if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
  15711. return;
  15712. // Note: ignoring parens here is not justified by the standard rules, but
  15713. // ignoring parentheses seems like a more reasonable approach, and this only
  15714. // drives a deprecation warning so doesn't affect conformance.
  15715. if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
  15716. if (BO->getOpcode() == BO_Assign) {
  15717. auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
  15718. llvm::erase_value(LHSs, BO->getLHS());
  15719. }
  15720. }
  15721. }
  15722. ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
  15723. if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
  15724. !Decl->isConsteval() || isConstantEvaluated() ||
  15725. isCheckingDefaultArgumentOrInitializer() ||
  15726. RebuildingImmediateInvocation || isImmediateFunctionContext())
  15727. return E;
  15728. /// Opportunistically remove the callee from ReferencesToConsteval if we can.
  15729. /// It's OK if this fails; we'll also remove this in
  15730. /// HandleImmediateInvocations, but catching it here allows us to avoid
  15731. /// walking the AST looking for it in simple cases.
  15732. if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
  15733. if (auto *DeclRef =
  15734. dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
  15735. ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
  15736. E = MaybeCreateExprWithCleanups(E);
  15737. ConstantExpr *Res = ConstantExpr::Create(
  15738. getASTContext(), E.get(),
  15739. ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
  15740. getASTContext()),
  15741. /*IsImmediateInvocation*/ true);
  15742. /// Value-dependent constant expressions should not be immediately
  15743. /// evaluated until they are instantiated.
  15744. if (!Res->isValueDependent())
  15745. ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
  15746. return Res;
  15747. }
  15748. static void EvaluateAndDiagnoseImmediateInvocation(
  15749. Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
  15750. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  15751. Expr::EvalResult Eval;
  15752. Eval.Diag = &Notes;
  15753. ConstantExpr *CE = Candidate.getPointer();
  15754. bool Result = CE->EvaluateAsConstantExpr(
  15755. Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
  15756. if (!Result || !Notes.empty()) {
  15757. Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
  15758. if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
  15759. InnerExpr = FunctionalCast->getSubExpr();
  15760. FunctionDecl *FD = nullptr;
  15761. if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
  15762. FD = cast<FunctionDecl>(Call->getCalleeDecl());
  15763. else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
  15764. FD = Call->getConstructor();
  15765. else
  15766. llvm_unreachable("unhandled decl kind");
  15767. assert(FD && FD->isConsteval());
  15768. SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
  15769. if (auto Context =
  15770. SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
  15771. SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
  15772. << Context->Decl;
  15773. SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
  15774. }
  15775. for (auto &Note : Notes)
  15776. SemaRef.Diag(Note.first, Note.second);
  15777. return;
  15778. }
  15779. CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
  15780. }
  15781. static void RemoveNestedImmediateInvocation(
  15782. Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
  15783. SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
  15784. struct ComplexRemove : TreeTransform<ComplexRemove> {
  15785. using Base = TreeTransform<ComplexRemove>;
  15786. llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
  15787. SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
  15788. SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
  15789. CurrentII;
  15790. ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
  15791. SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
  15792. SmallVector<Sema::ImmediateInvocationCandidate,
  15793. 4>::reverse_iterator Current)
  15794. : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
  15795. void RemoveImmediateInvocation(ConstantExpr* E) {
  15796. auto It = std::find_if(CurrentII, IISet.rend(),
  15797. [E](Sema::ImmediateInvocationCandidate Elem) {
  15798. return Elem.getPointer() == E;
  15799. });
  15800. assert(It != IISet.rend() &&
  15801. "ConstantExpr marked IsImmediateInvocation should "
  15802. "be present");
  15803. It->setInt(1); // Mark as deleted
  15804. }
  15805. ExprResult TransformConstantExpr(ConstantExpr *E) {
  15806. if (!E->isImmediateInvocation())
  15807. return Base::TransformConstantExpr(E);
  15808. RemoveImmediateInvocation(E);
  15809. return Base::TransformExpr(E->getSubExpr());
  15810. }
  15811. /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
  15812. /// we need to remove its DeclRefExpr from the DRSet.
  15813. ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  15814. DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
  15815. return Base::TransformCXXOperatorCallExpr(E);
  15816. }
  15817. /// Base::TransformInitializer skip ConstantExpr so we need to visit them
  15818. /// here.
  15819. ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
  15820. if (!Init)
  15821. return Init;
  15822. /// ConstantExpr are the first layer of implicit node to be removed so if
  15823. /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
  15824. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  15825. if (CE->isImmediateInvocation())
  15826. RemoveImmediateInvocation(CE);
  15827. return Base::TransformInitializer(Init, NotCopyInit);
  15828. }
  15829. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  15830. DRSet.erase(E);
  15831. return E;
  15832. }
  15833. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  15834. // Do not rebuild lambdas to avoid creating a new type.
  15835. // Lambdas have already been processed inside their eval context.
  15836. return E;
  15837. }
  15838. bool AlwaysRebuild() { return false; }
  15839. bool ReplacingOriginal() { return true; }
  15840. bool AllowSkippingCXXConstructExpr() {
  15841. bool Res = AllowSkippingFirstCXXConstructExpr;
  15842. AllowSkippingFirstCXXConstructExpr = true;
  15843. return Res;
  15844. }
  15845. bool AllowSkippingFirstCXXConstructExpr = true;
  15846. } Transformer(SemaRef, Rec.ReferenceToConsteval,
  15847. Rec.ImmediateInvocationCandidates, It);
  15848. /// CXXConstructExpr with a single argument are getting skipped by
  15849. /// TreeTransform in some situtation because they could be implicit. This
  15850. /// can only occur for the top-level CXXConstructExpr because it is used
  15851. /// nowhere in the expression being transformed therefore will not be rebuilt.
  15852. /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
  15853. /// skipping the first CXXConstructExpr.
  15854. if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
  15855. Transformer.AllowSkippingFirstCXXConstructExpr = false;
  15856. ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
  15857. // The result may not be usable in case of previous compilation errors.
  15858. // In this case evaluation of the expression may result in crash so just
  15859. // don't do anything further with the result.
  15860. if (Res.isUsable()) {
  15861. Res = SemaRef.MaybeCreateExprWithCleanups(Res);
  15862. It->getPointer()->setSubExpr(Res.get());
  15863. }
  15864. }
  15865. static void
  15866. HandleImmediateInvocations(Sema &SemaRef,
  15867. Sema::ExpressionEvaluationContextRecord &Rec) {
  15868. if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
  15869. Rec.ReferenceToConsteval.size() == 0) ||
  15870. SemaRef.RebuildingImmediateInvocation)
  15871. return;
  15872. /// When we have more then 1 ImmediateInvocationCandidates we need to check
  15873. /// for nested ImmediateInvocationCandidates. when we have only 1 we only
  15874. /// need to remove ReferenceToConsteval in the immediate invocation.
  15875. if (Rec.ImmediateInvocationCandidates.size() > 1) {
  15876. /// Prevent sema calls during the tree transform from adding pointers that
  15877. /// are already in the sets.
  15878. llvm::SaveAndRestore DisableIITracking(
  15879. SemaRef.RebuildingImmediateInvocation, true);
  15880. /// Prevent diagnostic during tree transfrom as they are duplicates
  15881. Sema::TentativeAnalysisScope DisableDiag(SemaRef);
  15882. for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
  15883. It != Rec.ImmediateInvocationCandidates.rend(); It++)
  15884. if (!It->getInt())
  15885. RemoveNestedImmediateInvocation(SemaRef, Rec, It);
  15886. } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
  15887. Rec.ReferenceToConsteval.size()) {
  15888. struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
  15889. llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
  15890. SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
  15891. bool VisitDeclRefExpr(DeclRefExpr *E) {
  15892. DRSet.erase(E);
  15893. return DRSet.size();
  15894. }
  15895. } Visitor(Rec.ReferenceToConsteval);
  15896. Visitor.TraverseStmt(
  15897. Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
  15898. }
  15899. for (auto CE : Rec.ImmediateInvocationCandidates)
  15900. if (!CE.getInt())
  15901. EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
  15902. for (auto *DR : Rec.ReferenceToConsteval) {
  15903. auto *FD = cast<FunctionDecl>(DR->getDecl());
  15904. SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
  15905. << FD;
  15906. SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
  15907. }
  15908. }
  15909. void Sema::PopExpressionEvaluationContext() {
  15910. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  15911. unsigned NumTypos = Rec.NumTypos;
  15912. if (!Rec.Lambdas.empty()) {
  15913. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  15914. if (!getLangOpts().CPlusPlus20 &&
  15915. (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
  15916. Rec.isUnevaluated() ||
  15917. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
  15918. unsigned D;
  15919. if (Rec.isUnevaluated()) {
  15920. // C++11 [expr.prim.lambda]p2:
  15921. // A lambda-expression shall not appear in an unevaluated operand
  15922. // (Clause 5).
  15923. D = diag::err_lambda_unevaluated_operand;
  15924. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  15925. // C++1y [expr.const]p2:
  15926. // A conditional-expression e is a core constant expression unless the
  15927. // evaluation of e, following the rules of the abstract machine, would
  15928. // evaluate [...] a lambda-expression.
  15929. D = diag::err_lambda_in_constant_expression;
  15930. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  15931. // C++17 [expr.prim.lamda]p2:
  15932. // A lambda-expression shall not appear [...] in a template-argument.
  15933. D = diag::err_lambda_in_invalid_context;
  15934. } else
  15935. llvm_unreachable("Couldn't infer lambda error message.");
  15936. for (const auto *L : Rec.Lambdas)
  15937. Diag(L->getBeginLoc(), D);
  15938. }
  15939. }
  15940. WarnOnPendingNoDerefs(Rec);
  15941. HandleImmediateInvocations(*this, Rec);
  15942. // Warn on any volatile-qualified simple-assignments that are not discarded-
  15943. // value expressions nor unevaluated operands (those cases get removed from
  15944. // this list by CheckUnusedVolatileAssignment).
  15945. for (auto *BO : Rec.VolatileAssignmentLHSs)
  15946. Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
  15947. << BO->getType();
  15948. // When are coming out of an unevaluated context, clear out any
  15949. // temporaries that we may have created as part of the evaluation of
  15950. // the expression in that context: they aren't relevant because they
  15951. // will never be constructed.
  15952. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  15953. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  15954. ExprCleanupObjects.end());
  15955. Cleanup = Rec.ParentCleanup;
  15956. CleanupVarDeclMarking();
  15957. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  15958. // Otherwise, merge the contexts together.
  15959. } else {
  15960. Cleanup.mergeFrom(Rec.ParentCleanup);
  15961. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  15962. Rec.SavedMaybeODRUseExprs.end());
  15963. }
  15964. // Pop the current expression evaluation context off the stack.
  15965. ExprEvalContexts.pop_back();
  15966. // The global expression evaluation context record is never popped.
  15967. ExprEvalContexts.back().NumTypos += NumTypos;
  15968. }
  15969. void Sema::DiscardCleanupsInEvaluationContext() {
  15970. ExprCleanupObjects.erase(
  15971. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  15972. ExprCleanupObjects.end());
  15973. Cleanup.reset();
  15974. MaybeODRUseExprs.clear();
  15975. }
  15976. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  15977. ExprResult Result = CheckPlaceholderExpr(E);
  15978. if (Result.isInvalid())
  15979. return ExprError();
  15980. E = Result.get();
  15981. if (!E->getType()->isVariablyModifiedType())
  15982. return E;
  15983. return TransformToPotentiallyEvaluated(E);
  15984. }
  15985. /// Are we in a context that is potentially constant evaluated per C++20
  15986. /// [expr.const]p12?
  15987. static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
  15988. /// C++2a [expr.const]p12:
  15989. // An expression or conversion is potentially constant evaluated if it is
  15990. switch (SemaRef.ExprEvalContexts.back().Context) {
  15991. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  15992. case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
  15993. // -- a manifestly constant-evaluated expression,
  15994. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  15995. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  15996. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  15997. // -- a potentially-evaluated expression,
  15998. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  15999. // -- an immediate subexpression of a braced-init-list,
  16000. // -- [FIXME] an expression of the form & cast-expression that occurs
  16001. // within a templated entity
  16002. // -- a subexpression of one of the above that is not a subexpression of
  16003. // a nested unevaluated operand.
  16004. return true;
  16005. case Sema::ExpressionEvaluationContext::Unevaluated:
  16006. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  16007. // Expressions in this context are never evaluated.
  16008. return false;
  16009. }
  16010. llvm_unreachable("Invalid context");
  16011. }
  16012. /// Return true if this function has a calling convention that requires mangling
  16013. /// in the size of the parameter pack.
  16014. static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
  16015. // These manglings don't do anything on non-Windows or non-x86 platforms, so
  16016. // we don't need parameter type sizes.
  16017. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  16018. if (!TT.isOSWindows() || !TT.isX86())
  16019. return false;
  16020. // If this is C++ and this isn't an extern "C" function, parameters do not
  16021. // need to be complete. In this case, C++ mangling will apply, which doesn't
  16022. // use the size of the parameters.
  16023. if (S.getLangOpts().CPlusPlus && !FD->isExternC())
  16024. return false;
  16025. // Stdcall, fastcall, and vectorcall need this special treatment.
  16026. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  16027. switch (CC) {
  16028. case CC_X86StdCall:
  16029. case CC_X86FastCall:
  16030. case CC_X86VectorCall:
  16031. return true;
  16032. default:
  16033. break;
  16034. }
  16035. return false;
  16036. }
  16037. /// Require that all of the parameter types of function be complete. Normally,
  16038. /// parameter types are only required to be complete when a function is called
  16039. /// or defined, but to mangle functions with certain calling conventions, the
  16040. /// mangler needs to know the size of the parameter list. In this situation,
  16041. /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
  16042. /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
  16043. /// result in a linker error. Clang doesn't implement this behavior, and instead
  16044. /// attempts to error at compile time.
  16045. static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
  16046. SourceLocation Loc) {
  16047. class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
  16048. FunctionDecl *FD;
  16049. ParmVarDecl *Param;
  16050. public:
  16051. ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
  16052. : FD(FD), Param(Param) {}
  16053. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  16054. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  16055. StringRef CCName;
  16056. switch (CC) {
  16057. case CC_X86StdCall:
  16058. CCName = "stdcall";
  16059. break;
  16060. case CC_X86FastCall:
  16061. CCName = "fastcall";
  16062. break;
  16063. case CC_X86VectorCall:
  16064. CCName = "vectorcall";
  16065. break;
  16066. default:
  16067. llvm_unreachable("CC does not need mangling");
  16068. }
  16069. S.Diag(Loc, diag::err_cconv_incomplete_param_type)
  16070. << Param->getDeclName() << FD->getDeclName() << CCName;
  16071. }
  16072. };
  16073. for (ParmVarDecl *Param : FD->parameters()) {
  16074. ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
  16075. S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
  16076. }
  16077. }
  16078. namespace {
  16079. enum class OdrUseContext {
  16080. /// Declarations in this context are not odr-used.
  16081. None,
  16082. /// Declarations in this context are formally odr-used, but this is a
  16083. /// dependent context.
  16084. Dependent,
  16085. /// Declarations in this context are odr-used but not actually used (yet).
  16086. FormallyOdrUsed,
  16087. /// Declarations in this context are used.
  16088. Used
  16089. };
  16090. }
  16091. /// Are we within a context in which references to resolved functions or to
  16092. /// variables result in odr-use?
  16093. static OdrUseContext isOdrUseContext(Sema &SemaRef) {
  16094. OdrUseContext Result;
  16095. switch (SemaRef.ExprEvalContexts.back().Context) {
  16096. case Sema::ExpressionEvaluationContext::Unevaluated:
  16097. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  16098. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  16099. return OdrUseContext::None;
  16100. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  16101. case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
  16102. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  16103. Result = OdrUseContext::Used;
  16104. break;
  16105. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  16106. Result = OdrUseContext::FormallyOdrUsed;
  16107. break;
  16108. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  16109. // A default argument formally results in odr-use, but doesn't actually
  16110. // result in a use in any real sense until it itself is used.
  16111. Result = OdrUseContext::FormallyOdrUsed;
  16112. break;
  16113. }
  16114. if (SemaRef.CurContext->isDependentContext())
  16115. return OdrUseContext::Dependent;
  16116. return Result;
  16117. }
  16118. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  16119. if (!Func->isConstexpr())
  16120. return false;
  16121. if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
  16122. return true;
  16123. auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
  16124. return CCD && CCD->getInheritedConstructor();
  16125. }
  16126. /// Mark a function referenced, and check whether it is odr-used
  16127. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  16128. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  16129. bool MightBeOdrUse) {
  16130. assert(Func && "No function?");
  16131. Func->setReferenced();
  16132. // Recursive functions aren't really used until they're used from some other
  16133. // context.
  16134. bool IsRecursiveCall = CurContext == Func;
  16135. // C++11 [basic.def.odr]p3:
  16136. // A function whose name appears as a potentially-evaluated expression is
  16137. // odr-used if it is the unique lookup result or the selected member of a
  16138. // set of overloaded functions [...].
  16139. //
  16140. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  16141. // can just check that here.
  16142. OdrUseContext OdrUse =
  16143. MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
  16144. if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
  16145. OdrUse = OdrUseContext::FormallyOdrUsed;
  16146. // Trivial default constructors and destructors are never actually used.
  16147. // FIXME: What about other special members?
  16148. if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
  16149. OdrUse == OdrUseContext::Used) {
  16150. if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
  16151. if (Constructor->isDefaultConstructor())
  16152. OdrUse = OdrUseContext::FormallyOdrUsed;
  16153. if (isa<CXXDestructorDecl>(Func))
  16154. OdrUse = OdrUseContext::FormallyOdrUsed;
  16155. }
  16156. // C++20 [expr.const]p12:
  16157. // A function [...] is needed for constant evaluation if it is [...] a
  16158. // constexpr function that is named by an expression that is potentially
  16159. // constant evaluated
  16160. bool NeededForConstantEvaluation =
  16161. isPotentiallyConstantEvaluatedContext(*this) &&
  16162. isImplicitlyDefinableConstexprFunction(Func);
  16163. // Determine whether we require a function definition to exist, per
  16164. // C++11 [temp.inst]p3:
  16165. // Unless a function template specialization has been explicitly
  16166. // instantiated or explicitly specialized, the function template
  16167. // specialization is implicitly instantiated when the specialization is
  16168. // referenced in a context that requires a function definition to exist.
  16169. // C++20 [temp.inst]p7:
  16170. // The existence of a definition of a [...] function is considered to
  16171. // affect the semantics of the program if the [...] function is needed for
  16172. // constant evaluation by an expression
  16173. // C++20 [basic.def.odr]p10:
  16174. // Every program shall contain exactly one definition of every non-inline
  16175. // function or variable that is odr-used in that program outside of a
  16176. // discarded statement
  16177. // C++20 [special]p1:
  16178. // The implementation will implicitly define [defaulted special members]
  16179. // if they are odr-used or needed for constant evaluation.
  16180. //
  16181. // Note that we skip the implicit instantiation of templates that are only
  16182. // used in unused default arguments or by recursive calls to themselves.
  16183. // This is formally non-conforming, but seems reasonable in practice.
  16184. bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
  16185. NeededForConstantEvaluation);
  16186. // C++14 [temp.expl.spec]p6:
  16187. // If a template [...] is explicitly specialized then that specialization
  16188. // shall be declared before the first use of that specialization that would
  16189. // cause an implicit instantiation to take place, in every translation unit
  16190. // in which such a use occurs
  16191. if (NeedDefinition &&
  16192. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  16193. Func->getMemberSpecializationInfo()))
  16194. checkSpecializationReachability(Loc, Func);
  16195. if (getLangOpts().CUDA)
  16196. CheckCUDACall(Loc, Func);
  16197. if (getLangOpts().SYCLIsDevice)
  16198. checkSYCLDeviceFunction(Loc, Func);
  16199. // If we need a definition, try to create one.
  16200. if (NeedDefinition && !Func->getBody()) {
  16201. runWithSufficientStackSpace(Loc, [&] {
  16202. if (CXXConstructorDecl *Constructor =
  16203. dyn_cast<CXXConstructorDecl>(Func)) {
  16204. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  16205. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  16206. if (Constructor->isDefaultConstructor()) {
  16207. if (Constructor->isTrivial() &&
  16208. !Constructor->hasAttr<DLLExportAttr>())
  16209. return;
  16210. DefineImplicitDefaultConstructor(Loc, Constructor);
  16211. } else if (Constructor->isCopyConstructor()) {
  16212. DefineImplicitCopyConstructor(Loc, Constructor);
  16213. } else if (Constructor->isMoveConstructor()) {
  16214. DefineImplicitMoveConstructor(Loc, Constructor);
  16215. }
  16216. } else if (Constructor->getInheritedConstructor()) {
  16217. DefineInheritingConstructor(Loc, Constructor);
  16218. }
  16219. } else if (CXXDestructorDecl *Destructor =
  16220. dyn_cast<CXXDestructorDecl>(Func)) {
  16221. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  16222. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  16223. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  16224. return;
  16225. DefineImplicitDestructor(Loc, Destructor);
  16226. }
  16227. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  16228. MarkVTableUsed(Loc, Destructor->getParent());
  16229. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  16230. if (MethodDecl->isOverloadedOperator() &&
  16231. MethodDecl->getOverloadedOperator() == OO_Equal) {
  16232. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  16233. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  16234. if (MethodDecl->isCopyAssignmentOperator())
  16235. DefineImplicitCopyAssignment(Loc, MethodDecl);
  16236. else if (MethodDecl->isMoveAssignmentOperator())
  16237. DefineImplicitMoveAssignment(Loc, MethodDecl);
  16238. }
  16239. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  16240. MethodDecl->getParent()->isLambda()) {
  16241. CXXConversionDecl *Conversion =
  16242. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  16243. if (Conversion->isLambdaToBlockPointerConversion())
  16244. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  16245. else
  16246. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  16247. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  16248. MarkVTableUsed(Loc, MethodDecl->getParent());
  16249. }
  16250. if (Func->isDefaulted() && !Func->isDeleted()) {
  16251. DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
  16252. if (DCK != DefaultedComparisonKind::None)
  16253. DefineDefaultedComparison(Loc, Func, DCK);
  16254. }
  16255. // Implicit instantiation of function templates and member functions of
  16256. // class templates.
  16257. if (Func->isImplicitlyInstantiable()) {
  16258. TemplateSpecializationKind TSK =
  16259. Func->getTemplateSpecializationKindForInstantiation();
  16260. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  16261. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  16262. if (FirstInstantiation) {
  16263. PointOfInstantiation = Loc;
  16264. if (auto *MSI = Func->getMemberSpecializationInfo())
  16265. MSI->setPointOfInstantiation(Loc);
  16266. // FIXME: Notify listener.
  16267. else
  16268. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  16269. } else if (TSK != TSK_ImplicitInstantiation) {
  16270. // Use the point of use as the point of instantiation, instead of the
  16271. // point of explicit instantiation (which we track as the actual point
  16272. // of instantiation). This gives better backtraces in diagnostics.
  16273. PointOfInstantiation = Loc;
  16274. }
  16275. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  16276. Func->isConstexpr()) {
  16277. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  16278. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  16279. CodeSynthesisContexts.size())
  16280. PendingLocalImplicitInstantiations.push_back(
  16281. std::make_pair(Func, PointOfInstantiation));
  16282. else if (Func->isConstexpr())
  16283. // Do not defer instantiations of constexpr functions, to avoid the
  16284. // expression evaluator needing to call back into Sema if it sees a
  16285. // call to such a function.
  16286. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  16287. else {
  16288. Func->setInstantiationIsPending(true);
  16289. PendingInstantiations.push_back(
  16290. std::make_pair(Func, PointOfInstantiation));
  16291. // Notify the consumer that a function was implicitly instantiated.
  16292. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  16293. }
  16294. }
  16295. } else {
  16296. // Walk redefinitions, as some of them may be instantiable.
  16297. for (auto *i : Func->redecls()) {
  16298. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  16299. MarkFunctionReferenced(Loc, i, MightBeOdrUse);
  16300. }
  16301. }
  16302. });
  16303. }
  16304. // If a constructor was defined in the context of a default parameter
  16305. // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
  16306. // context), its initializers may not be referenced yet.
  16307. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  16308. for (CXXCtorInitializer *Init : Constructor->inits()) {
  16309. if (Init->isInClassMemberInitializer())
  16310. MarkDeclarationsReferencedInExpr(Init->getInit());
  16311. }
  16312. }
  16313. // C++14 [except.spec]p17:
  16314. // An exception-specification is considered to be needed when:
  16315. // - the function is odr-used or, if it appears in an unevaluated operand,
  16316. // would be odr-used if the expression were potentially-evaluated;
  16317. //
  16318. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  16319. // function is a pure virtual function we're calling, and in that case the
  16320. // function was selected by overload resolution and we need to resolve its
  16321. // exception specification for a different reason.
  16322. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  16323. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  16324. ResolveExceptionSpec(Loc, FPT);
  16325. // If this is the first "real" use, act on that.
  16326. if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
  16327. // Keep track of used but undefined functions.
  16328. if (!Func->isDefined()) {
  16329. if (mightHaveNonExternalLinkage(Func))
  16330. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  16331. else if (Func->getMostRecentDecl()->isInlined() &&
  16332. !LangOpts.GNUInline &&
  16333. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  16334. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  16335. else if (isExternalWithNoLinkageType(Func))
  16336. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  16337. }
  16338. // Some x86 Windows calling conventions mangle the size of the parameter
  16339. // pack into the name. Computing the size of the parameters requires the
  16340. // parameter types to be complete. Check that now.
  16341. if (funcHasParameterSizeMangling(*this, Func))
  16342. CheckCompleteParameterTypesForMangler(*this, Func, Loc);
  16343. // In the MS C++ ABI, the compiler emits destructor variants where they are
  16344. // used. If the destructor is used here but defined elsewhere, mark the
  16345. // virtual base destructors referenced. If those virtual base destructors
  16346. // are inline, this will ensure they are defined when emitting the complete
  16347. // destructor variant. This checking may be redundant if the destructor is
  16348. // provided later in this TU.
  16349. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  16350. if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
  16351. CXXRecordDecl *Parent = Dtor->getParent();
  16352. if (Parent->getNumVBases() > 0 && !Dtor->getBody())
  16353. CheckCompleteDestructorVariant(Loc, Dtor);
  16354. }
  16355. }
  16356. Func->markUsed(Context);
  16357. }
  16358. }
  16359. /// Directly mark a variable odr-used. Given a choice, prefer to use
  16360. /// MarkVariableReferenced since it does additional checks and then
  16361. /// calls MarkVarDeclODRUsed.
  16362. /// If the variable must be captured:
  16363. /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
  16364. /// - else capture it in the DeclContext that maps to the
  16365. /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
  16366. static void
  16367. MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
  16368. const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
  16369. // Keep track of used but undefined variables.
  16370. // FIXME: We shouldn't suppress this warning for static data members.
  16371. VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
  16372. assert(Var && "expected a capturable variable");
  16373. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  16374. (!Var->isExternallyVisible() || Var->isInline() ||
  16375. SemaRef.isExternalWithNoLinkageType(Var)) &&
  16376. !(Var->isStaticDataMember() && Var->hasInit())) {
  16377. SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
  16378. if (old.isInvalid())
  16379. old = Loc;
  16380. }
  16381. QualType CaptureType, DeclRefType;
  16382. if (SemaRef.LangOpts.OpenMP)
  16383. SemaRef.tryCaptureOpenMPLambdas(V);
  16384. SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
  16385. /*EllipsisLoc*/ SourceLocation(),
  16386. /*BuildAndDiagnose*/ true, CaptureType,
  16387. DeclRefType, FunctionScopeIndexToStopAt);
  16388. if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
  16389. auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
  16390. auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
  16391. auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
  16392. if (VarTarget == Sema::CVT_Host &&
  16393. (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
  16394. UserTarget == Sema::CFT_Global)) {
  16395. // Diagnose ODR-use of host global variables in device functions.
  16396. // Reference of device global variables in host functions is allowed
  16397. // through shadow variables therefore it is not diagnosed.
  16398. if (SemaRef.LangOpts.CUDAIsDevice) {
  16399. SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
  16400. << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
  16401. SemaRef.targetDiag(Var->getLocation(),
  16402. Var->getType().isConstQualified()
  16403. ? diag::note_cuda_const_var_unpromoted
  16404. : diag::note_cuda_host_var);
  16405. }
  16406. } else if (VarTarget == Sema::CVT_Device &&
  16407. (UserTarget == Sema::CFT_Host ||
  16408. UserTarget == Sema::CFT_HostDevice)) {
  16409. // Record a CUDA/HIP device side variable if it is ODR-used
  16410. // by host code. This is done conservatively, when the variable is
  16411. // referenced in any of the following contexts:
  16412. // - a non-function context
  16413. // - a host function
  16414. // - a host device function
  16415. // This makes the ODR-use of the device side variable by host code to
  16416. // be visible in the device compilation for the compiler to be able to
  16417. // emit template variables instantiated by host code only and to
  16418. // externalize the static device side variable ODR-used by host code.
  16419. if (!Var->hasExternalStorage())
  16420. SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
  16421. else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
  16422. SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
  16423. }
  16424. }
  16425. V->markUsed(SemaRef.Context);
  16426. }
  16427. void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
  16428. SourceLocation Loc,
  16429. unsigned CapturingScopeIndex) {
  16430. MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
  16431. }
  16432. void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
  16433. ValueDecl *var) {
  16434. DeclContext *VarDC = var->getDeclContext();
  16435. // If the parameter still belongs to the translation unit, then
  16436. // we're actually just using one parameter in the declaration of
  16437. // the next.
  16438. if (isa<ParmVarDecl>(var) &&
  16439. isa<TranslationUnitDecl>(VarDC))
  16440. return;
  16441. // For C code, don't diagnose about capture if we're not actually in code
  16442. // right now; it's impossible to write a non-constant expression outside of
  16443. // function context, so we'll get other (more useful) diagnostics later.
  16444. //
  16445. // For C++, things get a bit more nasty... it would be nice to suppress this
  16446. // diagnostic for certain cases like using a local variable in an array bound
  16447. // for a member of a local class, but the correct predicate is not obvious.
  16448. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  16449. return;
  16450. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  16451. unsigned ContextKind = 3; // unknown
  16452. if (isa<CXXMethodDecl>(VarDC) &&
  16453. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  16454. ContextKind = 2;
  16455. } else if (isa<FunctionDecl>(VarDC)) {
  16456. ContextKind = 0;
  16457. } else if (isa<BlockDecl>(VarDC)) {
  16458. ContextKind = 1;
  16459. }
  16460. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  16461. << var << ValueKind << ContextKind << VarDC;
  16462. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  16463. << var;
  16464. // FIXME: Add additional diagnostic info about class etc. which prevents
  16465. // capture.
  16466. }
  16467. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
  16468. ValueDecl *Var,
  16469. bool &SubCapturesAreNested,
  16470. QualType &CaptureType,
  16471. QualType &DeclRefType) {
  16472. // Check whether we've already captured it.
  16473. if (CSI->CaptureMap.count(Var)) {
  16474. // If we found a capture, any subcaptures are nested.
  16475. SubCapturesAreNested = true;
  16476. // Retrieve the capture type for this variable.
  16477. CaptureType = CSI->getCapture(Var).getCaptureType();
  16478. // Compute the type of an expression that refers to this variable.
  16479. DeclRefType = CaptureType.getNonReferenceType();
  16480. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  16481. // are mutable in the sense that user can change their value - they are
  16482. // private instances of the captured declarations.
  16483. const Capture &Cap = CSI->getCapture(Var);
  16484. if (Cap.isCopyCapture() &&
  16485. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  16486. !(isa<CapturedRegionScopeInfo>(CSI) &&
  16487. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  16488. DeclRefType.addConst();
  16489. return true;
  16490. }
  16491. return false;
  16492. }
  16493. // Only block literals, captured statements, and lambda expressions can
  16494. // capture; other scopes don't work.
  16495. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
  16496. ValueDecl *Var,
  16497. SourceLocation Loc,
  16498. const bool Diagnose,
  16499. Sema &S) {
  16500. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  16501. return getLambdaAwareParentOfDeclContext(DC);
  16502. VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
  16503. if (Underlying) {
  16504. if (Underlying->hasLocalStorage() && Diagnose)
  16505. diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
  16506. }
  16507. return nullptr;
  16508. }
  16509. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  16510. // certain types of variables (unnamed, variably modified types etc.)
  16511. // so check for eligibility.
  16512. static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
  16513. SourceLocation Loc, const bool Diagnose,
  16514. Sema &S) {
  16515. assert((isa<VarDecl, BindingDecl>(Var)) &&
  16516. "Only variables and structured bindings can be captured");
  16517. bool IsBlock = isa<BlockScopeInfo>(CSI);
  16518. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  16519. // Lambdas are not allowed to capture unnamed variables
  16520. // (e.g. anonymous unions).
  16521. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  16522. // assuming that's the intent.
  16523. if (IsLambda && !Var->getDeclName()) {
  16524. if (Diagnose) {
  16525. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  16526. S.Diag(Var->getLocation(), diag::note_declared_at);
  16527. }
  16528. return false;
  16529. }
  16530. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  16531. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  16532. if (Diagnose) {
  16533. S.Diag(Loc, diag::err_ref_vm_type);
  16534. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  16535. }
  16536. return false;
  16537. }
  16538. // Prohibit structs with flexible array members too.
  16539. // We cannot capture what is in the tail end of the struct.
  16540. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  16541. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  16542. if (Diagnose) {
  16543. if (IsBlock)
  16544. S.Diag(Loc, diag::err_ref_flexarray_type);
  16545. else
  16546. S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
  16547. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  16548. }
  16549. return false;
  16550. }
  16551. }
  16552. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  16553. // Lambdas and captured statements are not allowed to capture __block
  16554. // variables; they don't support the expected semantics.
  16555. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  16556. if (Diagnose) {
  16557. S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
  16558. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  16559. }
  16560. return false;
  16561. }
  16562. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  16563. if (S.getLangOpts().OpenCL && IsBlock &&
  16564. Var->getType()->isBlockPointerType()) {
  16565. if (Diagnose)
  16566. S.Diag(Loc, diag::err_opencl_block_ref_block);
  16567. return false;
  16568. }
  16569. if (isa<BindingDecl>(Var)) {
  16570. if (!IsLambda || !S.getLangOpts().CPlusPlus) {
  16571. if (Diagnose)
  16572. diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
  16573. return false;
  16574. } else if (Diagnose && S.getLangOpts().CPlusPlus) {
  16575. S.Diag(Loc, S.LangOpts.CPlusPlus20
  16576. ? diag::warn_cxx17_compat_capture_binding
  16577. : diag::ext_capture_binding)
  16578. << Var;
  16579. S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
  16580. }
  16581. }
  16582. return true;
  16583. }
  16584. // Returns true if the capture by block was successful.
  16585. static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
  16586. SourceLocation Loc, const bool BuildAndDiagnose,
  16587. QualType &CaptureType, QualType &DeclRefType,
  16588. const bool Nested, Sema &S, bool Invalid) {
  16589. bool ByRef = false;
  16590. // Blocks are not allowed to capture arrays, excepting OpenCL.
  16591. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  16592. // (decayed to pointers).
  16593. if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  16594. if (BuildAndDiagnose) {
  16595. S.Diag(Loc, diag::err_ref_array_type);
  16596. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  16597. Invalid = true;
  16598. } else {
  16599. return false;
  16600. }
  16601. }
  16602. // Forbid the block-capture of autoreleasing variables.
  16603. if (!Invalid &&
  16604. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  16605. if (BuildAndDiagnose) {
  16606. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  16607. << /*block*/ 0;
  16608. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  16609. Invalid = true;
  16610. } else {
  16611. return false;
  16612. }
  16613. }
  16614. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  16615. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  16616. QualType PointeeTy = PT->getPointeeType();
  16617. if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
  16618. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  16619. !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
  16620. if (BuildAndDiagnose) {
  16621. SourceLocation VarLoc = Var->getLocation();
  16622. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  16623. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  16624. }
  16625. }
  16626. }
  16627. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  16628. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  16629. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  16630. // Block capture by reference does not change the capture or
  16631. // declaration reference types.
  16632. ByRef = true;
  16633. } else {
  16634. // Block capture by copy introduces 'const'.
  16635. CaptureType = CaptureType.getNonReferenceType().withConst();
  16636. DeclRefType = CaptureType;
  16637. }
  16638. // Actually capture the variable.
  16639. if (BuildAndDiagnose)
  16640. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
  16641. CaptureType, Invalid);
  16642. return !Invalid;
  16643. }
  16644. /// Capture the given variable in the captured region.
  16645. static bool captureInCapturedRegion(
  16646. CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
  16647. const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
  16648. const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
  16649. bool IsTopScope, Sema &S, bool Invalid) {
  16650. // By default, capture variables by reference.
  16651. bool ByRef = true;
  16652. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  16653. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  16654. } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  16655. // Using an LValue reference type is consistent with Lambdas (see below).
  16656. if (S.isOpenMPCapturedDecl(Var)) {
  16657. bool HasConst = DeclRefType.isConstQualified();
  16658. DeclRefType = DeclRefType.getUnqualifiedType();
  16659. // Don't lose diagnostics about assignments to const.
  16660. if (HasConst)
  16661. DeclRefType.addConst();
  16662. }
  16663. // Do not capture firstprivates in tasks.
  16664. if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
  16665. OMPC_unknown)
  16666. return true;
  16667. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
  16668. RSI->OpenMPCaptureLevel);
  16669. }
  16670. if (ByRef)
  16671. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  16672. else
  16673. CaptureType = DeclRefType;
  16674. // Actually capture the variable.
  16675. if (BuildAndDiagnose)
  16676. RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
  16677. Loc, SourceLocation(), CaptureType, Invalid);
  16678. return !Invalid;
  16679. }
  16680. /// Capture the given variable in the lambda.
  16681. static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
  16682. SourceLocation Loc, const bool BuildAndDiagnose,
  16683. QualType &CaptureType, QualType &DeclRefType,
  16684. const bool RefersToCapturedVariable,
  16685. const Sema::TryCaptureKind Kind,
  16686. SourceLocation EllipsisLoc, const bool IsTopScope,
  16687. Sema &S, bool Invalid) {
  16688. // Determine whether we are capturing by reference or by value.
  16689. bool ByRef = false;
  16690. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  16691. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  16692. } else {
  16693. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  16694. }
  16695. BindingDecl *BD = dyn_cast<BindingDecl>(Var);
  16696. // FIXME: We should support capturing structured bindings in OpenMP.
  16697. if (!Invalid && BD && S.LangOpts.OpenMP) {
  16698. if (BuildAndDiagnose) {
  16699. S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
  16700. S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
  16701. }
  16702. Invalid = true;
  16703. }
  16704. // Compute the type of the field that will capture this variable.
  16705. if (ByRef) {
  16706. // C++11 [expr.prim.lambda]p15:
  16707. // An entity is captured by reference if it is implicitly or
  16708. // explicitly captured but not captured by copy. It is
  16709. // unspecified whether additional unnamed non-static data
  16710. // members are declared in the closure type for entities
  16711. // captured by reference.
  16712. //
  16713. // FIXME: It is not clear whether we want to build an lvalue reference
  16714. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  16715. // to do the former, while EDG does the latter. Core issue 1249 will
  16716. // clarify, but for now we follow GCC because it's a more permissive and
  16717. // easily defensible position.
  16718. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  16719. } else {
  16720. // C++11 [expr.prim.lambda]p14:
  16721. // For each entity captured by copy, an unnamed non-static
  16722. // data member is declared in the closure type. The
  16723. // declaration order of these members is unspecified. The type
  16724. // of such a data member is the type of the corresponding
  16725. // captured entity if the entity is not a reference to an
  16726. // object, or the referenced type otherwise. [Note: If the
  16727. // captured entity is a reference to a function, the
  16728. // corresponding data member is also a reference to a
  16729. // function. - end note ]
  16730. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  16731. if (!RefType->getPointeeType()->isFunctionType())
  16732. CaptureType = RefType->getPointeeType();
  16733. }
  16734. // Forbid the lambda copy-capture of autoreleasing variables.
  16735. if (!Invalid &&
  16736. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  16737. if (BuildAndDiagnose) {
  16738. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  16739. S.Diag(Var->getLocation(), diag::note_previous_decl)
  16740. << Var->getDeclName();
  16741. Invalid = true;
  16742. } else {
  16743. return false;
  16744. }
  16745. }
  16746. // Make sure that by-copy captures are of a complete and non-abstract type.
  16747. if (!Invalid && BuildAndDiagnose) {
  16748. if (!CaptureType->isDependentType() &&
  16749. S.RequireCompleteSizedType(
  16750. Loc, CaptureType,
  16751. diag::err_capture_of_incomplete_or_sizeless_type,
  16752. Var->getDeclName()))
  16753. Invalid = true;
  16754. else if (S.RequireNonAbstractType(Loc, CaptureType,
  16755. diag::err_capture_of_abstract_type))
  16756. Invalid = true;
  16757. }
  16758. }
  16759. // Compute the type of a reference to this captured variable.
  16760. if (ByRef)
  16761. DeclRefType = CaptureType.getNonReferenceType();
  16762. else {
  16763. // C++ [expr.prim.lambda]p5:
  16764. // The closure type for a lambda-expression has a public inline
  16765. // function call operator [...]. This function call operator is
  16766. // declared const (9.3.1) if and only if the lambda-expression's
  16767. // parameter-declaration-clause is not followed by mutable.
  16768. DeclRefType = CaptureType.getNonReferenceType();
  16769. if (!LSI->Mutable && !CaptureType->isReferenceType())
  16770. DeclRefType.addConst();
  16771. }
  16772. // Add the capture.
  16773. if (BuildAndDiagnose)
  16774. LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
  16775. Loc, EllipsisLoc, CaptureType, Invalid);
  16776. return !Invalid;
  16777. }
  16778. static bool canCaptureVariableByCopy(ValueDecl *Var,
  16779. const ASTContext &Context) {
  16780. // Offer a Copy fix even if the type is dependent.
  16781. if (Var->getType()->isDependentType())
  16782. return true;
  16783. QualType T = Var->getType().getNonReferenceType();
  16784. if (T.isTriviallyCopyableType(Context))
  16785. return true;
  16786. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  16787. if (!(RD = RD->getDefinition()))
  16788. return false;
  16789. if (RD->hasSimpleCopyConstructor())
  16790. return true;
  16791. if (RD->hasUserDeclaredCopyConstructor())
  16792. for (CXXConstructorDecl *Ctor : RD->ctors())
  16793. if (Ctor->isCopyConstructor())
  16794. return !Ctor->isDeleted();
  16795. }
  16796. return false;
  16797. }
  16798. /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
  16799. /// default capture. Fixes may be omitted if they aren't allowed by the
  16800. /// standard, for example we can't emit a default copy capture fix-it if we
  16801. /// already explicitly copy capture capture another variable.
  16802. static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
  16803. ValueDecl *Var) {
  16804. assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
  16805. // Don't offer Capture by copy of default capture by copy fixes if Var is
  16806. // known not to be copy constructible.
  16807. bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
  16808. SmallString<32> FixBuffer;
  16809. StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
  16810. if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
  16811. SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
  16812. if (ShouldOfferCopyFix) {
  16813. // Offer fixes to insert an explicit capture for the variable.
  16814. // [] -> [VarName]
  16815. // [OtherCapture] -> [OtherCapture, VarName]
  16816. FixBuffer.assign({Separator, Var->getName()});
  16817. Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
  16818. << Var << /*value*/ 0
  16819. << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
  16820. }
  16821. // As above but capture by reference.
  16822. FixBuffer.assign({Separator, "&", Var->getName()});
  16823. Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
  16824. << Var << /*reference*/ 1
  16825. << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
  16826. }
  16827. // Only try to offer default capture if there are no captures excluding this
  16828. // and init captures.
  16829. // [this]: OK.
  16830. // [X = Y]: OK.
  16831. // [&A, &B]: Don't offer.
  16832. // [A, B]: Don't offer.
  16833. if (llvm::any_of(LSI->Captures, [](Capture &C) {
  16834. return !C.isThisCapture() && !C.isInitCapture();
  16835. }))
  16836. return;
  16837. // The default capture specifiers, '=' or '&', must appear first in the
  16838. // capture body.
  16839. SourceLocation DefaultInsertLoc =
  16840. LSI->IntroducerRange.getBegin().getLocWithOffset(1);
  16841. if (ShouldOfferCopyFix) {
  16842. bool CanDefaultCopyCapture = true;
  16843. // [=, *this] OK since c++17
  16844. // [=, this] OK since c++20
  16845. if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
  16846. CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
  16847. ? LSI->getCXXThisCapture().isCopyCapture()
  16848. : false;
  16849. // We can't use default capture by copy if any captures already specified
  16850. // capture by copy.
  16851. if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
  16852. return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
  16853. })) {
  16854. FixBuffer.assign({"=", Separator});
  16855. Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
  16856. << /*value*/ 0
  16857. << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
  16858. }
  16859. }
  16860. // We can't use default capture by reference if any captures already specified
  16861. // capture by reference.
  16862. if (llvm::none_of(LSI->Captures, [](Capture &C) {
  16863. return !C.isInitCapture() && C.isReferenceCapture() &&
  16864. !C.isThisCapture();
  16865. })) {
  16866. FixBuffer.assign({"&", Separator});
  16867. Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
  16868. << /*reference*/ 1
  16869. << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
  16870. }
  16871. }
  16872. bool Sema::tryCaptureVariable(
  16873. ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  16874. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  16875. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  16876. // An init-capture is notionally from the context surrounding its
  16877. // declaration, but its parent DC is the lambda class.
  16878. DeclContext *VarDC = Var->getDeclContext();
  16879. const auto *VD = dyn_cast<VarDecl>(Var);
  16880. if (VD) {
  16881. if (VD->isInitCapture())
  16882. VarDC = VarDC->getParent();
  16883. } else {
  16884. VD = Var->getPotentiallyDecomposedVarDecl();
  16885. }
  16886. assert(VD && "Cannot capture a null variable");
  16887. DeclContext *DC = CurContext;
  16888. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  16889. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  16890. // We need to sync up the Declaration Context with the
  16891. // FunctionScopeIndexToStopAt
  16892. if (FunctionScopeIndexToStopAt) {
  16893. unsigned FSIndex = FunctionScopes.size() - 1;
  16894. while (FSIndex != MaxFunctionScopesIndex) {
  16895. DC = getLambdaAwareParentOfDeclContext(DC);
  16896. --FSIndex;
  16897. }
  16898. }
  16899. // If the variable is declared in the current context, there is no need to
  16900. // capture it.
  16901. if (VarDC == DC) return true;
  16902. // Capture global variables if it is required to use private copy of this
  16903. // variable.
  16904. bool IsGlobal = !VD->hasLocalStorage();
  16905. if (IsGlobal &&
  16906. !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
  16907. MaxFunctionScopesIndex)))
  16908. return true;
  16909. if (isa<VarDecl>(Var))
  16910. Var = cast<VarDecl>(Var->getCanonicalDecl());
  16911. // Walk up the stack to determine whether we can capture the variable,
  16912. // performing the "simple" checks that don't depend on type. We stop when
  16913. // we've either hit the declared scope of the variable or find an existing
  16914. // capture of that variable. We start from the innermost capturing-entity
  16915. // (the DC) and ensure that all intervening capturing-entities
  16916. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  16917. // declcontext can either capture the variable or have already captured
  16918. // the variable.
  16919. CaptureType = Var->getType();
  16920. DeclRefType = CaptureType.getNonReferenceType();
  16921. bool Nested = false;
  16922. bool Explicit = (Kind != TryCapture_Implicit);
  16923. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  16924. do {
  16925. // Only block literals, captured statements, and lambda expressions can
  16926. // capture; other scopes don't work.
  16927. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  16928. ExprLoc,
  16929. BuildAndDiagnose,
  16930. *this);
  16931. // We need to check for the parent *first* because, if we *have*
  16932. // private-captured a global variable, we need to recursively capture it in
  16933. // intermediate blocks, lambdas, etc.
  16934. if (!ParentDC) {
  16935. if (IsGlobal) {
  16936. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  16937. break;
  16938. }
  16939. return true;
  16940. }
  16941. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  16942. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  16943. // Check whether we've already captured it.
  16944. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  16945. DeclRefType)) {
  16946. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  16947. break;
  16948. }
  16949. // If we are instantiating a generic lambda call operator body,
  16950. // we do not want to capture new variables. What was captured
  16951. // during either a lambdas transformation or initial parsing
  16952. // should be used.
  16953. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  16954. if (BuildAndDiagnose) {
  16955. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  16956. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  16957. Diag(ExprLoc, diag::err_lambda_impcap) << Var;
  16958. Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  16959. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  16960. buildLambdaCaptureFixit(*this, LSI, Var);
  16961. } else
  16962. diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
  16963. }
  16964. return true;
  16965. }
  16966. // Try to capture variable-length arrays types.
  16967. if (Var->getType()->isVariablyModifiedType()) {
  16968. // We're going to walk down into the type and look for VLA
  16969. // expressions.
  16970. QualType QTy = Var->getType();
  16971. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  16972. QTy = PVD->getOriginalType();
  16973. captureVariablyModifiedType(Context, QTy, CSI);
  16974. }
  16975. if (getLangOpts().OpenMP) {
  16976. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  16977. // OpenMP private variables should not be captured in outer scope, so
  16978. // just break here. Similarly, global variables that are captured in a
  16979. // target region should not be captured outside the scope of the region.
  16980. if (RSI->CapRegionKind == CR_OpenMP) {
  16981. OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
  16982. Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
  16983. // If the variable is private (i.e. not captured) and has variably
  16984. // modified type, we still need to capture the type for correct
  16985. // codegen in all regions, associated with the construct. Currently,
  16986. // it is captured in the innermost captured region only.
  16987. if (IsOpenMPPrivateDecl != OMPC_unknown &&
  16988. Var->getType()->isVariablyModifiedType()) {
  16989. QualType QTy = Var->getType();
  16990. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  16991. QTy = PVD->getOriginalType();
  16992. for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
  16993. I < E; ++I) {
  16994. auto *OuterRSI = cast<CapturedRegionScopeInfo>(
  16995. FunctionScopes[FunctionScopesIndex - I]);
  16996. assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
  16997. "Wrong number of captured regions associated with the "
  16998. "OpenMP construct.");
  16999. captureVariablyModifiedType(Context, QTy, OuterRSI);
  17000. }
  17001. }
  17002. bool IsTargetCap =
  17003. IsOpenMPPrivateDecl != OMPC_private &&
  17004. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
  17005. RSI->OpenMPCaptureLevel);
  17006. // Do not capture global if it is not privatized in outer regions.
  17007. bool IsGlobalCap =
  17008. IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
  17009. RSI->OpenMPCaptureLevel);
  17010. // When we detect target captures we are looking from inside the
  17011. // target region, therefore we need to propagate the capture from the
  17012. // enclosing region. Therefore, the capture is not initially nested.
  17013. if (IsTargetCap)
  17014. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  17015. if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
  17016. (IsGlobal && !IsGlobalCap)) {
  17017. Nested = !IsTargetCap;
  17018. bool HasConst = DeclRefType.isConstQualified();
  17019. DeclRefType = DeclRefType.getUnqualifiedType();
  17020. // Don't lose diagnostics about assignments to const.
  17021. if (HasConst)
  17022. DeclRefType.addConst();
  17023. CaptureType = Context.getLValueReferenceType(DeclRefType);
  17024. break;
  17025. }
  17026. }
  17027. }
  17028. }
  17029. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  17030. // No capture-default, and this is not an explicit capture
  17031. // so cannot capture this variable.
  17032. if (BuildAndDiagnose) {
  17033. Diag(ExprLoc, diag::err_lambda_impcap) << Var;
  17034. Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  17035. auto *LSI = cast<LambdaScopeInfo>(CSI);
  17036. if (LSI->Lambda) {
  17037. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  17038. buildLambdaCaptureFixit(*this, LSI, Var);
  17039. }
  17040. // FIXME: If we error out because an outer lambda can not implicitly
  17041. // capture a variable that an inner lambda explicitly captures, we
  17042. // should have the inner lambda do the explicit capture - because
  17043. // it makes for cleaner diagnostics later. This would purely be done
  17044. // so that the diagnostic does not misleadingly claim that a variable
  17045. // can not be captured by a lambda implicitly even though it is captured
  17046. // explicitly. Suggestion:
  17047. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  17048. // at the function head
  17049. // - cache the StartingDeclContext - this must be a lambda
  17050. // - captureInLambda in the innermost lambda the variable.
  17051. }
  17052. return true;
  17053. }
  17054. FunctionScopesIndex--;
  17055. DC = ParentDC;
  17056. Explicit = false;
  17057. } while (!VarDC->Equals(DC));
  17058. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  17059. // computing the type of the capture at each step, checking type-specific
  17060. // requirements, and adding captures if requested.
  17061. // If the variable had already been captured previously, we start capturing
  17062. // at the lambda nested within that one.
  17063. bool Invalid = false;
  17064. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  17065. ++I) {
  17066. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  17067. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  17068. // certain types of variables (unnamed, variably modified types etc.)
  17069. // so check for eligibility.
  17070. if (!Invalid)
  17071. Invalid =
  17072. !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
  17073. // After encountering an error, if we're actually supposed to capture, keep
  17074. // capturing in nested contexts to suppress any follow-on diagnostics.
  17075. if (Invalid && !BuildAndDiagnose)
  17076. return true;
  17077. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  17078. Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  17079. DeclRefType, Nested, *this, Invalid);
  17080. Nested = true;
  17081. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  17082. Invalid = !captureInCapturedRegion(
  17083. RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
  17084. Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
  17085. Nested = true;
  17086. } else {
  17087. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  17088. Invalid =
  17089. !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  17090. DeclRefType, Nested, Kind, EllipsisLoc,
  17091. /*IsTopScope*/ I == N - 1, *this, Invalid);
  17092. Nested = true;
  17093. }
  17094. if (Invalid && !BuildAndDiagnose)
  17095. return true;
  17096. }
  17097. return Invalid;
  17098. }
  17099. bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
  17100. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  17101. QualType CaptureType;
  17102. QualType DeclRefType;
  17103. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  17104. /*BuildAndDiagnose=*/true, CaptureType,
  17105. DeclRefType, nullptr);
  17106. }
  17107. bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
  17108. QualType CaptureType;
  17109. QualType DeclRefType;
  17110. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  17111. /*BuildAndDiagnose=*/false, CaptureType,
  17112. DeclRefType, nullptr);
  17113. }
  17114. QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
  17115. QualType CaptureType;
  17116. QualType DeclRefType;
  17117. // Determine whether we can capture this variable.
  17118. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  17119. /*BuildAndDiagnose=*/false, CaptureType,
  17120. DeclRefType, nullptr))
  17121. return QualType();
  17122. return DeclRefType;
  17123. }
  17124. namespace {
  17125. // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
  17126. // The produced TemplateArgumentListInfo* points to data stored within this
  17127. // object, so should only be used in contexts where the pointer will not be
  17128. // used after the CopiedTemplateArgs object is destroyed.
  17129. class CopiedTemplateArgs {
  17130. bool HasArgs;
  17131. TemplateArgumentListInfo TemplateArgStorage;
  17132. public:
  17133. template<typename RefExpr>
  17134. CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
  17135. if (HasArgs)
  17136. E->copyTemplateArgumentsInto(TemplateArgStorage);
  17137. }
  17138. operator TemplateArgumentListInfo*()
  17139. #ifdef __has_cpp_attribute
  17140. #if __has_cpp_attribute(clang::lifetimebound)
  17141. [[clang::lifetimebound]]
  17142. #endif
  17143. #endif
  17144. {
  17145. return HasArgs ? &TemplateArgStorage : nullptr;
  17146. }
  17147. };
  17148. }
  17149. /// Walk the set of potential results of an expression and mark them all as
  17150. /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
  17151. ///
  17152. /// \return A new expression if we found any potential results, ExprEmpty() if
  17153. /// not, and ExprError() if we diagnosed an error.
  17154. static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
  17155. NonOdrUseReason NOUR) {
  17156. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  17157. // an object that satisfies the requirements for appearing in a
  17158. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  17159. // is immediately applied." This function handles the lvalue-to-rvalue
  17160. // conversion part.
  17161. //
  17162. // If we encounter a node that claims to be an odr-use but shouldn't be, we
  17163. // transform it into the relevant kind of non-odr-use node and rebuild the
  17164. // tree of nodes leading to it.
  17165. //
  17166. // This is a mini-TreeTransform that only transforms a restricted subset of
  17167. // nodes (and only certain operands of them).
  17168. // Rebuild a subexpression.
  17169. auto Rebuild = [&](Expr *Sub) {
  17170. return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
  17171. };
  17172. // Check whether a potential result satisfies the requirements of NOUR.
  17173. auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
  17174. // Any entity other than a VarDecl is always odr-used whenever it's named
  17175. // in a potentially-evaluated expression.
  17176. auto *VD = dyn_cast<VarDecl>(D);
  17177. if (!VD)
  17178. return true;
  17179. // C++2a [basic.def.odr]p4:
  17180. // A variable x whose name appears as a potentially-evalauted expression
  17181. // e is odr-used by e unless
  17182. // -- x is a reference that is usable in constant expressions, or
  17183. // -- x is a variable of non-reference type that is usable in constant
  17184. // expressions and has no mutable subobjects, and e is an element of
  17185. // the set of potential results of an expression of
  17186. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  17187. // conversion is applied, or
  17188. // -- x is a variable of non-reference type, and e is an element of the
  17189. // set of potential results of a discarded-value expression to which
  17190. // the lvalue-to-rvalue conversion is not applied
  17191. //
  17192. // We check the first bullet and the "potentially-evaluated" condition in
  17193. // BuildDeclRefExpr. We check the type requirements in the second bullet
  17194. // in CheckLValueToRValueConversionOperand below.
  17195. switch (NOUR) {
  17196. case NOUR_None:
  17197. case NOUR_Unevaluated:
  17198. llvm_unreachable("unexpected non-odr-use-reason");
  17199. case NOUR_Constant:
  17200. // Constant references were handled when they were built.
  17201. if (VD->getType()->isReferenceType())
  17202. return true;
  17203. if (auto *RD = VD->getType()->getAsCXXRecordDecl())
  17204. if (RD->hasMutableFields())
  17205. return true;
  17206. if (!VD->isUsableInConstantExpressions(S.Context))
  17207. return true;
  17208. break;
  17209. case NOUR_Discarded:
  17210. if (VD->getType()->isReferenceType())
  17211. return true;
  17212. break;
  17213. }
  17214. return false;
  17215. };
  17216. // Mark that this expression does not constitute an odr-use.
  17217. auto MarkNotOdrUsed = [&] {
  17218. S.MaybeODRUseExprs.remove(E);
  17219. if (LambdaScopeInfo *LSI = S.getCurLambda())
  17220. LSI->markVariableExprAsNonODRUsed(E);
  17221. };
  17222. // C++2a [basic.def.odr]p2:
  17223. // The set of potential results of an expression e is defined as follows:
  17224. switch (E->getStmtClass()) {
  17225. // -- If e is an id-expression, ...
  17226. case Expr::DeclRefExprClass: {
  17227. auto *DRE = cast<DeclRefExpr>(E);
  17228. if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
  17229. break;
  17230. // Rebuild as a non-odr-use DeclRefExpr.
  17231. MarkNotOdrUsed();
  17232. return DeclRefExpr::Create(
  17233. S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
  17234. DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
  17235. DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
  17236. DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
  17237. }
  17238. case Expr::FunctionParmPackExprClass: {
  17239. auto *FPPE = cast<FunctionParmPackExpr>(E);
  17240. // If any of the declarations in the pack is odr-used, then the expression
  17241. // as a whole constitutes an odr-use.
  17242. for (VarDecl *D : *FPPE)
  17243. if (IsPotentialResultOdrUsed(D))
  17244. return ExprEmpty();
  17245. // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
  17246. // nothing cares about whether we marked this as an odr-use, but it might
  17247. // be useful for non-compiler tools.
  17248. MarkNotOdrUsed();
  17249. break;
  17250. }
  17251. // -- If e is a subscripting operation with an array operand...
  17252. case Expr::ArraySubscriptExprClass: {
  17253. auto *ASE = cast<ArraySubscriptExpr>(E);
  17254. Expr *OldBase = ASE->getBase()->IgnoreImplicit();
  17255. if (!OldBase->getType()->isArrayType())
  17256. break;
  17257. ExprResult Base = Rebuild(OldBase);
  17258. if (!Base.isUsable())
  17259. return Base;
  17260. Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
  17261. Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
  17262. SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
  17263. return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
  17264. ASE->getRBracketLoc());
  17265. }
  17266. case Expr::MemberExprClass: {
  17267. auto *ME = cast<MemberExpr>(E);
  17268. // -- If e is a class member access expression [...] naming a non-static
  17269. // data member...
  17270. if (isa<FieldDecl>(ME->getMemberDecl())) {
  17271. ExprResult Base = Rebuild(ME->getBase());
  17272. if (!Base.isUsable())
  17273. return Base;
  17274. return MemberExpr::Create(
  17275. S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
  17276. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
  17277. ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
  17278. CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
  17279. ME->getObjectKind(), ME->isNonOdrUse());
  17280. }
  17281. if (ME->getMemberDecl()->isCXXInstanceMember())
  17282. break;
  17283. // -- If e is a class member access expression naming a static data member,
  17284. // ...
  17285. if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
  17286. break;
  17287. // Rebuild as a non-odr-use MemberExpr.
  17288. MarkNotOdrUsed();
  17289. return MemberExpr::Create(
  17290. S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
  17291. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
  17292. ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
  17293. ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
  17294. }
  17295. case Expr::BinaryOperatorClass: {
  17296. auto *BO = cast<BinaryOperator>(E);
  17297. Expr *LHS = BO->getLHS();
  17298. Expr *RHS = BO->getRHS();
  17299. // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
  17300. if (BO->getOpcode() == BO_PtrMemD) {
  17301. ExprResult Sub = Rebuild(LHS);
  17302. if (!Sub.isUsable())
  17303. return Sub;
  17304. LHS = Sub.get();
  17305. // -- If e is a comma expression, ...
  17306. } else if (BO->getOpcode() == BO_Comma) {
  17307. ExprResult Sub = Rebuild(RHS);
  17308. if (!Sub.isUsable())
  17309. return Sub;
  17310. RHS = Sub.get();
  17311. } else {
  17312. break;
  17313. }
  17314. return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
  17315. LHS, RHS);
  17316. }
  17317. // -- If e has the form (e1)...
  17318. case Expr::ParenExprClass: {
  17319. auto *PE = cast<ParenExpr>(E);
  17320. ExprResult Sub = Rebuild(PE->getSubExpr());
  17321. if (!Sub.isUsable())
  17322. return Sub;
  17323. return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
  17324. }
  17325. // -- If e is a glvalue conditional expression, ...
  17326. // We don't apply this to a binary conditional operator. FIXME: Should we?
  17327. case Expr::ConditionalOperatorClass: {
  17328. auto *CO = cast<ConditionalOperator>(E);
  17329. ExprResult LHS = Rebuild(CO->getLHS());
  17330. if (LHS.isInvalid())
  17331. return ExprError();
  17332. ExprResult RHS = Rebuild(CO->getRHS());
  17333. if (RHS.isInvalid())
  17334. return ExprError();
  17335. if (!LHS.isUsable() && !RHS.isUsable())
  17336. return ExprEmpty();
  17337. if (!LHS.isUsable())
  17338. LHS = CO->getLHS();
  17339. if (!RHS.isUsable())
  17340. RHS = CO->getRHS();
  17341. return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
  17342. CO->getCond(), LHS.get(), RHS.get());
  17343. }
  17344. // [Clang extension]
  17345. // -- If e has the form __extension__ e1...
  17346. case Expr::UnaryOperatorClass: {
  17347. auto *UO = cast<UnaryOperator>(E);
  17348. if (UO->getOpcode() != UO_Extension)
  17349. break;
  17350. ExprResult Sub = Rebuild(UO->getSubExpr());
  17351. if (!Sub.isUsable())
  17352. return Sub;
  17353. return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
  17354. Sub.get());
  17355. }
  17356. // [Clang extension]
  17357. // -- If e has the form _Generic(...), the set of potential results is the
  17358. // union of the sets of potential results of the associated expressions.
  17359. case Expr::GenericSelectionExprClass: {
  17360. auto *GSE = cast<GenericSelectionExpr>(E);
  17361. SmallVector<Expr *, 4> AssocExprs;
  17362. bool AnyChanged = false;
  17363. for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
  17364. ExprResult AssocExpr = Rebuild(OrigAssocExpr);
  17365. if (AssocExpr.isInvalid())
  17366. return ExprError();
  17367. if (AssocExpr.isUsable()) {
  17368. AssocExprs.push_back(AssocExpr.get());
  17369. AnyChanged = true;
  17370. } else {
  17371. AssocExprs.push_back(OrigAssocExpr);
  17372. }
  17373. }
  17374. return AnyChanged ? S.CreateGenericSelectionExpr(
  17375. GSE->getGenericLoc(), GSE->getDefaultLoc(),
  17376. GSE->getRParenLoc(), GSE->getControllingExpr(),
  17377. GSE->getAssocTypeSourceInfos(), AssocExprs)
  17378. : ExprEmpty();
  17379. }
  17380. // [Clang extension]
  17381. // -- If e has the form __builtin_choose_expr(...), the set of potential
  17382. // results is the union of the sets of potential results of the
  17383. // second and third subexpressions.
  17384. case Expr::ChooseExprClass: {
  17385. auto *CE = cast<ChooseExpr>(E);
  17386. ExprResult LHS = Rebuild(CE->getLHS());
  17387. if (LHS.isInvalid())
  17388. return ExprError();
  17389. ExprResult RHS = Rebuild(CE->getLHS());
  17390. if (RHS.isInvalid())
  17391. return ExprError();
  17392. if (!LHS.get() && !RHS.get())
  17393. return ExprEmpty();
  17394. if (!LHS.isUsable())
  17395. LHS = CE->getLHS();
  17396. if (!RHS.isUsable())
  17397. RHS = CE->getRHS();
  17398. return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
  17399. RHS.get(), CE->getRParenLoc());
  17400. }
  17401. // Step through non-syntactic nodes.
  17402. case Expr::ConstantExprClass: {
  17403. auto *CE = cast<ConstantExpr>(E);
  17404. ExprResult Sub = Rebuild(CE->getSubExpr());
  17405. if (!Sub.isUsable())
  17406. return Sub;
  17407. return ConstantExpr::Create(S.Context, Sub.get());
  17408. }
  17409. // We could mostly rely on the recursive rebuilding to rebuild implicit
  17410. // casts, but not at the top level, so rebuild them here.
  17411. case Expr::ImplicitCastExprClass: {
  17412. auto *ICE = cast<ImplicitCastExpr>(E);
  17413. // Only step through the narrow set of cast kinds we expect to encounter.
  17414. // Anything else suggests we've left the region in which potential results
  17415. // can be found.
  17416. switch (ICE->getCastKind()) {
  17417. case CK_NoOp:
  17418. case CK_DerivedToBase:
  17419. case CK_UncheckedDerivedToBase: {
  17420. ExprResult Sub = Rebuild(ICE->getSubExpr());
  17421. if (!Sub.isUsable())
  17422. return Sub;
  17423. CXXCastPath Path(ICE->path());
  17424. return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
  17425. ICE->getValueKind(), &Path);
  17426. }
  17427. default:
  17428. break;
  17429. }
  17430. break;
  17431. }
  17432. default:
  17433. break;
  17434. }
  17435. // Can't traverse through this node. Nothing to do.
  17436. return ExprEmpty();
  17437. }
  17438. ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
  17439. // Check whether the operand is or contains an object of non-trivial C union
  17440. // type.
  17441. if (E->getType().isVolatileQualified() &&
  17442. (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  17443. E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
  17444. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  17445. Sema::NTCUC_LValueToRValueVolatile,
  17446. NTCUK_Destruct|NTCUK_Copy);
  17447. // C++2a [basic.def.odr]p4:
  17448. // [...] an expression of non-volatile-qualified non-class type to which
  17449. // the lvalue-to-rvalue conversion is applied [...]
  17450. if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
  17451. return E;
  17452. ExprResult Result =
  17453. rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
  17454. if (Result.isInvalid())
  17455. return ExprError();
  17456. return Result.get() ? Result : E;
  17457. }
  17458. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  17459. Res = CorrectDelayedTyposInExpr(Res);
  17460. if (!Res.isUsable())
  17461. return Res;
  17462. // If a constant-expression is a reference to a variable where we delay
  17463. // deciding whether it is an odr-use, just assume we will apply the
  17464. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  17465. // (a non-type template argument), we have special handling anyway.
  17466. return CheckLValueToRValueConversionOperand(Res.get());
  17467. }
  17468. void Sema::CleanupVarDeclMarking() {
  17469. // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
  17470. // call.
  17471. MaybeODRUseExprSet LocalMaybeODRUseExprs;
  17472. std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
  17473. for (Expr *E : LocalMaybeODRUseExprs) {
  17474. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  17475. MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
  17476. DRE->getLocation(), *this);
  17477. } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
  17478. MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
  17479. *this);
  17480. } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
  17481. for (VarDecl *VD : *FP)
  17482. MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
  17483. } else {
  17484. llvm_unreachable("Unexpected expression");
  17485. }
  17486. }
  17487. assert(MaybeODRUseExprs.empty() &&
  17488. "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
  17489. }
  17490. static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
  17491. ValueDecl *Var, Expr *E) {
  17492. VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
  17493. if (!VD)
  17494. return;
  17495. const bool RefersToEnclosingScope =
  17496. (SemaRef.CurContext != VD->getDeclContext() &&
  17497. VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
  17498. if (RefersToEnclosingScope) {
  17499. LambdaScopeInfo *const LSI =
  17500. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  17501. if (LSI && (!LSI->CallOperator ||
  17502. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  17503. // If a variable could potentially be odr-used, defer marking it so
  17504. // until we finish analyzing the full expression for any
  17505. // lvalue-to-rvalue
  17506. // or discarded value conversions that would obviate odr-use.
  17507. // Add it to the list of potential captures that will be analyzed
  17508. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  17509. // unless the variable is a reference that was initialized by a constant
  17510. // expression (this will never need to be captured or odr-used).
  17511. //
  17512. // FIXME: We can simplify this a lot after implementing P0588R1.
  17513. assert(E && "Capture variable should be used in an expression.");
  17514. if (!Var->getType()->isReferenceType() ||
  17515. !VD->isUsableInConstantExpressions(SemaRef.Context))
  17516. LSI->addPotentialCapture(E->IgnoreParens());
  17517. }
  17518. }
  17519. }
  17520. static void DoMarkVarDeclReferenced(
  17521. Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
  17522. llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
  17523. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
  17524. isa<FunctionParmPackExpr>(E)) &&
  17525. "Invalid Expr argument to DoMarkVarDeclReferenced");
  17526. Var->setReferenced();
  17527. if (Var->isInvalidDecl())
  17528. return;
  17529. auto *MSI = Var->getMemberSpecializationInfo();
  17530. TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
  17531. : Var->getTemplateSpecializationKind();
  17532. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  17533. bool UsableInConstantExpr =
  17534. Var->mightBeUsableInConstantExpressions(SemaRef.Context);
  17535. if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
  17536. RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
  17537. }
  17538. // C++20 [expr.const]p12:
  17539. // A variable [...] is needed for constant evaluation if it is [...] a
  17540. // variable whose name appears as a potentially constant evaluated
  17541. // expression that is either a contexpr variable or is of non-volatile
  17542. // const-qualified integral type or of reference type
  17543. bool NeededForConstantEvaluation =
  17544. isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
  17545. bool NeedDefinition =
  17546. OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
  17547. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  17548. "Can't instantiate a partial template specialization.");
  17549. // If this might be a member specialization of a static data member, check
  17550. // the specialization is visible. We already did the checks for variable
  17551. // template specializations when we created them.
  17552. if (NeedDefinition && TSK != TSK_Undeclared &&
  17553. !isa<VarTemplateSpecializationDecl>(Var))
  17554. SemaRef.checkSpecializationVisibility(Loc, Var);
  17555. // Perform implicit instantiation of static data members, static data member
  17556. // templates of class templates, and variable template specializations. Delay
  17557. // instantiations of variable templates, except for those that could be used
  17558. // in a constant expression.
  17559. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  17560. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  17561. // instantiation declaration if a variable is usable in a constant
  17562. // expression (among other cases).
  17563. bool TryInstantiating =
  17564. TSK == TSK_ImplicitInstantiation ||
  17565. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  17566. if (TryInstantiating) {
  17567. SourceLocation PointOfInstantiation =
  17568. MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
  17569. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  17570. if (FirstInstantiation) {
  17571. PointOfInstantiation = Loc;
  17572. if (MSI)
  17573. MSI->setPointOfInstantiation(PointOfInstantiation);
  17574. // FIXME: Notify listener.
  17575. else
  17576. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  17577. }
  17578. if (UsableInConstantExpr) {
  17579. // Do not defer instantiations of variables that could be used in a
  17580. // constant expression.
  17581. SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
  17582. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  17583. });
  17584. // Re-set the member to trigger a recomputation of the dependence bits
  17585. // for the expression.
  17586. if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  17587. DRE->setDecl(DRE->getDecl());
  17588. else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
  17589. ME->setMemberDecl(ME->getMemberDecl());
  17590. } else if (FirstInstantiation ||
  17591. isa<VarTemplateSpecializationDecl>(Var)) {
  17592. // FIXME: For a specialization of a variable template, we don't
  17593. // distinguish between "declaration and type implicitly instantiated"
  17594. // and "implicit instantiation of definition requested", so we have
  17595. // no direct way to avoid enqueueing the pending instantiation
  17596. // multiple times.
  17597. SemaRef.PendingInstantiations
  17598. .push_back(std::make_pair(Var, PointOfInstantiation));
  17599. }
  17600. }
  17601. }
  17602. // C++2a [basic.def.odr]p4:
  17603. // A variable x whose name appears as a potentially-evaluated expression e
  17604. // is odr-used by e unless
  17605. // -- x is a reference that is usable in constant expressions
  17606. // -- x is a variable of non-reference type that is usable in constant
  17607. // expressions and has no mutable subobjects [FIXME], and e is an
  17608. // element of the set of potential results of an expression of
  17609. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  17610. // conversion is applied
  17611. // -- x is a variable of non-reference type, and e is an element of the set
  17612. // of potential results of a discarded-value expression to which the
  17613. // lvalue-to-rvalue conversion is not applied [FIXME]
  17614. //
  17615. // We check the first part of the second bullet here, and
  17616. // Sema::CheckLValueToRValueConversionOperand deals with the second part.
  17617. // FIXME: To get the third bullet right, we need to delay this even for
  17618. // variables that are not usable in constant expressions.
  17619. // If we already know this isn't an odr-use, there's nothing more to do.
  17620. if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  17621. if (DRE->isNonOdrUse())
  17622. return;
  17623. if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
  17624. if (ME->isNonOdrUse())
  17625. return;
  17626. switch (OdrUse) {
  17627. case OdrUseContext::None:
  17628. // In some cases, a variable may not have been marked unevaluated, if it
  17629. // appears in a defaukt initializer.
  17630. assert((!E || isa<FunctionParmPackExpr>(E) ||
  17631. SemaRef.isUnevaluatedContext()) &&
  17632. "missing non-odr-use marking for unevaluated decl ref");
  17633. break;
  17634. case OdrUseContext::FormallyOdrUsed:
  17635. // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
  17636. // behavior.
  17637. break;
  17638. case OdrUseContext::Used:
  17639. // If we might later find that this expression isn't actually an odr-use,
  17640. // delay the marking.
  17641. if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
  17642. SemaRef.MaybeODRUseExprs.insert(E);
  17643. else
  17644. MarkVarDeclODRUsed(Var, Loc, SemaRef);
  17645. break;
  17646. case OdrUseContext::Dependent:
  17647. // If this is a dependent context, we don't need to mark variables as
  17648. // odr-used, but we may still need to track them for lambda capture.
  17649. // FIXME: Do we also need to do this inside dependent typeid expressions
  17650. // (which are modeled as unevaluated at this point)?
  17651. DoMarkPotentialCapture(SemaRef, Loc, Var, E);
  17652. break;
  17653. }
  17654. }
  17655. static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  17656. BindingDecl *BD, Expr *E) {
  17657. BD->setReferenced();
  17658. if (BD->isInvalidDecl())
  17659. return;
  17660. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  17661. if (OdrUse == OdrUseContext::Used) {
  17662. QualType CaptureType, DeclRefType;
  17663. SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
  17664. /*EllipsisLoc*/ SourceLocation(),
  17665. /*BuildAndDiagnose*/ true, CaptureType,
  17666. DeclRefType,
  17667. /*FunctionScopeIndexToStopAt*/ nullptr);
  17668. } else if (OdrUse == OdrUseContext::Dependent) {
  17669. DoMarkPotentialCapture(SemaRef, Loc, BD, E);
  17670. }
  17671. }
  17672. /// Mark a variable referenced, and check whether it is odr-used
  17673. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  17674. /// used directly for normal expressions referring to VarDecl.
  17675. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  17676. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
  17677. }
  17678. static void
  17679. MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
  17680. bool MightBeOdrUse,
  17681. llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
  17682. if (SemaRef.isInOpenMPDeclareTargetContext())
  17683. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  17684. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  17685. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
  17686. return;
  17687. }
  17688. if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
  17689. DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
  17690. return;
  17691. }
  17692. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  17693. // If this is a call to a method via a cast, also mark the method in the
  17694. // derived class used in case codegen can devirtualize the call.
  17695. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  17696. if (!ME)
  17697. return;
  17698. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  17699. if (!MD)
  17700. return;
  17701. // Only attempt to devirtualize if this is truly a virtual call.
  17702. bool IsVirtualCall = MD->isVirtual() &&
  17703. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  17704. if (!IsVirtualCall)
  17705. return;
  17706. // If it's possible to devirtualize the call, mark the called function
  17707. // referenced.
  17708. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  17709. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  17710. if (DM)
  17711. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  17712. }
  17713. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  17714. ///
  17715. /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
  17716. /// handled with care if the DeclRefExpr is not newly-created.
  17717. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  17718. // TODO: update this with DR# once a defect report is filed.
  17719. // C++11 defect. The address of a pure member should not be an ODR use, even
  17720. // if it's a qualified reference.
  17721. bool OdrUse = true;
  17722. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  17723. if (Method->isVirtual() &&
  17724. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  17725. OdrUse = false;
  17726. if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  17727. if (!isUnevaluatedContext() && !isConstantEvaluated() &&
  17728. !isImmediateFunctionContext() &&
  17729. !isCheckingDefaultArgumentOrInitializer() && FD->isConsteval() &&
  17730. !RebuildingImmediateInvocation && !FD->isDependentContext())
  17731. ExprEvalContexts.back().ReferenceToConsteval.insert(E);
  17732. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
  17733. RefsMinusAssignments);
  17734. }
  17735. /// Perform reference-marking and odr-use handling for a MemberExpr.
  17736. void Sema::MarkMemberReferenced(MemberExpr *E) {
  17737. // C++11 [basic.def.odr]p2:
  17738. // A non-overloaded function whose name appears as a potentially-evaluated
  17739. // expression or a member of a set of candidate functions, if selected by
  17740. // overload resolution when referred to from a potentially-evaluated
  17741. // expression, is odr-used, unless it is a pure virtual function and its
  17742. // name is not explicitly qualified.
  17743. bool MightBeOdrUse = true;
  17744. if (E->performsVirtualDispatch(getLangOpts())) {
  17745. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  17746. if (Method->isPure())
  17747. MightBeOdrUse = false;
  17748. }
  17749. SourceLocation Loc =
  17750. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  17751. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
  17752. RefsMinusAssignments);
  17753. }
  17754. /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
  17755. void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
  17756. for (VarDecl *VD : *E)
  17757. MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
  17758. RefsMinusAssignments);
  17759. }
  17760. /// Perform marking for a reference to an arbitrary declaration. It
  17761. /// marks the declaration referenced, and performs odr-use checking for
  17762. /// functions and variables. This method should not be used when building a
  17763. /// normal expression which refers to a variable.
  17764. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  17765. bool MightBeOdrUse) {
  17766. if (MightBeOdrUse) {
  17767. if (auto *VD = dyn_cast<VarDecl>(D)) {
  17768. MarkVariableReferenced(Loc, VD);
  17769. return;
  17770. }
  17771. }
  17772. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  17773. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  17774. return;
  17775. }
  17776. D->setReferenced();
  17777. }
  17778. namespace {
  17779. // Mark all of the declarations used by a type as referenced.
  17780. // FIXME: Not fully implemented yet! We need to have a better understanding
  17781. // of when we're entering a context we should not recurse into.
  17782. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  17783. // TreeTransforms rebuilding the type in a new context. Rather than
  17784. // duplicating the TreeTransform logic, we should consider reusing it here.
  17785. // Currently that causes problems when rebuilding LambdaExprs.
  17786. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  17787. Sema &S;
  17788. SourceLocation Loc;
  17789. public:
  17790. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  17791. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  17792. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  17793. };
  17794. }
  17795. bool MarkReferencedDecls::TraverseTemplateArgument(
  17796. const TemplateArgument &Arg) {
  17797. {
  17798. // A non-type template argument is a constant-evaluated context.
  17799. EnterExpressionEvaluationContext Evaluated(
  17800. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  17801. if (Arg.getKind() == TemplateArgument::Declaration) {
  17802. if (Decl *D = Arg.getAsDecl())
  17803. S.MarkAnyDeclReferenced(Loc, D, true);
  17804. } else if (Arg.getKind() == TemplateArgument::Expression) {
  17805. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  17806. }
  17807. }
  17808. return Inherited::TraverseTemplateArgument(Arg);
  17809. }
  17810. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  17811. MarkReferencedDecls Marker(*this, Loc);
  17812. Marker.TraverseType(T);
  17813. }
  17814. namespace {
  17815. /// Helper class that marks all of the declarations referenced by
  17816. /// potentially-evaluated subexpressions as "referenced".
  17817. class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
  17818. public:
  17819. typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
  17820. bool SkipLocalVariables;
  17821. ArrayRef<const Expr *> StopAt;
  17822. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
  17823. ArrayRef<const Expr *> StopAt)
  17824. : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
  17825. void visitUsedDecl(SourceLocation Loc, Decl *D) {
  17826. S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
  17827. }
  17828. void Visit(Expr *E) {
  17829. if (llvm::is_contained(StopAt, E))
  17830. return;
  17831. Inherited::Visit(E);
  17832. }
  17833. void VisitConstantExpr(ConstantExpr *E) {
  17834. // Don't mark declarations within a ConstantExpression, as this expression
  17835. // will be evaluated and folded to a value.
  17836. }
  17837. void VisitDeclRefExpr(DeclRefExpr *E) {
  17838. // If we were asked not to visit local variables, don't.
  17839. if (SkipLocalVariables) {
  17840. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  17841. if (VD->hasLocalStorage())
  17842. return;
  17843. }
  17844. // FIXME: This can trigger the instantiation of the initializer of a
  17845. // variable, which can cause the expression to become value-dependent
  17846. // or error-dependent. Do we need to propagate the new dependence bits?
  17847. S.MarkDeclRefReferenced(E);
  17848. }
  17849. void VisitMemberExpr(MemberExpr *E) {
  17850. S.MarkMemberReferenced(E);
  17851. Visit(E->getBase());
  17852. }
  17853. };
  17854. } // namespace
  17855. /// Mark any declarations that appear within this expression or any
  17856. /// potentially-evaluated subexpressions as "referenced".
  17857. ///
  17858. /// \param SkipLocalVariables If true, don't mark local variables as
  17859. /// 'referenced'.
  17860. /// \param StopAt Subexpressions that we shouldn't recurse into.
  17861. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  17862. bool SkipLocalVariables,
  17863. ArrayRef<const Expr*> StopAt) {
  17864. EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
  17865. }
  17866. /// Emit a diagnostic when statements are reachable.
  17867. /// FIXME: check for reachability even in expressions for which we don't build a
  17868. /// CFG (eg, in the initializer of a global or in a constant expression).
  17869. /// For example,
  17870. /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
  17871. bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
  17872. const PartialDiagnostic &PD) {
  17873. if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
  17874. if (!FunctionScopes.empty())
  17875. FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
  17876. sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
  17877. return true;
  17878. }
  17879. // The initializer of a constexpr variable or of the first declaration of a
  17880. // static data member is not syntactically a constant evaluated constant,
  17881. // but nonetheless is always required to be a constant expression, so we
  17882. // can skip diagnosing.
  17883. // FIXME: Using the mangling context here is a hack.
  17884. if (auto *VD = dyn_cast_or_null<VarDecl>(
  17885. ExprEvalContexts.back().ManglingContextDecl)) {
  17886. if (VD->isConstexpr() ||
  17887. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  17888. return false;
  17889. // FIXME: For any other kind of variable, we should build a CFG for its
  17890. // initializer and check whether the context in question is reachable.
  17891. }
  17892. Diag(Loc, PD);
  17893. return true;
  17894. }
  17895. /// Emit a diagnostic that describes an effect on the run-time behavior
  17896. /// of the program being compiled.
  17897. ///
  17898. /// This routine emits the given diagnostic when the code currently being
  17899. /// type-checked is "potentially evaluated", meaning that there is a
  17900. /// possibility that the code will actually be executable. Code in sizeof()
  17901. /// expressions, code used only during overload resolution, etc., are not
  17902. /// potentially evaluated. This routine will suppress such diagnostics or,
  17903. /// in the absolutely nutty case of potentially potentially evaluated
  17904. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  17905. /// later.
  17906. ///
  17907. /// This routine should be used for all diagnostics that describe the run-time
  17908. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  17909. /// Failure to do so will likely result in spurious diagnostics or failures
  17910. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  17911. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
  17912. const PartialDiagnostic &PD) {
  17913. if (ExprEvalContexts.back().isDiscardedStatementContext())
  17914. return false;
  17915. switch (ExprEvalContexts.back().Context) {
  17916. case ExpressionEvaluationContext::Unevaluated:
  17917. case ExpressionEvaluationContext::UnevaluatedList:
  17918. case ExpressionEvaluationContext::UnevaluatedAbstract:
  17919. case ExpressionEvaluationContext::DiscardedStatement:
  17920. // The argument will never be evaluated, so don't complain.
  17921. break;
  17922. case ExpressionEvaluationContext::ConstantEvaluated:
  17923. case ExpressionEvaluationContext::ImmediateFunctionContext:
  17924. // Relevant diagnostics should be produced by constant evaluation.
  17925. break;
  17926. case ExpressionEvaluationContext::PotentiallyEvaluated:
  17927. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  17928. return DiagIfReachable(Loc, Stmts, PD);
  17929. }
  17930. return false;
  17931. }
  17932. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  17933. const PartialDiagnostic &PD) {
  17934. return DiagRuntimeBehavior(
  17935. Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
  17936. }
  17937. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  17938. CallExpr *CE, FunctionDecl *FD) {
  17939. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  17940. return false;
  17941. // If we're inside a decltype's expression, don't check for a valid return
  17942. // type or construct temporaries until we know whether this is the last call.
  17943. if (ExprEvalContexts.back().ExprContext ==
  17944. ExpressionEvaluationContextRecord::EK_Decltype) {
  17945. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  17946. return false;
  17947. }
  17948. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  17949. FunctionDecl *FD;
  17950. CallExpr *CE;
  17951. public:
  17952. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  17953. : FD(FD), CE(CE) { }
  17954. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  17955. if (!FD) {
  17956. S.Diag(Loc, diag::err_call_incomplete_return)
  17957. << T << CE->getSourceRange();
  17958. return;
  17959. }
  17960. S.Diag(Loc, diag::err_call_function_incomplete_return)
  17961. << CE->getSourceRange() << FD << T;
  17962. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  17963. << FD->getDeclName();
  17964. }
  17965. } Diagnoser(FD, CE);
  17966. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  17967. return true;
  17968. return false;
  17969. }
  17970. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  17971. // will prevent this condition from triggering, which is what we want.
  17972. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  17973. SourceLocation Loc;
  17974. unsigned diagnostic = diag::warn_condition_is_assignment;
  17975. bool IsOrAssign = false;
  17976. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  17977. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  17978. return;
  17979. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  17980. // Greylist some idioms by putting them into a warning subcategory.
  17981. if (ObjCMessageExpr *ME
  17982. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  17983. Selector Sel = ME->getSelector();
  17984. // self = [<foo> init...]
  17985. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  17986. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  17987. // <foo> = [<bar> nextObject]
  17988. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  17989. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  17990. }
  17991. Loc = Op->getOperatorLoc();
  17992. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  17993. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  17994. return;
  17995. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  17996. Loc = Op->getOperatorLoc();
  17997. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  17998. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  17999. else {
  18000. // Not an assignment.
  18001. return;
  18002. }
  18003. Diag(Loc, diagnostic) << E->getSourceRange();
  18004. SourceLocation Open = E->getBeginLoc();
  18005. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  18006. Diag(Loc, diag::note_condition_assign_silence)
  18007. << FixItHint::CreateInsertion(Open, "(")
  18008. << FixItHint::CreateInsertion(Close, ")");
  18009. if (IsOrAssign)
  18010. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  18011. << FixItHint::CreateReplacement(Loc, "!=");
  18012. else
  18013. Diag(Loc, diag::note_condition_assign_to_comparison)
  18014. << FixItHint::CreateReplacement(Loc, "==");
  18015. }
  18016. /// Redundant parentheses over an equality comparison can indicate
  18017. /// that the user intended an assignment used as condition.
  18018. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  18019. // Don't warn if the parens came from a macro.
  18020. SourceLocation parenLoc = ParenE->getBeginLoc();
  18021. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  18022. return;
  18023. // Don't warn for dependent expressions.
  18024. if (ParenE->isTypeDependent())
  18025. return;
  18026. Expr *E = ParenE->IgnoreParens();
  18027. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  18028. if (opE->getOpcode() == BO_EQ &&
  18029. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  18030. == Expr::MLV_Valid) {
  18031. SourceLocation Loc = opE->getOperatorLoc();
  18032. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  18033. SourceRange ParenERange = ParenE->getSourceRange();
  18034. Diag(Loc, diag::note_equality_comparison_silence)
  18035. << FixItHint::CreateRemoval(ParenERange.getBegin())
  18036. << FixItHint::CreateRemoval(ParenERange.getEnd());
  18037. Diag(Loc, diag::note_equality_comparison_to_assign)
  18038. << FixItHint::CreateReplacement(Loc, "=");
  18039. }
  18040. }
  18041. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  18042. bool IsConstexpr) {
  18043. DiagnoseAssignmentAsCondition(E);
  18044. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  18045. DiagnoseEqualityWithExtraParens(parenE);
  18046. ExprResult result = CheckPlaceholderExpr(E);
  18047. if (result.isInvalid()) return ExprError();
  18048. E = result.get();
  18049. if (!E->isTypeDependent()) {
  18050. if (getLangOpts().CPlusPlus)
  18051. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  18052. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  18053. if (ERes.isInvalid())
  18054. return ExprError();
  18055. E = ERes.get();
  18056. QualType T = E->getType();
  18057. if (!T->isScalarType()) { // C99 6.8.4.1p1
  18058. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  18059. << T << E->getSourceRange();
  18060. return ExprError();
  18061. }
  18062. CheckBoolLikeConversion(E, Loc);
  18063. }
  18064. return E;
  18065. }
  18066. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  18067. Expr *SubExpr, ConditionKind CK,
  18068. bool MissingOK) {
  18069. // MissingOK indicates whether having no condition expression is valid
  18070. // (for loop) or invalid (e.g. while loop).
  18071. if (!SubExpr)
  18072. return MissingOK ? ConditionResult() : ConditionError();
  18073. ExprResult Cond;
  18074. switch (CK) {
  18075. case ConditionKind::Boolean:
  18076. Cond = CheckBooleanCondition(Loc, SubExpr);
  18077. break;
  18078. case ConditionKind::ConstexprIf:
  18079. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  18080. break;
  18081. case ConditionKind::Switch:
  18082. Cond = CheckSwitchCondition(Loc, SubExpr);
  18083. break;
  18084. }
  18085. if (Cond.isInvalid()) {
  18086. Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
  18087. {SubExpr}, PreferredConditionType(CK));
  18088. if (!Cond.get())
  18089. return ConditionError();
  18090. }
  18091. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  18092. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  18093. if (!FullExpr.get())
  18094. return ConditionError();
  18095. return ConditionResult(*this, nullptr, FullExpr,
  18096. CK == ConditionKind::ConstexprIf);
  18097. }
  18098. namespace {
  18099. /// A visitor for rebuilding a call to an __unknown_any expression
  18100. /// to have an appropriate type.
  18101. struct RebuildUnknownAnyFunction
  18102. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  18103. Sema &S;
  18104. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  18105. ExprResult VisitStmt(Stmt *S) {
  18106. llvm_unreachable("unexpected statement!");
  18107. }
  18108. ExprResult VisitExpr(Expr *E) {
  18109. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  18110. << E->getSourceRange();
  18111. return ExprError();
  18112. }
  18113. /// Rebuild an expression which simply semantically wraps another
  18114. /// expression which it shares the type and value kind of.
  18115. template <class T> ExprResult rebuildSugarExpr(T *E) {
  18116. ExprResult SubResult = Visit(E->getSubExpr());
  18117. if (SubResult.isInvalid()) return ExprError();
  18118. Expr *SubExpr = SubResult.get();
  18119. E->setSubExpr(SubExpr);
  18120. E->setType(SubExpr->getType());
  18121. E->setValueKind(SubExpr->getValueKind());
  18122. assert(E->getObjectKind() == OK_Ordinary);
  18123. return E;
  18124. }
  18125. ExprResult VisitParenExpr(ParenExpr *E) {
  18126. return rebuildSugarExpr(E);
  18127. }
  18128. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  18129. return rebuildSugarExpr(E);
  18130. }
  18131. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  18132. ExprResult SubResult = Visit(E->getSubExpr());
  18133. if (SubResult.isInvalid()) return ExprError();
  18134. Expr *SubExpr = SubResult.get();
  18135. E->setSubExpr(SubExpr);
  18136. E->setType(S.Context.getPointerType(SubExpr->getType()));
  18137. assert(E->isPRValue());
  18138. assert(E->getObjectKind() == OK_Ordinary);
  18139. return E;
  18140. }
  18141. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  18142. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  18143. E->setType(VD->getType());
  18144. assert(E->isPRValue());
  18145. if (S.getLangOpts().CPlusPlus &&
  18146. !(isa<CXXMethodDecl>(VD) &&
  18147. cast<CXXMethodDecl>(VD)->isInstance()))
  18148. E->setValueKind(VK_LValue);
  18149. return E;
  18150. }
  18151. ExprResult VisitMemberExpr(MemberExpr *E) {
  18152. return resolveDecl(E, E->getMemberDecl());
  18153. }
  18154. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  18155. return resolveDecl(E, E->getDecl());
  18156. }
  18157. };
  18158. }
  18159. /// Given a function expression of unknown-any type, try to rebuild it
  18160. /// to have a function type.
  18161. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  18162. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  18163. if (Result.isInvalid()) return ExprError();
  18164. return S.DefaultFunctionArrayConversion(Result.get());
  18165. }
  18166. namespace {
  18167. /// A visitor for rebuilding an expression of type __unknown_anytype
  18168. /// into one which resolves the type directly on the referring
  18169. /// expression. Strict preservation of the original source
  18170. /// structure is not a goal.
  18171. struct RebuildUnknownAnyExpr
  18172. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  18173. Sema &S;
  18174. /// The current destination type.
  18175. QualType DestType;
  18176. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  18177. : S(S), DestType(CastType) {}
  18178. ExprResult VisitStmt(Stmt *S) {
  18179. llvm_unreachable("unexpected statement!");
  18180. }
  18181. ExprResult VisitExpr(Expr *E) {
  18182. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  18183. << E->getSourceRange();
  18184. return ExprError();
  18185. }
  18186. ExprResult VisitCallExpr(CallExpr *E);
  18187. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  18188. /// Rebuild an expression which simply semantically wraps another
  18189. /// expression which it shares the type and value kind of.
  18190. template <class T> ExprResult rebuildSugarExpr(T *E) {
  18191. ExprResult SubResult = Visit(E->getSubExpr());
  18192. if (SubResult.isInvalid()) return ExprError();
  18193. Expr *SubExpr = SubResult.get();
  18194. E->setSubExpr(SubExpr);
  18195. E->setType(SubExpr->getType());
  18196. E->setValueKind(SubExpr->getValueKind());
  18197. assert(E->getObjectKind() == OK_Ordinary);
  18198. return E;
  18199. }
  18200. ExprResult VisitParenExpr(ParenExpr *E) {
  18201. return rebuildSugarExpr(E);
  18202. }
  18203. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  18204. return rebuildSugarExpr(E);
  18205. }
  18206. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  18207. const PointerType *Ptr = DestType->getAs<PointerType>();
  18208. if (!Ptr) {
  18209. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  18210. << E->getSourceRange();
  18211. return ExprError();
  18212. }
  18213. if (isa<CallExpr>(E->getSubExpr())) {
  18214. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  18215. << E->getSourceRange();
  18216. return ExprError();
  18217. }
  18218. assert(E->isPRValue());
  18219. assert(E->getObjectKind() == OK_Ordinary);
  18220. E->setType(DestType);
  18221. // Build the sub-expression as if it were an object of the pointee type.
  18222. DestType = Ptr->getPointeeType();
  18223. ExprResult SubResult = Visit(E->getSubExpr());
  18224. if (SubResult.isInvalid()) return ExprError();
  18225. E->setSubExpr(SubResult.get());
  18226. return E;
  18227. }
  18228. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  18229. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  18230. ExprResult VisitMemberExpr(MemberExpr *E) {
  18231. return resolveDecl(E, E->getMemberDecl());
  18232. }
  18233. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  18234. return resolveDecl(E, E->getDecl());
  18235. }
  18236. };
  18237. }
  18238. /// Rebuilds a call expression which yielded __unknown_anytype.
  18239. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  18240. Expr *CalleeExpr = E->getCallee();
  18241. enum FnKind {
  18242. FK_MemberFunction,
  18243. FK_FunctionPointer,
  18244. FK_BlockPointer
  18245. };
  18246. FnKind Kind;
  18247. QualType CalleeType = CalleeExpr->getType();
  18248. if (CalleeType == S.Context.BoundMemberTy) {
  18249. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  18250. Kind = FK_MemberFunction;
  18251. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  18252. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  18253. CalleeType = Ptr->getPointeeType();
  18254. Kind = FK_FunctionPointer;
  18255. } else {
  18256. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  18257. Kind = FK_BlockPointer;
  18258. }
  18259. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  18260. // Verify that this is a legal result type of a function.
  18261. if (DestType->isArrayType() || DestType->isFunctionType()) {
  18262. unsigned diagID = diag::err_func_returning_array_function;
  18263. if (Kind == FK_BlockPointer)
  18264. diagID = diag::err_block_returning_array_function;
  18265. S.Diag(E->getExprLoc(), diagID)
  18266. << DestType->isFunctionType() << DestType;
  18267. return ExprError();
  18268. }
  18269. // Otherwise, go ahead and set DestType as the call's result.
  18270. E->setType(DestType.getNonLValueExprType(S.Context));
  18271. E->setValueKind(Expr::getValueKindForType(DestType));
  18272. assert(E->getObjectKind() == OK_Ordinary);
  18273. // Rebuild the function type, replacing the result type with DestType.
  18274. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  18275. if (Proto) {
  18276. // __unknown_anytype(...) is a special case used by the debugger when
  18277. // it has no idea what a function's signature is.
  18278. //
  18279. // We want to build this call essentially under the K&R
  18280. // unprototyped rules, but making a FunctionNoProtoType in C++
  18281. // would foul up all sorts of assumptions. However, we cannot
  18282. // simply pass all arguments as variadic arguments, nor can we
  18283. // portably just call the function under a non-variadic type; see
  18284. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  18285. // However, it turns out that in practice it is generally safe to
  18286. // call a function declared as "A foo(B,C,D);" under the prototype
  18287. // "A foo(B,C,D,...);". The only known exception is with the
  18288. // Windows ABI, where any variadic function is implicitly cdecl
  18289. // regardless of its normal CC. Therefore we change the parameter
  18290. // types to match the types of the arguments.
  18291. //
  18292. // This is a hack, but it is far superior to moving the
  18293. // corresponding target-specific code from IR-gen to Sema/AST.
  18294. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  18295. SmallVector<QualType, 8> ArgTypes;
  18296. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  18297. ArgTypes.reserve(E->getNumArgs());
  18298. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  18299. ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
  18300. }
  18301. ParamTypes = ArgTypes;
  18302. }
  18303. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  18304. Proto->getExtProtoInfo());
  18305. } else {
  18306. DestType = S.Context.getFunctionNoProtoType(DestType,
  18307. FnType->getExtInfo());
  18308. }
  18309. // Rebuild the appropriate pointer-to-function type.
  18310. switch (Kind) {
  18311. case FK_MemberFunction:
  18312. // Nothing to do.
  18313. break;
  18314. case FK_FunctionPointer:
  18315. DestType = S.Context.getPointerType(DestType);
  18316. break;
  18317. case FK_BlockPointer:
  18318. DestType = S.Context.getBlockPointerType(DestType);
  18319. break;
  18320. }
  18321. // Finally, we can recurse.
  18322. ExprResult CalleeResult = Visit(CalleeExpr);
  18323. if (!CalleeResult.isUsable()) return ExprError();
  18324. E->setCallee(CalleeResult.get());
  18325. // Bind a temporary if necessary.
  18326. return S.MaybeBindToTemporary(E);
  18327. }
  18328. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  18329. // Verify that this is a legal result type of a call.
  18330. if (DestType->isArrayType() || DestType->isFunctionType()) {
  18331. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  18332. << DestType->isFunctionType() << DestType;
  18333. return ExprError();
  18334. }
  18335. // Rewrite the method result type if available.
  18336. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  18337. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  18338. Method->setReturnType(DestType);
  18339. }
  18340. // Change the type of the message.
  18341. E->setType(DestType.getNonReferenceType());
  18342. E->setValueKind(Expr::getValueKindForType(DestType));
  18343. return S.MaybeBindToTemporary(E);
  18344. }
  18345. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  18346. // The only case we should ever see here is a function-to-pointer decay.
  18347. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  18348. assert(E->isPRValue());
  18349. assert(E->getObjectKind() == OK_Ordinary);
  18350. E->setType(DestType);
  18351. // Rebuild the sub-expression as the pointee (function) type.
  18352. DestType = DestType->castAs<PointerType>()->getPointeeType();
  18353. ExprResult Result = Visit(E->getSubExpr());
  18354. if (!Result.isUsable()) return ExprError();
  18355. E->setSubExpr(Result.get());
  18356. return E;
  18357. } else if (E->getCastKind() == CK_LValueToRValue) {
  18358. assert(E->isPRValue());
  18359. assert(E->getObjectKind() == OK_Ordinary);
  18360. assert(isa<BlockPointerType>(E->getType()));
  18361. E->setType(DestType);
  18362. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  18363. DestType = S.Context.getLValueReferenceType(DestType);
  18364. ExprResult Result = Visit(E->getSubExpr());
  18365. if (!Result.isUsable()) return ExprError();
  18366. E->setSubExpr(Result.get());
  18367. return E;
  18368. } else {
  18369. llvm_unreachable("Unhandled cast type!");
  18370. }
  18371. }
  18372. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  18373. ExprValueKind ValueKind = VK_LValue;
  18374. QualType Type = DestType;
  18375. // We know how to make this work for certain kinds of decls:
  18376. // - functions
  18377. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  18378. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  18379. DestType = Ptr->getPointeeType();
  18380. ExprResult Result = resolveDecl(E, VD);
  18381. if (Result.isInvalid()) return ExprError();
  18382. return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
  18383. VK_PRValue);
  18384. }
  18385. if (!Type->isFunctionType()) {
  18386. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  18387. << VD << E->getSourceRange();
  18388. return ExprError();
  18389. }
  18390. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  18391. // We must match the FunctionDecl's type to the hack introduced in
  18392. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  18393. // type. See the lengthy commentary in that routine.
  18394. QualType FDT = FD->getType();
  18395. const FunctionType *FnType = FDT->castAs<FunctionType>();
  18396. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  18397. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  18398. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  18399. SourceLocation Loc = FD->getLocation();
  18400. FunctionDecl *NewFD = FunctionDecl::Create(
  18401. S.Context, FD->getDeclContext(), Loc, Loc,
  18402. FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
  18403. SC_None, S.getCurFPFeatures().isFPConstrained(),
  18404. false /*isInlineSpecified*/, FD->hasPrototype(),
  18405. /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
  18406. if (FD->getQualifier())
  18407. NewFD->setQualifierInfo(FD->getQualifierLoc());
  18408. SmallVector<ParmVarDecl*, 16> Params;
  18409. for (const auto &AI : FT->param_types()) {
  18410. ParmVarDecl *Param =
  18411. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  18412. Param->setScopeInfo(0, Params.size());
  18413. Params.push_back(Param);
  18414. }
  18415. NewFD->setParams(Params);
  18416. DRE->setDecl(NewFD);
  18417. VD = DRE->getDecl();
  18418. }
  18419. }
  18420. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  18421. if (MD->isInstance()) {
  18422. ValueKind = VK_PRValue;
  18423. Type = S.Context.BoundMemberTy;
  18424. }
  18425. // Function references aren't l-values in C.
  18426. if (!S.getLangOpts().CPlusPlus)
  18427. ValueKind = VK_PRValue;
  18428. // - variables
  18429. } else if (isa<VarDecl>(VD)) {
  18430. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  18431. Type = RefTy->getPointeeType();
  18432. } else if (Type->isFunctionType()) {
  18433. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  18434. << VD << E->getSourceRange();
  18435. return ExprError();
  18436. }
  18437. // - nothing else
  18438. } else {
  18439. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  18440. << VD << E->getSourceRange();
  18441. return ExprError();
  18442. }
  18443. // Modifying the declaration like this is friendly to IR-gen but
  18444. // also really dangerous.
  18445. VD->setType(DestType);
  18446. E->setType(Type);
  18447. E->setValueKind(ValueKind);
  18448. return E;
  18449. }
  18450. /// Check a cast of an unknown-any type. We intentionally only
  18451. /// trigger this for C-style casts.
  18452. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  18453. Expr *CastExpr, CastKind &CastKind,
  18454. ExprValueKind &VK, CXXCastPath &Path) {
  18455. // The type we're casting to must be either void or complete.
  18456. if (!CastType->isVoidType() &&
  18457. RequireCompleteType(TypeRange.getBegin(), CastType,
  18458. diag::err_typecheck_cast_to_incomplete))
  18459. return ExprError();
  18460. // Rewrite the casted expression from scratch.
  18461. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  18462. if (!result.isUsable()) return ExprError();
  18463. CastExpr = result.get();
  18464. VK = CastExpr->getValueKind();
  18465. CastKind = CK_NoOp;
  18466. return CastExpr;
  18467. }
  18468. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  18469. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  18470. }
  18471. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  18472. Expr *arg, QualType &paramType) {
  18473. // If the syntactic form of the argument is not an explicit cast of
  18474. // any sort, just do default argument promotion.
  18475. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  18476. if (!castArg) {
  18477. ExprResult result = DefaultArgumentPromotion(arg);
  18478. if (result.isInvalid()) return ExprError();
  18479. paramType = result.get()->getType();
  18480. return result;
  18481. }
  18482. // Otherwise, use the type that was written in the explicit cast.
  18483. assert(!arg->hasPlaceholderType());
  18484. paramType = castArg->getTypeAsWritten();
  18485. // Copy-initialize a parameter of that type.
  18486. InitializedEntity entity =
  18487. InitializedEntity::InitializeParameter(Context, paramType,
  18488. /*consumed*/ false);
  18489. return PerformCopyInitialization(entity, callLoc, arg);
  18490. }
  18491. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  18492. Expr *orig = E;
  18493. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  18494. while (true) {
  18495. E = E->IgnoreParenImpCasts();
  18496. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  18497. E = call->getCallee();
  18498. diagID = diag::err_uncasted_call_of_unknown_any;
  18499. } else {
  18500. break;
  18501. }
  18502. }
  18503. SourceLocation loc;
  18504. NamedDecl *d;
  18505. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  18506. loc = ref->getLocation();
  18507. d = ref->getDecl();
  18508. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  18509. loc = mem->getMemberLoc();
  18510. d = mem->getMemberDecl();
  18511. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  18512. diagID = diag::err_uncasted_call_of_unknown_any;
  18513. loc = msg->getSelectorStartLoc();
  18514. d = msg->getMethodDecl();
  18515. if (!d) {
  18516. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  18517. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  18518. << orig->getSourceRange();
  18519. return ExprError();
  18520. }
  18521. } else {
  18522. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  18523. << E->getSourceRange();
  18524. return ExprError();
  18525. }
  18526. S.Diag(loc, diagID) << d << orig->getSourceRange();
  18527. // Never recoverable.
  18528. return ExprError();
  18529. }
  18530. /// Check for operands with placeholder types and complain if found.
  18531. /// Returns ExprError() if there was an error and no recovery was possible.
  18532. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  18533. if (!Context.isDependenceAllowed()) {
  18534. // C cannot handle TypoExpr nodes on either side of a binop because it
  18535. // doesn't handle dependent types properly, so make sure any TypoExprs have
  18536. // been dealt with before checking the operands.
  18537. ExprResult Result = CorrectDelayedTyposInExpr(E);
  18538. if (!Result.isUsable()) return ExprError();
  18539. E = Result.get();
  18540. }
  18541. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  18542. if (!placeholderType) return E;
  18543. switch (placeholderType->getKind()) {
  18544. // Overloaded expressions.
  18545. case BuiltinType::Overload: {
  18546. // Try to resolve a single function template specialization.
  18547. // This is obligatory.
  18548. ExprResult Result = E;
  18549. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  18550. return Result;
  18551. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  18552. // leaves Result unchanged on failure.
  18553. Result = E;
  18554. if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
  18555. return Result;
  18556. // If that failed, try to recover with a call.
  18557. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  18558. /*complain*/ true);
  18559. return Result;
  18560. }
  18561. // Bound member functions.
  18562. case BuiltinType::BoundMember: {
  18563. ExprResult result = E;
  18564. const Expr *BME = E->IgnoreParens();
  18565. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  18566. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  18567. if (isa<CXXPseudoDestructorExpr>(BME)) {
  18568. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  18569. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  18570. if (ME->getMemberNameInfo().getName().getNameKind() ==
  18571. DeclarationName::CXXDestructorName)
  18572. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  18573. }
  18574. tryToRecoverWithCall(result, PD,
  18575. /*complain*/ true);
  18576. return result;
  18577. }
  18578. // ARC unbridged casts.
  18579. case BuiltinType::ARCUnbridgedCast: {
  18580. Expr *realCast = stripARCUnbridgedCast(E);
  18581. diagnoseARCUnbridgedCast(realCast);
  18582. return realCast;
  18583. }
  18584. // Expressions of unknown type.
  18585. case BuiltinType::UnknownAny:
  18586. return diagnoseUnknownAnyExpr(*this, E);
  18587. // Pseudo-objects.
  18588. case BuiltinType::PseudoObject:
  18589. return checkPseudoObjectRValue(E);
  18590. case BuiltinType::BuiltinFn: {
  18591. // Accept __noop without parens by implicitly converting it to a call expr.
  18592. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  18593. if (DRE) {
  18594. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  18595. unsigned BuiltinID = FD->getBuiltinID();
  18596. if (BuiltinID == Builtin::BI__noop) {
  18597. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  18598. CK_BuiltinFnToFnPtr)
  18599. .get();
  18600. return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
  18601. VK_PRValue, SourceLocation(),
  18602. FPOptionsOverride());
  18603. }
  18604. if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
  18605. // Any use of these other than a direct call is ill-formed as of C++20,
  18606. // because they are not addressable functions. In earlier language
  18607. // modes, warn and force an instantiation of the real body.
  18608. Diag(E->getBeginLoc(),
  18609. getLangOpts().CPlusPlus20
  18610. ? diag::err_use_of_unaddressable_function
  18611. : diag::warn_cxx20_compat_use_of_unaddressable_function);
  18612. if (FD->isImplicitlyInstantiable()) {
  18613. // Require a definition here because a normal attempt at
  18614. // instantiation for a builtin will be ignored, and we won't try
  18615. // again later. We assume that the definition of the template
  18616. // precedes this use.
  18617. InstantiateFunctionDefinition(E->getBeginLoc(), FD,
  18618. /*Recursive=*/false,
  18619. /*DefinitionRequired=*/true,
  18620. /*AtEndOfTU=*/false);
  18621. }
  18622. // Produce a properly-typed reference to the function.
  18623. CXXScopeSpec SS;
  18624. SS.Adopt(DRE->getQualifierLoc());
  18625. TemplateArgumentListInfo TemplateArgs;
  18626. DRE->copyTemplateArgumentsInto(TemplateArgs);
  18627. return BuildDeclRefExpr(
  18628. FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
  18629. DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
  18630. DRE->getTemplateKeywordLoc(),
  18631. DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
  18632. }
  18633. }
  18634. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  18635. return ExprError();
  18636. }
  18637. case BuiltinType::IncompleteMatrixIdx:
  18638. Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
  18639. ->getRowIdx()
  18640. ->getBeginLoc(),
  18641. diag::err_matrix_incomplete_index);
  18642. return ExprError();
  18643. // Expressions of unknown type.
  18644. case BuiltinType::OMPArraySection:
  18645. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  18646. return ExprError();
  18647. // Expressions of unknown type.
  18648. case BuiltinType::OMPArrayShaping:
  18649. return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
  18650. case BuiltinType::OMPIterator:
  18651. return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
  18652. // Everything else should be impossible.
  18653. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  18654. case BuiltinType::Id:
  18655. #include "clang/Basic/OpenCLImageTypes.def"
  18656. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  18657. case BuiltinType::Id:
  18658. #include "clang/Basic/OpenCLExtensionTypes.def"
  18659. #define SVE_TYPE(Name, Id, SingletonId) \
  18660. case BuiltinType::Id:
  18661. #include "clang/Basic/AArch64SVEACLETypes.def"
  18662. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  18663. case BuiltinType::Id:
  18664. #include "clang/Basic/PPCTypes.def"
  18665. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  18666. #include "clang/Basic/RISCVVTypes.def"
  18667. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  18668. #define PLACEHOLDER_TYPE(Id, SingletonId)
  18669. #include "clang/AST/BuiltinTypes.def"
  18670. break;
  18671. }
  18672. llvm_unreachable("invalid placeholder type!");
  18673. }
  18674. bool Sema::CheckCaseExpression(Expr *E) {
  18675. if (E->isTypeDependent())
  18676. return true;
  18677. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  18678. return E->getType()->isIntegralOrEnumerationType();
  18679. return false;
  18680. }
  18681. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  18682. ExprResult
  18683. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  18684. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  18685. "Unknown Objective-C Boolean value!");
  18686. QualType BoolT = Context.ObjCBuiltinBoolTy;
  18687. if (!Context.getBOOLDecl()) {
  18688. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  18689. Sema::LookupOrdinaryName);
  18690. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  18691. NamedDecl *ND = Result.getFoundDecl();
  18692. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  18693. Context.setBOOLDecl(TD);
  18694. }
  18695. }
  18696. if (Context.getBOOLDecl())
  18697. BoolT = Context.getBOOLType();
  18698. return new (Context)
  18699. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  18700. }
  18701. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  18702. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  18703. SourceLocation RParen) {
  18704. auto FindSpecVersion =
  18705. [&](StringRef Platform) -> std::optional<VersionTuple> {
  18706. auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  18707. return Spec.getPlatform() == Platform;
  18708. });
  18709. // Transcribe the "ios" availability check to "maccatalyst" when compiling
  18710. // for "maccatalyst" if "maccatalyst" is not specified.
  18711. if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
  18712. Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  18713. return Spec.getPlatform() == "ios";
  18714. });
  18715. }
  18716. if (Spec == AvailSpecs.end())
  18717. return std::nullopt;
  18718. return Spec->getVersion();
  18719. };
  18720. VersionTuple Version;
  18721. if (auto MaybeVersion =
  18722. FindSpecVersion(Context.getTargetInfo().getPlatformName()))
  18723. Version = *MaybeVersion;
  18724. // The use of `@available` in the enclosing context should be analyzed to
  18725. // warn when it's used inappropriately (i.e. not if(@available)).
  18726. if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
  18727. Context->HasPotentialAvailabilityViolations = true;
  18728. return new (Context)
  18729. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  18730. }
  18731. ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
  18732. ArrayRef<Expr *> SubExprs, QualType T) {
  18733. if (!Context.getLangOpts().RecoveryAST)
  18734. return ExprError();
  18735. if (isSFINAEContext())
  18736. return ExprError();
  18737. if (T.isNull() || T->isUndeducedType() ||
  18738. !Context.getLangOpts().RecoveryASTType)
  18739. // We don't know the concrete type, fallback to dependent type.
  18740. T = Context.DependentTy;
  18741. return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
  18742. }